babylon.no-module.max.js 5.7 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226
  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. * It is recommended to use executeWhenCompile() or to make sure that scene.isReady() is called to get this observable raised.
  153. */
  154. this.onCompileObservable = new BABYLON.Observable();
  155. /**
  156. * Observable that will be called if an error occurs during shader compilation.
  157. */
  158. this.onErrorObservable = new BABYLON.Observable();
  159. /** @hidden */
  160. this._bonesComputationForcedToCPU = false;
  161. this._uniformBuffersNames = {};
  162. this._isReady = false;
  163. this._compilationError = "";
  164. this.name = baseName;
  165. if (attributesNamesOrOptions.attributes) {
  166. var options = attributesNamesOrOptions;
  167. this._engine = uniformsNamesOrEngine;
  168. this._attributesNames = options.attributes;
  169. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  170. this._samplers = options.samplers.slice();
  171. this.defines = options.defines;
  172. this.onError = options.onError;
  173. this.onCompiled = options.onCompiled;
  174. this._fallbacks = options.fallbacks;
  175. this._indexParameters = options.indexParameters;
  176. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  177. if (options.uniformBuffersNames) {
  178. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  179. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  180. }
  181. }
  182. }
  183. else {
  184. this._engine = engine;
  185. this.defines = defines;
  186. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  187. this._samplers = samplers ? samplers.slice() : [];
  188. this._attributesNames = attributesNamesOrOptions;
  189. this.onError = onError;
  190. this.onCompiled = onCompiled;
  191. this._indexParameters = indexParameters;
  192. this._fallbacks = fallbacks;
  193. }
  194. this.uniqueId = Effect._uniqueIdSeed++;
  195. var vertexSource;
  196. var fragmentSource;
  197. if (baseName.vertexElement) {
  198. vertexSource = document.getElementById(baseName.vertexElement);
  199. if (!vertexSource) {
  200. vertexSource = baseName.vertexElement;
  201. }
  202. }
  203. else {
  204. vertexSource = baseName.vertex || baseName;
  205. }
  206. if (baseName.fragmentElement) {
  207. fragmentSource = document.getElementById(baseName.fragmentElement);
  208. if (!fragmentSource) {
  209. fragmentSource = baseName.fragmentElement;
  210. }
  211. }
  212. else {
  213. fragmentSource = baseName.fragment || baseName;
  214. }
  215. this._loadVertexShader(vertexSource, function (vertexCode) {
  216. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  217. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  218. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  219. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  220. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  221. if (baseName) {
  222. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  223. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  224. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  225. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  226. }
  227. else {
  228. _this._vertexSourceCode = migratedVertexCode;
  229. _this._fragmentSourceCode = migratedFragmentCode;
  230. }
  231. _this._prepareEffect();
  232. });
  233. });
  234. });
  235. });
  236. });
  237. });
  238. }
  239. Object.defineProperty(Effect.prototype, "onBindObservable", {
  240. /**
  241. * Observable that will be called when effect is bound.
  242. */
  243. get: function () {
  244. if (!this._onBindObservable) {
  245. this._onBindObservable = new BABYLON.Observable();
  246. }
  247. return this._onBindObservable;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. Object.defineProperty(Effect.prototype, "key", {
  253. /**
  254. * Unique key for this effect
  255. */
  256. get: function () {
  257. return this._key;
  258. },
  259. enumerable: true,
  260. configurable: true
  261. });
  262. /**
  263. * If the effect has been compiled and prepared.
  264. * @returns if the effect is compiled and prepared.
  265. */
  266. Effect.prototype.isReady = function () {
  267. if (!this._isReady && this._program && this._program.isParallelCompiled) {
  268. return this._engine._isProgramCompiled(this._program);
  269. }
  270. return this._isReady;
  271. };
  272. /**
  273. * The engine the effect was initialized with.
  274. * @returns the engine.
  275. */
  276. Effect.prototype.getEngine = function () {
  277. return this._engine;
  278. };
  279. /**
  280. * The compiled webGL program for the effect
  281. * @returns the webGL program.
  282. */
  283. Effect.prototype.getProgram = function () {
  284. return this._program;
  285. };
  286. /**
  287. * The set of names of attribute variables for the shader.
  288. * @returns An array of attribute names.
  289. */
  290. Effect.prototype.getAttributesNames = function () {
  291. return this._attributesNames;
  292. };
  293. /**
  294. * Returns the attribute at the given index.
  295. * @param index The index of the attribute.
  296. * @returns The location of the attribute.
  297. */
  298. Effect.prototype.getAttributeLocation = function (index) {
  299. return this._attributes[index];
  300. };
  301. /**
  302. * Returns the attribute based on the name of the variable.
  303. * @param name of the attribute to look up.
  304. * @returns the attribute location.
  305. */
  306. Effect.prototype.getAttributeLocationByName = function (name) {
  307. var index = this._attributesNames.indexOf(name);
  308. return this._attributes[index];
  309. };
  310. /**
  311. * The number of attributes.
  312. * @returns the numnber of attributes.
  313. */
  314. Effect.prototype.getAttributesCount = function () {
  315. return this._attributes.length;
  316. };
  317. /**
  318. * Gets the index of a uniform variable.
  319. * @param uniformName of the uniform to look up.
  320. * @returns the index.
  321. */
  322. Effect.prototype.getUniformIndex = function (uniformName) {
  323. return this._uniformsNames.indexOf(uniformName);
  324. };
  325. /**
  326. * Returns the attribute based on the name of the variable.
  327. * @param uniformName of the uniform to look up.
  328. * @returns the location of the uniform.
  329. */
  330. Effect.prototype.getUniform = function (uniformName) {
  331. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  332. };
  333. /**
  334. * Returns an array of sampler variable names
  335. * @returns The array of sampler variable neames.
  336. */
  337. Effect.prototype.getSamplers = function () {
  338. return this._samplers;
  339. };
  340. /**
  341. * The error from the last compilation.
  342. * @returns the error string.
  343. */
  344. Effect.prototype.getCompilationError = function () {
  345. return this._compilationError;
  346. };
  347. /**
  348. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  349. * @param func The callback to be used.
  350. */
  351. Effect.prototype.executeWhenCompiled = function (func) {
  352. var _this = this;
  353. if (this.isReady()) {
  354. func(this);
  355. return;
  356. }
  357. this.onCompileObservable.add(function (effect) {
  358. func(effect);
  359. });
  360. if (!this._program || this._program.isParallelCompiled) {
  361. setTimeout(function () {
  362. _this._checkIsReady();
  363. }, 16);
  364. }
  365. };
  366. Effect.prototype._checkIsReady = function () {
  367. var _this = this;
  368. if (this.isReady()) {
  369. return;
  370. }
  371. setTimeout(function () {
  372. _this._checkIsReady();
  373. }, 16);
  374. };
  375. /** @hidden */
  376. Effect.prototype._loadVertexShader = function (vertex, callback) {
  377. if (BABYLON.Tools.IsWindowObjectExist()) {
  378. // DOM element ?
  379. if (vertex instanceof HTMLElement) {
  380. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  381. callback(vertexCode);
  382. return;
  383. }
  384. }
  385. // Base64 encoded ?
  386. if (vertex.substr(0, 7) === "base64:") {
  387. var vertexBinary = window.atob(vertex.substr(7));
  388. callback(vertexBinary);
  389. return;
  390. }
  391. // Is in local store ?
  392. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  393. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  394. return;
  395. }
  396. var vertexShaderUrl;
  397. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  398. vertexShaderUrl = vertex;
  399. }
  400. else {
  401. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  402. }
  403. // Vertex shader
  404. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  405. };
  406. /** @hidden */
  407. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  408. if (BABYLON.Tools.IsWindowObjectExist()) {
  409. // DOM element ?
  410. if (fragment instanceof HTMLElement) {
  411. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  412. callback(fragmentCode);
  413. return;
  414. }
  415. }
  416. // Base64 encoded ?
  417. if (fragment.substr(0, 7) === "base64:") {
  418. var fragmentBinary = window.atob(fragment.substr(7));
  419. callback(fragmentBinary);
  420. return;
  421. }
  422. // Is in local store ?
  423. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  424. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  425. return;
  426. }
  427. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  428. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  429. return;
  430. }
  431. var fragmentShaderUrl;
  432. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  433. fragmentShaderUrl = fragment;
  434. }
  435. else {
  436. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  437. }
  438. // Fragment shader
  439. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  440. };
  441. /** @hidden */
  442. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  443. // Rebuild shaders source code
  444. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  445. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  446. vertexCode = prefix + vertexCode;
  447. fragmentCode = prefix + fragmentCode;
  448. // Number lines of shaders source code
  449. var i = 2;
  450. var regex = /\n/gm;
  451. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  452. i = 2;
  453. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  454. // Dump shaders name and formatted source code
  455. if (this.name.vertexElement) {
  456. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  457. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  458. }
  459. else if (this.name.vertex) {
  460. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  461. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  462. }
  463. else {
  464. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  465. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  466. }
  467. };
  468. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  469. var preparedSourceCode = this._processPrecision(sourceCode);
  470. if (this._engine.webGLVersion == 1) {
  471. callback(preparedSourceCode);
  472. return;
  473. }
  474. // Already converted
  475. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  476. callback(preparedSourceCode.replace("#version 300 es", ""));
  477. return;
  478. }
  479. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  480. // Remove extensions
  481. // #extension GL_OES_standard_derivatives : enable
  482. // #extension GL_EXT_shader_texture_lod : enable
  483. // #extension GL_EXT_frag_depth : enable
  484. // #extension GL_EXT_draw_buffers : require
  485. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  486. var result = preparedSourceCode.replace(regex, "");
  487. // Migrate to GLSL v300
  488. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  489. result = result.replace(/attribute[ \t]/g, "in ");
  490. result = result.replace(/[ \t]attribute/g, " in");
  491. result = result.replace(/texture2D\s*\(/g, "texture(");
  492. if (isFragment) {
  493. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  494. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  495. result = result.replace(/textureCube\s*\(/g, "texture(");
  496. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  497. result = result.replace(/gl_FragColor/g, "glFragColor");
  498. result = result.replace(/gl_FragData/g, "glFragData");
  499. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  500. }
  501. callback(result);
  502. };
  503. Effect.prototype._processIncludes = function (sourceCode, callback) {
  504. var _this = this;
  505. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  506. var match = regex.exec(sourceCode);
  507. var returnValue = new String(sourceCode);
  508. while (match != null) {
  509. var includeFile = match[1];
  510. // Uniform declaration
  511. if (includeFile.indexOf("__decl__") !== -1) {
  512. includeFile = includeFile.replace(/__decl__/, "");
  513. if (this._engine.supportsUniformBuffers) {
  514. includeFile = includeFile.replace(/Vertex/, "Ubo");
  515. includeFile = includeFile.replace(/Fragment/, "Ubo");
  516. }
  517. includeFile = includeFile + "Declaration";
  518. }
  519. if (Effect.IncludesShadersStore[includeFile]) {
  520. // Substitution
  521. var includeContent = Effect.IncludesShadersStore[includeFile];
  522. if (match[2]) {
  523. var splits = match[3].split(",");
  524. for (var index = 0; index < splits.length; index += 2) {
  525. var source = new RegExp(splits[index], "g");
  526. var dest = splits[index + 1];
  527. includeContent = includeContent.replace(source, dest);
  528. }
  529. }
  530. if (match[4]) {
  531. var indexString = match[5];
  532. if (indexString.indexOf("..") !== -1) {
  533. var indexSplits = indexString.split("..");
  534. var minIndex = parseInt(indexSplits[0]);
  535. var maxIndex = parseInt(indexSplits[1]);
  536. var sourceIncludeContent = includeContent.slice(0);
  537. includeContent = "";
  538. if (isNaN(maxIndex)) {
  539. maxIndex = this._indexParameters[indexSplits[1]];
  540. }
  541. for (var i = minIndex; i < maxIndex; i++) {
  542. if (!this._engine.supportsUniformBuffers) {
  543. // Ubo replacement
  544. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  545. return p1 + "{X}";
  546. });
  547. }
  548. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  549. }
  550. }
  551. else {
  552. if (!this._engine.supportsUniformBuffers) {
  553. // Ubo replacement
  554. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  555. return p1 + "{X}";
  556. });
  557. }
  558. includeContent = includeContent.replace(/\{X\}/g, indexString);
  559. }
  560. }
  561. // Replace
  562. returnValue = returnValue.replace(match[0], includeContent);
  563. }
  564. else {
  565. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  566. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  567. Effect.IncludesShadersStore[includeFile] = fileContent;
  568. _this._processIncludes(returnValue, callback);
  569. });
  570. return;
  571. }
  572. match = regex.exec(sourceCode);
  573. }
  574. callback(returnValue);
  575. };
  576. Effect.prototype._processPrecision = function (source) {
  577. if (source.indexOf("precision highp float") === -1) {
  578. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  579. source = "precision mediump float;\n" + source;
  580. }
  581. else {
  582. source = "precision highp float;\n" + source;
  583. }
  584. }
  585. else {
  586. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  587. source = source.replace("precision highp float", "precision mediump float");
  588. }
  589. }
  590. return source;
  591. };
  592. /**
  593. * Recompiles the webGL program
  594. * @param vertexSourceCode The source code for the vertex shader.
  595. * @param fragmentSourceCode The source code for the fragment shader.
  596. * @param onCompiled Callback called when completed.
  597. * @param onError Callback called on error.
  598. * @hidden
  599. */
  600. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  601. var _this = this;
  602. this._isReady = false;
  603. this._vertexSourceCodeOverride = vertexSourceCode;
  604. this._fragmentSourceCodeOverride = fragmentSourceCode;
  605. this.onError = function (effect, error) {
  606. if (onError) {
  607. onError(error);
  608. }
  609. };
  610. this.onCompiled = function () {
  611. var scenes = _this.getEngine().scenes;
  612. for (var i = 0; i < scenes.length; i++) {
  613. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  614. }
  615. if (onCompiled) {
  616. onCompiled(_this._program);
  617. }
  618. };
  619. this._fallbacks = null;
  620. this._prepareEffect();
  621. };
  622. /**
  623. * Gets the uniform locations of the the specified variable names
  624. * @param names THe names of the variables to lookup.
  625. * @returns Array of locations in the same order as variable names.
  626. */
  627. Effect.prototype.getSpecificUniformLocations = function (names) {
  628. var engine = this._engine;
  629. return engine.getUniforms(this._program, names);
  630. };
  631. /**
  632. * Prepares the effect
  633. * @hidden
  634. */
  635. Effect.prototype._prepareEffect = function () {
  636. var _this = this;
  637. var attributesNames = this._attributesNames;
  638. var defines = this.defines;
  639. var fallbacks = this._fallbacks;
  640. this._valueCache = {};
  641. var previousProgram = this._program;
  642. try {
  643. var engine_1 = this._engine;
  644. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  645. this._program = engine_1.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  646. }
  647. else {
  648. this._program = engine_1.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  649. }
  650. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  651. engine_1._executeWhenProgramIsCompiled(this._program, function () {
  652. if (engine_1.supportsUniformBuffers) {
  653. for (var name in _this._uniformBuffersNames) {
  654. _this.bindUniformBlock(name, _this._uniformBuffersNames[name]);
  655. }
  656. }
  657. _this._uniforms = engine_1.getUniforms(_this._program, _this._uniformsNames);
  658. _this._attributes = engine_1.getAttributes(_this._program, attributesNames);
  659. var index;
  660. for (index = 0; index < _this._samplers.length; index++) {
  661. var sampler = _this.getUniform(_this._samplers[index]);
  662. if (sampler == null) {
  663. _this._samplers.splice(index, 1);
  664. index--;
  665. }
  666. }
  667. engine_1.bindSamplers(_this);
  668. _this._compilationError = "";
  669. _this._isReady = true;
  670. if (_this.onCompiled) {
  671. _this.onCompiled(_this);
  672. }
  673. _this.onCompileObservable.notifyObservers(_this);
  674. _this.onCompileObservable.clear();
  675. // Unbind mesh reference in fallbacks
  676. if (_this._fallbacks) {
  677. _this._fallbacks.unBindMesh();
  678. }
  679. if (previousProgram) {
  680. _this.getEngine()._deleteProgram(previousProgram);
  681. }
  682. });
  683. if (this._program.isParallelCompiled) {
  684. this._checkIsReady();
  685. }
  686. }
  687. catch (e) {
  688. this._compilationError = e.message;
  689. // Let's go through fallbacks then
  690. BABYLON.Tools.Error("Unable to compile effect:");
  691. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  692. return " " + uniform;
  693. }));
  694. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  695. return " " + attribute;
  696. }));
  697. BABYLON.Tools.Error("Error: " + this._compilationError);
  698. if (previousProgram) {
  699. this._program = previousProgram;
  700. this._isReady = true;
  701. if (this.onError) {
  702. this.onError(this, this._compilationError);
  703. }
  704. this.onErrorObservable.notifyObservers(this);
  705. }
  706. if (fallbacks && fallbacks.isMoreFallbacks) {
  707. BABYLON.Tools.Error("Trying next fallback.");
  708. this.defines = fallbacks.reduce(this.defines, this);
  709. this._prepareEffect();
  710. }
  711. else { // Sorry we did everything we can
  712. if (this.onError) {
  713. this.onError(this, this._compilationError);
  714. }
  715. this.onErrorObservable.notifyObservers(this);
  716. this.onErrorObservable.clear();
  717. // Unbind mesh reference in fallbacks
  718. if (this._fallbacks) {
  719. this._fallbacks.unBindMesh();
  720. }
  721. }
  722. }
  723. };
  724. Object.defineProperty(Effect.prototype, "isSupported", {
  725. /**
  726. * Checks if the effect is supported. (Must be called after compilation)
  727. */
  728. get: function () {
  729. return this._compilationError === "";
  730. },
  731. enumerable: true,
  732. configurable: true
  733. });
  734. /**
  735. * Binds a texture to the engine to be used as output of the shader.
  736. * @param channel Name of the output variable.
  737. * @param texture Texture to bind.
  738. * @hidden
  739. */
  740. Effect.prototype._bindTexture = function (channel, texture) {
  741. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  742. };
  743. /**
  744. * Sets a texture on the engine to be used in the shader.
  745. * @param channel Name of the sampler variable.
  746. * @param texture Texture to set.
  747. */
  748. Effect.prototype.setTexture = function (channel, texture) {
  749. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  750. };
  751. /**
  752. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  753. * @param channel Name of the sampler variable.
  754. * @param texture Texture to set.
  755. */
  756. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  757. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  758. };
  759. /**
  760. * Sets an array of textures on the engine to be used in the shader.
  761. * @param channel Name of the variable.
  762. * @param textures Textures to set.
  763. */
  764. Effect.prototype.setTextureArray = function (channel, textures) {
  765. if (this._samplers.indexOf(channel + "Ex") === -1) {
  766. var initialPos = this._samplers.indexOf(channel);
  767. for (var index = 1; index < textures.length; index++) {
  768. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  769. }
  770. }
  771. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  772. };
  773. /**
  774. * 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)
  775. * @param channel Name of the sampler variable.
  776. * @param postProcess Post process to get the input texture from.
  777. */
  778. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  779. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  780. };
  781. /**
  782. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  783. * 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)
  784. * @param channel Name of the sampler variable.
  785. * @param postProcess Post process to get the output texture from.
  786. */
  787. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  788. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  789. };
  790. /** @hidden */
  791. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  792. var cache = this._valueCache[uniformName];
  793. var flag = matrix.updateFlag;
  794. if (cache !== undefined && cache === flag) {
  795. return false;
  796. }
  797. this._valueCache[uniformName] = flag;
  798. return true;
  799. };
  800. /** @hidden */
  801. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  802. var cache = this._valueCache[uniformName];
  803. if (!cache) {
  804. cache = [x, y];
  805. this._valueCache[uniformName] = cache;
  806. return true;
  807. }
  808. var changed = false;
  809. if (cache[0] !== x) {
  810. cache[0] = x;
  811. changed = true;
  812. }
  813. if (cache[1] !== y) {
  814. cache[1] = y;
  815. changed = true;
  816. }
  817. return changed;
  818. };
  819. /** @hidden */
  820. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  821. var cache = this._valueCache[uniformName];
  822. if (!cache) {
  823. cache = [x, y, z];
  824. this._valueCache[uniformName] = cache;
  825. return true;
  826. }
  827. var changed = false;
  828. if (cache[0] !== x) {
  829. cache[0] = x;
  830. changed = true;
  831. }
  832. if (cache[1] !== y) {
  833. cache[1] = y;
  834. changed = true;
  835. }
  836. if (cache[2] !== z) {
  837. cache[2] = z;
  838. changed = true;
  839. }
  840. return changed;
  841. };
  842. /** @hidden */
  843. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  844. var cache = this._valueCache[uniformName];
  845. if (!cache) {
  846. cache = [x, y, z, w];
  847. this._valueCache[uniformName] = cache;
  848. return true;
  849. }
  850. var changed = false;
  851. if (cache[0] !== x) {
  852. cache[0] = x;
  853. changed = true;
  854. }
  855. if (cache[1] !== y) {
  856. cache[1] = y;
  857. changed = true;
  858. }
  859. if (cache[2] !== z) {
  860. cache[2] = z;
  861. changed = true;
  862. }
  863. if (cache[3] !== w) {
  864. cache[3] = w;
  865. changed = true;
  866. }
  867. return changed;
  868. };
  869. /**
  870. * Binds a buffer to a uniform.
  871. * @param buffer Buffer to bind.
  872. * @param name Name of the uniform variable to bind to.
  873. */
  874. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  875. var bufferName = this._uniformBuffersNames[name];
  876. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  877. return;
  878. }
  879. Effect._baseCache[bufferName] = buffer;
  880. this._engine.bindUniformBufferBase(buffer, bufferName);
  881. };
  882. /**
  883. * Binds block to a uniform.
  884. * @param blockName Name of the block to bind.
  885. * @param index Index to bind.
  886. */
  887. Effect.prototype.bindUniformBlock = function (blockName, index) {
  888. this._engine.bindUniformBlock(this._program, blockName, index);
  889. };
  890. /**
  891. * Sets an interger value on a uniform variable.
  892. * @param uniformName Name of the variable.
  893. * @param value Value to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setInt = function (uniformName, value) {
  897. var cache = this._valueCache[uniformName];
  898. if (cache !== undefined && cache === value) {
  899. return this;
  900. }
  901. this._valueCache[uniformName] = value;
  902. this._engine.setInt(this.getUniform(uniformName), value);
  903. return this;
  904. };
  905. /**
  906. * Sets an int array on a uniform variable.
  907. * @param uniformName Name of the variable.
  908. * @param array array to be set.
  909. * @returns this effect.
  910. */
  911. Effect.prototype.setIntArray = function (uniformName, array) {
  912. this._valueCache[uniformName] = null;
  913. this._engine.setIntArray(this.getUniform(uniformName), array);
  914. return this;
  915. };
  916. /**
  917. * 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)
  918. * @param uniformName Name of the variable.
  919. * @param array array to be set.
  920. * @returns this effect.
  921. */
  922. Effect.prototype.setIntArray2 = function (uniformName, array) {
  923. this._valueCache[uniformName] = null;
  924. this._engine.setIntArray2(this.getUniform(uniformName), array);
  925. return this;
  926. };
  927. /**
  928. * 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)
  929. * @param uniformName Name of the variable.
  930. * @param array array to be set.
  931. * @returns this effect.
  932. */
  933. Effect.prototype.setIntArray3 = function (uniformName, array) {
  934. this._valueCache[uniformName] = null;
  935. this._engine.setIntArray3(this.getUniform(uniformName), array);
  936. return this;
  937. };
  938. /**
  939. * 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)
  940. * @param uniformName Name of the variable.
  941. * @param array array to be set.
  942. * @returns this effect.
  943. */
  944. Effect.prototype.setIntArray4 = function (uniformName, array) {
  945. this._valueCache[uniformName] = null;
  946. this._engine.setIntArray4(this.getUniform(uniformName), array);
  947. return this;
  948. };
  949. /**
  950. * Sets an float array on a uniform variable.
  951. * @param uniformName Name of the variable.
  952. * @param array array to be set.
  953. * @returns this effect.
  954. */
  955. Effect.prototype.setFloatArray = function (uniformName, array) {
  956. this._valueCache[uniformName] = null;
  957. this._engine.setFloatArray(this.getUniform(uniformName), array);
  958. return this;
  959. };
  960. /**
  961. * 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)
  962. * @param uniformName Name of the variable.
  963. * @param array array to be set.
  964. * @returns this effect.
  965. */
  966. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  967. this._valueCache[uniformName] = null;
  968. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  969. return this;
  970. };
  971. /**
  972. * 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)
  973. * @param uniformName Name of the variable.
  974. * @param array array to be set.
  975. * @returns this effect.
  976. */
  977. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  978. this._valueCache[uniformName] = null;
  979. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  980. return this;
  981. };
  982. /**
  983. * 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)
  984. * @param uniformName Name of the variable.
  985. * @param array array to be set.
  986. * @returns this effect.
  987. */
  988. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  989. this._valueCache[uniformName] = null;
  990. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  991. return this;
  992. };
  993. /**
  994. * Sets an array on a uniform variable.
  995. * @param uniformName Name of the variable.
  996. * @param array array to be set.
  997. * @returns this effect.
  998. */
  999. Effect.prototype.setArray = function (uniformName, array) {
  1000. this._valueCache[uniformName] = null;
  1001. this._engine.setArray(this.getUniform(uniformName), array);
  1002. return this;
  1003. };
  1004. /**
  1005. * 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)
  1006. * @param uniformName Name of the variable.
  1007. * @param array array to be set.
  1008. * @returns this effect.
  1009. */
  1010. Effect.prototype.setArray2 = function (uniformName, array) {
  1011. this._valueCache[uniformName] = null;
  1012. this._engine.setArray2(this.getUniform(uniformName), array);
  1013. return this;
  1014. };
  1015. /**
  1016. * 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)
  1017. * @param uniformName Name of the variable.
  1018. * @param array array to be set.
  1019. * @returns this effect.
  1020. */
  1021. Effect.prototype.setArray3 = function (uniformName, array) {
  1022. this._valueCache[uniformName] = null;
  1023. this._engine.setArray3(this.getUniform(uniformName), array);
  1024. return this;
  1025. };
  1026. /**
  1027. * 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)
  1028. * @param uniformName Name of the variable.
  1029. * @param array array to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setArray4 = function (uniformName, array) {
  1033. this._valueCache[uniformName] = null;
  1034. this._engine.setArray4(this.getUniform(uniformName), array);
  1035. return this;
  1036. };
  1037. /**
  1038. * Sets matrices on a uniform variable.
  1039. * @param uniformName Name of the variable.
  1040. * @param matrices matrices to be set.
  1041. * @returns this effect.
  1042. */
  1043. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1044. if (!matrices) {
  1045. return this;
  1046. }
  1047. this._valueCache[uniformName] = null;
  1048. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1049. return this;
  1050. };
  1051. /**
  1052. * Sets matrix on a uniform variable.
  1053. * @param uniformName Name of the variable.
  1054. * @param matrix matrix to be set.
  1055. * @returns this effect.
  1056. */
  1057. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1058. if (this._cacheMatrix(uniformName, matrix)) {
  1059. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1060. }
  1061. return this;
  1062. };
  1063. /**
  1064. * 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)
  1065. * @param uniformName Name of the variable.
  1066. * @param matrix matrix to be set.
  1067. * @returns this effect.
  1068. */
  1069. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1070. this._valueCache[uniformName] = null;
  1071. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1072. return this;
  1073. };
  1074. /**
  1075. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1076. * @param uniformName Name of the variable.
  1077. * @param matrix matrix to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1081. this._valueCache[uniformName] = null;
  1082. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1083. return this;
  1084. };
  1085. /**
  1086. * Sets a float on a uniform variable.
  1087. * @param uniformName Name of the variable.
  1088. * @param value value to be set.
  1089. * @returns this effect.
  1090. */
  1091. Effect.prototype.setFloat = function (uniformName, value) {
  1092. var cache = this._valueCache[uniformName];
  1093. if (cache !== undefined && cache === value) {
  1094. return this;
  1095. }
  1096. this._valueCache[uniformName] = value;
  1097. this._engine.setFloat(this.getUniform(uniformName), value);
  1098. return this;
  1099. };
  1100. /**
  1101. * Sets a boolean on a uniform variable.
  1102. * @param uniformName Name of the variable.
  1103. * @param bool value to be set.
  1104. * @returns this effect.
  1105. */
  1106. Effect.prototype.setBool = function (uniformName, bool) {
  1107. var cache = this._valueCache[uniformName];
  1108. if (cache !== undefined && cache === bool) {
  1109. return this;
  1110. }
  1111. this._valueCache[uniformName] = bool;
  1112. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a Vector2 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param vector2 vector2 to be set.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1122. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1123. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a float2 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param x First float in float2.
  1131. * @param y Second float in float2.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1135. if (this._cacheFloat2(uniformName, x, y)) {
  1136. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1137. }
  1138. return this;
  1139. };
  1140. /**
  1141. * Sets a Vector3 on a uniform variable.
  1142. * @param uniformName Name of the variable.
  1143. * @param vector3 Value to be set.
  1144. * @returns this effect.
  1145. */
  1146. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1147. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1148. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1149. }
  1150. return this;
  1151. };
  1152. /**
  1153. * Sets a float3 on a uniform variable.
  1154. * @param uniformName Name of the variable.
  1155. * @param x First float in float3.
  1156. * @param y Second float in float3.
  1157. * @param z Third float in float3.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1161. if (this._cacheFloat3(uniformName, x, y, z)) {
  1162. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Vector4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param vector4 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1173. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1174. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a float4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param x First float in float4.
  1182. * @param y Second float in float4.
  1183. * @param z Third float in float4.
  1184. * @param w Fourth float in float4.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1188. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1189. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color3 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param color3 Value to be set.
  1197. * @returns this effect.
  1198. */
  1199. Effect.prototype.setColor3 = function (uniformName, color3) {
  1200. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1201. this._engine.setColor3(this.getUniform(uniformName), color3);
  1202. }
  1203. return this;
  1204. };
  1205. /**
  1206. * Sets a Color4 on a uniform variable.
  1207. * @param uniformName Name of the variable.
  1208. * @param color3 Value to be set.
  1209. * @param alpha Alpha value to be set.
  1210. * @returns this effect.
  1211. */
  1212. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1213. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1214. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1215. }
  1216. return this;
  1217. };
  1218. /**
  1219. * Sets a Color4 on a uniform variable
  1220. * @param uniformName defines the name of the variable
  1221. * @param color4 defines the value to be set
  1222. * @returns this effect.
  1223. */
  1224. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1225. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1226. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1227. }
  1228. return this;
  1229. };
  1230. /**
  1231. * This function will add a new shader to the shader store
  1232. * @param name the name of the shader
  1233. * @param pixelShader optional pixel shader content
  1234. * @param vertexShader optional vertex shader content
  1235. */
  1236. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1237. if (pixelShader) {
  1238. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1239. }
  1240. if (vertexShader) {
  1241. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1242. }
  1243. };
  1244. /**
  1245. * Resets the cache of effects.
  1246. */
  1247. Effect.ResetCache = function () {
  1248. Effect._baseCache = {};
  1249. };
  1250. Effect._uniqueIdSeed = 0;
  1251. Effect._baseCache = {};
  1252. /**
  1253. * Store of each shader (The can be looked up using effect.key)
  1254. */
  1255. Effect.ShadersStore = {};
  1256. /**
  1257. * Store of each included file for a shader (The can be looked up using effect.key)
  1258. */
  1259. Effect.IncludesShadersStore = {};
  1260. return Effect;
  1261. }());
  1262. BABYLON.Effect = Effect;
  1263. })(BABYLON || (BABYLON = {}));
  1264. //# sourceMappingURL=effect.js.map
  1265. //# sourceMappingURL=types.js.map
  1266. var BABYLON;
  1267. (function (BABYLON) {
  1268. /**
  1269. * Gather the list of keyboard event types as constants.
  1270. */
  1271. var KeyboardEventTypes = /** @class */ (function () {
  1272. function KeyboardEventTypes() {
  1273. }
  1274. /**
  1275. * The keydown event is fired when a key becomes active (pressed).
  1276. */
  1277. KeyboardEventTypes.KEYDOWN = 0x01;
  1278. /**
  1279. * The keyup event is fired when a key has been released.
  1280. */
  1281. KeyboardEventTypes.KEYUP = 0x02;
  1282. return KeyboardEventTypes;
  1283. }());
  1284. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1285. /**
  1286. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1287. */
  1288. var KeyboardInfo = /** @class */ (function () {
  1289. /**
  1290. * Instantiates a new keyboard info.
  1291. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1292. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1293. * @param event Defines the related dom event
  1294. */
  1295. function KeyboardInfo(
  1296. /**
  1297. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1298. */
  1299. type,
  1300. /**
  1301. * Defines the related dom event
  1302. */
  1303. event) {
  1304. this.type = type;
  1305. this.event = event;
  1306. }
  1307. return KeyboardInfo;
  1308. }());
  1309. BABYLON.KeyboardInfo = KeyboardInfo;
  1310. /**
  1311. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1312. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1313. */
  1314. var KeyboardInfoPre = /** @class */ (function (_super) {
  1315. __extends(KeyboardInfoPre, _super);
  1316. /**
  1317. * Instantiates a new keyboard pre info.
  1318. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1319. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1320. * @param event Defines the related dom event
  1321. */
  1322. function KeyboardInfoPre(
  1323. /**
  1324. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1325. */
  1326. type,
  1327. /**
  1328. * Defines the related dom event
  1329. */
  1330. event) {
  1331. var _this = _super.call(this, type, event) || this;
  1332. _this.type = type;
  1333. _this.event = event;
  1334. _this.skipOnPointerObservable = false;
  1335. return _this;
  1336. }
  1337. return KeyboardInfoPre;
  1338. }(KeyboardInfo));
  1339. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1340. })(BABYLON || (BABYLON = {}));
  1341. //# sourceMappingURL=keyboardEvents.js.map
  1342. var BABYLON;
  1343. (function (BABYLON) {
  1344. /**
  1345. * Gather the list of pointer event types as constants.
  1346. */
  1347. var PointerEventTypes = /** @class */ (function () {
  1348. function PointerEventTypes() {
  1349. }
  1350. /**
  1351. * 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.
  1352. */
  1353. PointerEventTypes.POINTERDOWN = 0x01;
  1354. /**
  1355. * The pointerup event is fired when a pointer is no longer active.
  1356. */
  1357. PointerEventTypes.POINTERUP = 0x02;
  1358. /**
  1359. * The pointermove event is fired when a pointer changes coordinates.
  1360. */
  1361. PointerEventTypes.POINTERMOVE = 0x04;
  1362. /**
  1363. * The pointerwheel event is fired when a mouse wheel has been rotated.
  1364. */
  1365. PointerEventTypes.POINTERWHEEL = 0x08;
  1366. /**
  1367. * The pointerpick event is fired when a mesh or sprite has been picked by the pointer.
  1368. */
  1369. PointerEventTypes.POINTERPICK = 0x10;
  1370. /**
  1371. * The pointertap event is fired when a the object has been touched and released without drag.
  1372. */
  1373. PointerEventTypes.POINTERTAP = 0x20;
  1374. /**
  1375. * The pointerdoubletap event is fired when a the object has been touched and released twice without drag.
  1376. */
  1377. PointerEventTypes.POINTERDOUBLETAP = 0x40;
  1378. return PointerEventTypes;
  1379. }());
  1380. BABYLON.PointerEventTypes = PointerEventTypes;
  1381. /**
  1382. * Base class of pointer info types.
  1383. */
  1384. var PointerInfoBase = /** @class */ (function () {
  1385. /**
  1386. * Instantiates the base class of pointers info.
  1387. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1388. * @param event Defines the related dom event
  1389. */
  1390. function PointerInfoBase(
  1391. /**
  1392. * Defines the type of event (BABYLON.PointerEventTypes)
  1393. */
  1394. type,
  1395. /**
  1396. * Defines the related dom event
  1397. */
  1398. event) {
  1399. this.type = type;
  1400. this.event = event;
  1401. }
  1402. return PointerInfoBase;
  1403. }());
  1404. BABYLON.PointerInfoBase = PointerInfoBase;
  1405. /**
  1406. * This class is used to store pointer related info for the onPrePointerObservable event.
  1407. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1408. */
  1409. var PointerInfoPre = /** @class */ (function (_super) {
  1410. __extends(PointerInfoPre, _super);
  1411. /**
  1412. * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.
  1413. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1414. * @param event Defines the related dom event
  1415. * @param localX Defines the local x coordinates of the pointer when the event occured
  1416. * @param localY Defines the local y coordinates of the pointer when the event occured
  1417. */
  1418. function PointerInfoPre(type, event, localX, localY) {
  1419. var _this = _super.call(this, type, event) || this;
  1420. /**
  1421. * Ray from a pointer if availible (eg. 6dof controller)
  1422. */
  1423. _this.ray = null;
  1424. _this.skipOnPointerObservable = false;
  1425. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1426. return _this;
  1427. }
  1428. return PointerInfoPre;
  1429. }(PointerInfoBase));
  1430. BABYLON.PointerInfoPre = PointerInfoPre;
  1431. /**
  1432. * This type contains all the data related to a pointer event in Babylon.js.
  1433. * 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.
  1434. */
  1435. var PointerInfo = /** @class */ (function (_super) {
  1436. __extends(PointerInfo, _super);
  1437. /**
  1438. * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.
  1439. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1440. * @param event Defines the related dom event
  1441. * @param pickInfo Defines the picking info associated to the info (if any)\
  1442. */
  1443. function PointerInfo(type, event,
  1444. /**
  1445. * Defines the picking info associated to the info (if any)\
  1446. */
  1447. pickInfo) {
  1448. var _this = _super.call(this, type, event) || this;
  1449. _this.pickInfo = pickInfo;
  1450. return _this;
  1451. }
  1452. return PointerInfo;
  1453. }(PointerInfoBase));
  1454. BABYLON.PointerInfo = PointerInfo;
  1455. })(BABYLON || (BABYLON = {}));
  1456. //# sourceMappingURL=pointerEvents.js.map
  1457. var BABYLON;
  1458. (function (BABYLON) {
  1459. /** Class used to store color4 gradient */
  1460. var ColorGradient = /** @class */ (function () {
  1461. function ColorGradient() {
  1462. }
  1463. /**
  1464. * Will get a color picked randomly between color1 and color2.
  1465. * If color2 is undefined then color1 will be used
  1466. * @param result defines the target Color4 to store the result in
  1467. */
  1468. ColorGradient.prototype.getColorToRef = function (result) {
  1469. if (!this.color2) {
  1470. result.copyFrom(this.color1);
  1471. return;
  1472. }
  1473. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  1474. };
  1475. return ColorGradient;
  1476. }());
  1477. BABYLON.ColorGradient = ColorGradient;
  1478. /** Class used to store color 3 gradient */
  1479. var Color3Gradient = /** @class */ (function () {
  1480. function Color3Gradient() {
  1481. }
  1482. return Color3Gradient;
  1483. }());
  1484. BABYLON.Color3Gradient = Color3Gradient;
  1485. /** Class used to store factor gradient */
  1486. var FactorGradient = /** @class */ (function () {
  1487. function FactorGradient() {
  1488. }
  1489. /**
  1490. * Will get a number picked randomly between factor1 and factor2.
  1491. * If factor2 is undefined then factor1 will be used
  1492. * @returns the picked number
  1493. */
  1494. FactorGradient.prototype.getFactor = function () {
  1495. if (this.factor2 === undefined) {
  1496. return this.factor1;
  1497. }
  1498. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  1499. };
  1500. return FactorGradient;
  1501. }());
  1502. BABYLON.FactorGradient = FactorGradient;
  1503. /**
  1504. * @ignore
  1505. * Application error to support additional information when loading a file
  1506. */
  1507. var LoadFileError = /** @class */ (function (_super) {
  1508. __extends(LoadFileError, _super);
  1509. /**
  1510. * Creates a new LoadFileError
  1511. * @param message defines the message of the error
  1512. * @param request defines the optional XHR request
  1513. */
  1514. function LoadFileError(message,
  1515. /** defines the optional XHR request */
  1516. request) {
  1517. var _this = _super.call(this, message) || this;
  1518. _this.request = request;
  1519. _this.name = "LoadFileError";
  1520. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  1521. return _this;
  1522. }
  1523. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  1524. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  1525. // Polyfill for Object.setPrototypeOf if necessary.
  1526. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  1527. return LoadFileError;
  1528. }(Error));
  1529. BABYLON.LoadFileError = LoadFileError;
  1530. /**
  1531. * Class used to define a retry strategy when error happens while loading assets
  1532. */
  1533. var RetryStrategy = /** @class */ (function () {
  1534. function RetryStrategy() {
  1535. }
  1536. /**
  1537. * Function used to defines an exponential back off strategy
  1538. * @param maxRetries defines the maximum number of retries (3 by default)
  1539. * @param baseInterval defines the interval between retries
  1540. * @returns the strategy function to use
  1541. */
  1542. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  1543. if (maxRetries === void 0) { maxRetries = 3; }
  1544. if (baseInterval === void 0) { baseInterval = 500; }
  1545. return function (url, request, retryIndex) {
  1546. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  1547. return -1;
  1548. }
  1549. return Math.pow(2, retryIndex) * baseInterval;
  1550. };
  1551. };
  1552. return RetryStrategy;
  1553. }());
  1554. BABYLON.RetryStrategy = RetryStrategy;
  1555. // Screenshots
  1556. var screenshotCanvas;
  1557. var cloneValue = function (source, destinationObject) {
  1558. if (!source) {
  1559. return null;
  1560. }
  1561. if (source instanceof BABYLON.Mesh) {
  1562. return null;
  1563. }
  1564. if (source instanceof BABYLON.SubMesh) {
  1565. return source.clone(destinationObject);
  1566. }
  1567. else if (source.clone) {
  1568. return source.clone();
  1569. }
  1570. return null;
  1571. };
  1572. /**
  1573. * Class containing a set of static utilities functions
  1574. */
  1575. var Tools = /** @class */ (function () {
  1576. function Tools() {
  1577. }
  1578. /**
  1579. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  1580. * @param u defines the coordinate on X axis
  1581. * @param v defines the coordinate on Y axis
  1582. * @param width defines the width of the source data
  1583. * @param height defines the height of the source data
  1584. * @param pixels defines the source byte array
  1585. * @param color defines the output color
  1586. */
  1587. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  1588. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  1589. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  1590. var position = (wrappedU + wrappedV * width) * 4;
  1591. color.r = pixels[position] / 255;
  1592. color.g = pixels[position + 1] / 255;
  1593. color.b = pixels[position + 2] / 255;
  1594. color.a = pixels[position + 3] / 255;
  1595. };
  1596. /**
  1597. * Interpolates between a and b via alpha
  1598. * @param a The lower value (returned when alpha = 0)
  1599. * @param b The upper value (returned when alpha = 1)
  1600. * @param alpha The interpolation-factor
  1601. * @return The mixed value
  1602. */
  1603. Tools.Mix = function (a, b, alpha) {
  1604. return a * (1 - alpha) + b * alpha;
  1605. };
  1606. /**
  1607. * Tries to instantiate a new object from a given class name
  1608. * @param className defines the class name to instantiate
  1609. * @returns the new object or null if the system was not able to do the instantiation
  1610. */
  1611. Tools.Instantiate = function (className) {
  1612. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  1613. return Tools.RegisteredExternalClasses[className];
  1614. }
  1615. var arr = className.split(".");
  1616. var fn = (window || this);
  1617. for (var i = 0, len = arr.length; i < len; i++) {
  1618. fn = fn[arr[i]];
  1619. }
  1620. if (typeof fn !== "function") {
  1621. return null;
  1622. }
  1623. return fn;
  1624. };
  1625. /**
  1626. * Provides a slice function that will work even on IE
  1627. * @param data defines the array to slice
  1628. * @param start defines the start of the data (optional)
  1629. * @param end defines the end of the data (optional)
  1630. * @returns the new sliced array
  1631. */
  1632. Tools.Slice = function (data, start, end) {
  1633. if (data.slice) {
  1634. return data.slice(start, end);
  1635. }
  1636. return Array.prototype.slice.call(data, start, end);
  1637. };
  1638. /**
  1639. * Polyfill for setImmediate
  1640. * @param action defines the action to execute after the current execution block
  1641. */
  1642. Tools.SetImmediate = function (action) {
  1643. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  1644. window.setImmediate(action);
  1645. }
  1646. else {
  1647. setTimeout(action, 1);
  1648. }
  1649. };
  1650. /**
  1651. * Function indicating if a number is an exponent of 2
  1652. * @param value defines the value to test
  1653. * @returns true if the value is an exponent of 2
  1654. */
  1655. Tools.IsExponentOfTwo = function (value) {
  1656. var count = 1;
  1657. do {
  1658. count *= 2;
  1659. } while (count < value);
  1660. return count === value;
  1661. };
  1662. /**
  1663. * Returns the nearest 32-bit single precision float representation of a Number
  1664. * @param value A Number. If the parameter is of a different type, it will get converted
  1665. * to a number or to NaN if it cannot be converted
  1666. * @returns number
  1667. */
  1668. Tools.FloatRound = function (value) {
  1669. if (Math.fround) {
  1670. return Math.fround(value);
  1671. }
  1672. return (Tools._tmpFloatArray[0] = value);
  1673. };
  1674. /**
  1675. * Find the next highest power of two.
  1676. * @param x Number to start search from.
  1677. * @return Next highest power of two.
  1678. */
  1679. Tools.CeilingPOT = function (x) {
  1680. x--;
  1681. x |= x >> 1;
  1682. x |= x >> 2;
  1683. x |= x >> 4;
  1684. x |= x >> 8;
  1685. x |= x >> 16;
  1686. x++;
  1687. return x;
  1688. };
  1689. /**
  1690. * Find the next lowest power of two.
  1691. * @param x Number to start search from.
  1692. * @return Next lowest power of two.
  1693. */
  1694. Tools.FloorPOT = function (x) {
  1695. x = x | (x >> 1);
  1696. x = x | (x >> 2);
  1697. x = x | (x >> 4);
  1698. x = x | (x >> 8);
  1699. x = x | (x >> 16);
  1700. return x - (x >> 1);
  1701. };
  1702. /**
  1703. * Find the nearest power of two.
  1704. * @param x Number to start search from.
  1705. * @return Next nearest power of two.
  1706. */
  1707. Tools.NearestPOT = function (x) {
  1708. var c = Tools.CeilingPOT(x);
  1709. var f = Tools.FloorPOT(x);
  1710. return (c - x) > (x - f) ? f : c;
  1711. };
  1712. /**
  1713. * Get the closest exponent of two
  1714. * @param value defines the value to approximate
  1715. * @param max defines the maximum value to return
  1716. * @param mode defines how to define the closest value
  1717. * @returns closest exponent of two of the given value
  1718. */
  1719. Tools.GetExponentOfTwo = function (value, max, mode) {
  1720. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  1721. var pot;
  1722. switch (mode) {
  1723. case BABYLON.Engine.SCALEMODE_FLOOR:
  1724. pot = Tools.FloorPOT(value);
  1725. break;
  1726. case BABYLON.Engine.SCALEMODE_NEAREST:
  1727. pot = Tools.NearestPOT(value);
  1728. break;
  1729. case BABYLON.Engine.SCALEMODE_CEILING:
  1730. default:
  1731. pot = Tools.CeilingPOT(value);
  1732. break;
  1733. }
  1734. return Math.min(pot, max);
  1735. };
  1736. /**
  1737. * Extracts the filename from a path
  1738. * @param path defines the path to use
  1739. * @returns the filename
  1740. */
  1741. Tools.GetFilename = function (path) {
  1742. var index = path.lastIndexOf("/");
  1743. if (index < 0) {
  1744. return path;
  1745. }
  1746. return path.substring(index + 1);
  1747. };
  1748. /**
  1749. * Extracts the "folder" part of a path (everything before the filename).
  1750. * @param uri The URI to extract the info from
  1751. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  1752. * @returns The "folder" part of the path
  1753. */
  1754. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  1755. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  1756. var index = uri.lastIndexOf("/");
  1757. if (index < 0) {
  1758. if (returnUnchangedIfNoSlash) {
  1759. return uri;
  1760. }
  1761. return "";
  1762. }
  1763. return uri.substring(0, index + 1);
  1764. };
  1765. /**
  1766. * Extracts text content from a DOM element hierarchy
  1767. * @param element defines the root element
  1768. * @returns a string
  1769. */
  1770. Tools.GetDOMTextContent = function (element) {
  1771. var result = "";
  1772. var child = element.firstChild;
  1773. while (child) {
  1774. if (child.nodeType === 3) {
  1775. result += child.textContent;
  1776. }
  1777. child = (child.nextSibling);
  1778. }
  1779. return result;
  1780. };
  1781. /**
  1782. * Convert an angle in radians to degrees
  1783. * @param angle defines the angle to convert
  1784. * @returns the angle in degrees
  1785. */
  1786. Tools.ToDegrees = function (angle) {
  1787. return angle * 180 / Math.PI;
  1788. };
  1789. /**
  1790. * Convert an angle in degrees to radians
  1791. * @param angle defines the angle to convert
  1792. * @returns the angle in radians
  1793. */
  1794. Tools.ToRadians = function (angle) {
  1795. return angle * Math.PI / 180;
  1796. };
  1797. /**
  1798. * Encode a buffer to a base64 string
  1799. * @param buffer defines the buffer to encode
  1800. * @returns the encoded string
  1801. */
  1802. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  1803. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  1804. var output = "";
  1805. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  1806. var i = 0;
  1807. var bytes = new Uint8Array(buffer);
  1808. while (i < bytes.length) {
  1809. chr1 = bytes[i++];
  1810. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  1811. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  1812. enc1 = chr1 >> 2;
  1813. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  1814. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  1815. enc4 = chr3 & 63;
  1816. if (isNaN(chr2)) {
  1817. enc3 = enc4 = 64;
  1818. }
  1819. else if (isNaN(chr3)) {
  1820. enc4 = 64;
  1821. }
  1822. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  1823. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  1824. }
  1825. return "data:image/png;base64," + output;
  1826. };
  1827. /**
  1828. * Extracts minimum and maximum values from a list of indexed positions
  1829. * @param positions defines the positions to use
  1830. * @param indices defines the indices to the positions
  1831. * @param indexStart defines the start index
  1832. * @param indexCount defines the end index
  1833. * @param bias defines bias value to add to the result
  1834. * @return minimum and maximum values
  1835. */
  1836. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  1837. if (bias === void 0) { bias = null; }
  1838. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1839. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1840. for (var index = indexStart; index < indexStart + indexCount; index++) {
  1841. var offset = indices[index] * 3;
  1842. var x = positions[offset];
  1843. var y = positions[offset + 1];
  1844. var z = positions[offset + 2];
  1845. minimum.minimizeInPlaceFromFloats(x, y, z);
  1846. maximum.maximizeInPlaceFromFloats(x, y, z);
  1847. }
  1848. if (bias) {
  1849. minimum.x -= minimum.x * bias.x + bias.y;
  1850. minimum.y -= minimum.y * bias.x + bias.y;
  1851. minimum.z -= minimum.z * bias.x + bias.y;
  1852. maximum.x += maximum.x * bias.x + bias.y;
  1853. maximum.y += maximum.y * bias.x + bias.y;
  1854. maximum.z += maximum.z * bias.x + bias.y;
  1855. }
  1856. return {
  1857. minimum: minimum,
  1858. maximum: maximum
  1859. };
  1860. };
  1861. /**
  1862. * Extracts minimum and maximum values from a list of positions
  1863. * @param positions defines the positions to use
  1864. * @param start defines the start index in the positions array
  1865. * @param count defines the number of positions to handle
  1866. * @param bias defines bias value to add to the result
  1867. * @param stride defines the stride size to use (distance between two positions in the positions array)
  1868. * @return minimum and maximum values
  1869. */
  1870. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  1871. if (bias === void 0) { bias = null; }
  1872. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1873. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1874. if (!stride) {
  1875. stride = 3;
  1876. }
  1877. for (var index = start, offset = start * stride; index < start + count; index++, offset += stride) {
  1878. var x = positions[offset];
  1879. var y = positions[offset + 1];
  1880. var z = positions[offset + 2];
  1881. minimum.minimizeInPlaceFromFloats(x, y, z);
  1882. maximum.maximizeInPlaceFromFloats(x, y, z);
  1883. }
  1884. if (bias) {
  1885. minimum.x -= minimum.x * bias.x + bias.y;
  1886. minimum.y -= minimum.y * bias.x + bias.y;
  1887. minimum.z -= minimum.z * bias.x + bias.y;
  1888. maximum.x += maximum.x * bias.x + bias.y;
  1889. maximum.y += maximum.y * bias.x + bias.y;
  1890. maximum.z += maximum.z * bias.x + bias.y;
  1891. }
  1892. return {
  1893. minimum: minimum,
  1894. maximum: maximum
  1895. };
  1896. };
  1897. /**
  1898. * Returns an array if obj is not an array
  1899. * @param obj defines the object to evaluate as an array
  1900. * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
  1901. * @returns either obj directly if obj is an array or a new array containing obj
  1902. */
  1903. Tools.MakeArray = function (obj, allowsNullUndefined) {
  1904. if (allowsNullUndefined !== true && (obj === undefined || obj == null)) {
  1905. return null;
  1906. }
  1907. return Array.isArray(obj) ? obj : [obj];
  1908. };
  1909. /**
  1910. * Returns an array of the given size filled with element built from the given constructor and the paramters
  1911. * @param size the number of element to construct and put in the array
  1912. * @param itemBuilder a callback responsible for creating new instance of item. Called once per array entry.
  1913. * @returns a new array filled with new objects
  1914. */
  1915. Tools.BuildArray = function (size, itemBuilder) {
  1916. var a = [];
  1917. for (var i = 0; i < size; ++i) {
  1918. a.push(itemBuilder());
  1919. }
  1920. return a;
  1921. };
  1922. /**
  1923. * Gets the pointer prefix to use
  1924. * @returns "pointer" if touch is enabled. Else returns "mouse"
  1925. */
  1926. Tools.GetPointerPrefix = function () {
  1927. var eventPrefix = "pointer";
  1928. // Check if pointer events are supported
  1929. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  1930. eventPrefix = "mouse";
  1931. }
  1932. return eventPrefix;
  1933. };
  1934. /**
  1935. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  1936. * @param func - the function to be called
  1937. * @param requester - the object that will request the next frame. Falls back to window.
  1938. * @returns frame number
  1939. */
  1940. Tools.QueueNewFrame = function (func, requester) {
  1941. if (!Tools.IsWindowObjectExist()) {
  1942. return setTimeout(func, 16);
  1943. }
  1944. if (!requester) {
  1945. requester = window;
  1946. }
  1947. if (requester.requestAnimationFrame) {
  1948. return requester.requestAnimationFrame(func);
  1949. }
  1950. else if (requester.msRequestAnimationFrame) {
  1951. return requester.msRequestAnimationFrame(func);
  1952. }
  1953. else if (requester.webkitRequestAnimationFrame) {
  1954. return requester.webkitRequestAnimationFrame(func);
  1955. }
  1956. else if (requester.mozRequestAnimationFrame) {
  1957. return requester.mozRequestAnimationFrame(func);
  1958. }
  1959. else if (requester.oRequestAnimationFrame) {
  1960. return requester.oRequestAnimationFrame(func);
  1961. }
  1962. else {
  1963. return window.setTimeout(func, 16);
  1964. }
  1965. };
  1966. /**
  1967. * Ask the browser to promote the current element to fullscreen rendering mode
  1968. * @param element defines the DOM element to promote
  1969. */
  1970. Tools.RequestFullscreen = function (element) {
  1971. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  1972. if (!requestFunction) {
  1973. return;
  1974. }
  1975. requestFunction.call(element);
  1976. };
  1977. /**
  1978. * Asks the browser to exit fullscreen mode
  1979. */
  1980. Tools.ExitFullscreen = function () {
  1981. if (document.exitFullscreen) {
  1982. document.exitFullscreen();
  1983. }
  1984. else if (document.mozCancelFullScreen) {
  1985. document.mozCancelFullScreen();
  1986. }
  1987. else if (document.webkitCancelFullScreen) {
  1988. document.webkitCancelFullScreen();
  1989. }
  1990. else if (document.msCancelFullScreen) {
  1991. document.msCancelFullScreen();
  1992. }
  1993. };
  1994. /**
  1995. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  1996. * @param url define the url we are trying
  1997. * @param element define the dom element where to configure the cors policy
  1998. */
  1999. Tools.SetCorsBehavior = function (url, element) {
  2000. if (url && url.indexOf("data:") === 0) {
  2001. return;
  2002. }
  2003. if (Tools.CorsBehavior) {
  2004. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  2005. element.crossOrigin = Tools.CorsBehavior;
  2006. }
  2007. else {
  2008. var result = Tools.CorsBehavior(url);
  2009. if (result) {
  2010. element.crossOrigin = result;
  2011. }
  2012. }
  2013. }
  2014. };
  2015. // External files
  2016. /**
  2017. * Removes unwanted characters from an url
  2018. * @param url defines the url to clean
  2019. * @returns the cleaned url
  2020. */
  2021. Tools.CleanUrl = function (url) {
  2022. url = url.replace(/#/mg, "%23");
  2023. return url;
  2024. };
  2025. /**
  2026. * Loads an image as an HTMLImageElement.
  2027. * @param input url string, ArrayBuffer, or Blob to load
  2028. * @param onLoad callback called when the image successfully loads
  2029. * @param onError callback called when the image fails to load
  2030. * @param offlineProvider offline provider for caching
  2031. * @returns the HTMLImageElement of the loaded image
  2032. */
  2033. Tools.LoadImage = function (input, onLoad, onError, offlineProvider) {
  2034. var url;
  2035. var usingObjectURL = false;
  2036. if (input instanceof ArrayBuffer) {
  2037. url = URL.createObjectURL(new Blob([input]));
  2038. usingObjectURL = true;
  2039. }
  2040. else if (input instanceof Blob) {
  2041. url = URL.createObjectURL(input);
  2042. usingObjectURL = true;
  2043. }
  2044. else {
  2045. url = Tools.CleanUrl(input);
  2046. url = Tools.PreprocessUrl(input);
  2047. }
  2048. var img = new Image();
  2049. Tools.SetCorsBehavior(url, img);
  2050. var loadHandler = function () {
  2051. if (usingObjectURL && img.src) {
  2052. URL.revokeObjectURL(img.src);
  2053. }
  2054. img.removeEventListener("load", loadHandler);
  2055. img.removeEventListener("error", errorHandler);
  2056. onLoad(img);
  2057. };
  2058. var errorHandler = function (err) {
  2059. if (usingObjectURL && img.src) {
  2060. URL.revokeObjectURL(img.src);
  2061. }
  2062. img.removeEventListener("load", loadHandler);
  2063. img.removeEventListener("error", errorHandler);
  2064. Tools.Error("Error while trying to load image: " + input);
  2065. if (onError) {
  2066. onError("Error while trying to load image: " + input, err);
  2067. }
  2068. };
  2069. img.addEventListener("load", loadHandler);
  2070. img.addEventListener("error", errorHandler);
  2071. var noOfflineSupport = function () {
  2072. img.src = url;
  2073. };
  2074. var loadFromOfflineSupport = function () {
  2075. if (offlineProvider) {
  2076. offlineProvider.loadImage(url, img);
  2077. }
  2078. };
  2079. if (url.substr(0, 5) !== "data:" && offlineProvider && offlineProvider.enableTexturesOffline) {
  2080. offlineProvider.open(loadFromOfflineSupport, noOfflineSupport);
  2081. }
  2082. else {
  2083. if (url.indexOf("file:") !== -1) {
  2084. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  2085. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  2086. try {
  2087. var blobURL;
  2088. try {
  2089. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  2090. }
  2091. catch (ex) {
  2092. // Chrome doesn't support oneTimeOnly parameter
  2093. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  2094. }
  2095. img.src = blobURL;
  2096. usingObjectURL = true;
  2097. }
  2098. catch (e) {
  2099. img.src = "";
  2100. }
  2101. return img;
  2102. }
  2103. }
  2104. noOfflineSupport();
  2105. }
  2106. return img;
  2107. };
  2108. /**
  2109. * Loads a file
  2110. * @param url url string, ArrayBuffer, or Blob to load
  2111. * @param onSuccess callback called when the file successfully loads
  2112. * @param onProgress callback called while file is loading (if the server supports this mode)
  2113. * @param offlineProvider defines the offline provider for caching
  2114. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  2115. * @param onError callback called when the file fails to load
  2116. * @returns a file request object
  2117. */
  2118. Tools.LoadFile = function (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) {
  2119. url = Tools.CleanUrl(url);
  2120. url = Tools.PreprocessUrl(url);
  2121. // If file and file input are set
  2122. if (url.indexOf("file:") !== -1) {
  2123. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  2124. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  2125. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  2126. }
  2127. }
  2128. var loadUrl = Tools.BaseUrl + url;
  2129. var aborted = false;
  2130. var fileRequest = {
  2131. onCompleteObservable: new BABYLON.Observable(),
  2132. abort: function () { return aborted = true; },
  2133. };
  2134. var requestFile = function () {
  2135. var request = new XMLHttpRequest();
  2136. var retryHandle = null;
  2137. fileRequest.abort = function () {
  2138. aborted = true;
  2139. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  2140. request.abort();
  2141. }
  2142. if (retryHandle !== null) {
  2143. clearTimeout(retryHandle);
  2144. retryHandle = null;
  2145. }
  2146. };
  2147. var retryLoop = function (retryIndex) {
  2148. request.open('GET', loadUrl, true);
  2149. if (useArrayBuffer) {
  2150. request.responseType = "arraybuffer";
  2151. }
  2152. if (onProgress) {
  2153. request.addEventListener("progress", onProgress);
  2154. }
  2155. var onLoadEnd = function () {
  2156. request.removeEventListener("loadend", onLoadEnd);
  2157. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  2158. fileRequest.onCompleteObservable.clear();
  2159. };
  2160. request.addEventListener("loadend", onLoadEnd);
  2161. var onReadyStateChange = function () {
  2162. if (aborted) {
  2163. return;
  2164. }
  2165. // In case of undefined state in some browsers.
  2166. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  2167. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  2168. request.removeEventListener("readystatechange", onReadyStateChange);
  2169. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  2170. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  2171. return;
  2172. }
  2173. var retryStrategy = Tools.DefaultRetryStrategy;
  2174. if (retryStrategy) {
  2175. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  2176. if (waitTime !== -1) {
  2177. // Prevent the request from completing for retry.
  2178. request.removeEventListener("loadend", onLoadEnd);
  2179. request = new XMLHttpRequest();
  2180. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  2181. return;
  2182. }
  2183. }
  2184. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  2185. if (onError) {
  2186. onError(request, e);
  2187. }
  2188. else {
  2189. throw e;
  2190. }
  2191. }
  2192. };
  2193. request.addEventListener("readystatechange", onReadyStateChange);
  2194. request.send();
  2195. };
  2196. retryLoop(0);
  2197. };
  2198. // Caching all files
  2199. if (offlineProvider && offlineProvider.enableSceneOffline) {
  2200. var noOfflineSupport_1 = function (request) {
  2201. if (request && request.status > 400) {
  2202. if (onError) {
  2203. onError(request);
  2204. }
  2205. }
  2206. else {
  2207. if (!aborted) {
  2208. requestFile();
  2209. }
  2210. }
  2211. };
  2212. var loadFromOfflineSupport = function () {
  2213. // TODO: database needs to support aborting and should return a IFileRequest
  2214. if (aborted) {
  2215. return;
  2216. }
  2217. if (offlineProvider) {
  2218. offlineProvider.loadFile(url, function (data) {
  2219. if (!aborted) {
  2220. onSuccess(data);
  2221. }
  2222. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  2223. }, onProgress ? function (event) {
  2224. if (!aborted) {
  2225. onProgress(event);
  2226. }
  2227. } : undefined, noOfflineSupport_1, useArrayBuffer);
  2228. }
  2229. };
  2230. offlineProvider.open(loadFromOfflineSupport, noOfflineSupport_1);
  2231. }
  2232. else {
  2233. requestFile();
  2234. }
  2235. return fileRequest;
  2236. };
  2237. /**
  2238. * Load a script (identified by an url). When the url returns, the
  2239. * content of this file is added into a new script element, attached to the DOM (body element)
  2240. * @param scriptUrl defines the url of the script to laod
  2241. * @param onSuccess defines the callback called when the script is loaded
  2242. * @param onError defines the callback to call if an error occurs
  2243. */
  2244. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  2245. if (!Tools.IsWindowObjectExist()) {
  2246. return;
  2247. }
  2248. var head = document.getElementsByTagName('head')[0];
  2249. var script = document.createElement('script');
  2250. script.type = 'text/javascript';
  2251. script.src = scriptUrl;
  2252. script.onload = function () {
  2253. if (onSuccess) {
  2254. onSuccess();
  2255. }
  2256. };
  2257. script.onerror = function (e) {
  2258. if (onError) {
  2259. onError("Unable to load script '" + scriptUrl + "'", e);
  2260. }
  2261. };
  2262. head.appendChild(script);
  2263. };
  2264. /**
  2265. * Loads a file from a blob
  2266. * @param fileToLoad defines the blob to use
  2267. * @param callback defines the callback to call when data is loaded
  2268. * @param progressCallback defines the callback to call during loading process
  2269. * @returns a file request object
  2270. */
  2271. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2272. var reader = new FileReader();
  2273. var request = {
  2274. onCompleteObservable: new BABYLON.Observable(),
  2275. abort: function () { return reader.abort(); },
  2276. };
  2277. reader.onloadend = function (e) {
  2278. request.onCompleteObservable.notifyObservers(request);
  2279. };
  2280. reader.onload = function (e) {
  2281. //target doesn't have result from ts 1.3
  2282. callback(e.target['result']);
  2283. };
  2284. reader.onprogress = progressCallback;
  2285. reader.readAsDataURL(fileToLoad);
  2286. return request;
  2287. };
  2288. /**
  2289. * Loads a file
  2290. * @param fileToLoad defines the file to load
  2291. * @param callback defines the callback to call when data is loaded
  2292. * @param progressCallBack defines the callback to call during loading process
  2293. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  2294. * @returns a file request object
  2295. */
  2296. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2297. var reader = new FileReader();
  2298. var request = {
  2299. onCompleteObservable: new BABYLON.Observable(),
  2300. abort: function () { return reader.abort(); },
  2301. };
  2302. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  2303. reader.onerror = function (e) {
  2304. Tools.Log("Error while reading file: " + fileToLoad.name);
  2305. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  2306. };
  2307. reader.onload = function (e) {
  2308. //target doesn't have result from ts 1.3
  2309. callback(e.target['result']);
  2310. };
  2311. if (progressCallBack) {
  2312. reader.onprogress = progressCallBack;
  2313. }
  2314. if (!useArrayBuffer) {
  2315. // Asynchronous read
  2316. reader.readAsText(fileToLoad);
  2317. }
  2318. else {
  2319. reader.readAsArrayBuffer(fileToLoad);
  2320. }
  2321. return request;
  2322. };
  2323. /**
  2324. * Creates a data url from a given string content
  2325. * @param content defines the content to convert
  2326. * @returns the new data url link
  2327. */
  2328. Tools.FileAsURL = function (content) {
  2329. var fileBlob = new Blob([content]);
  2330. var url = window.URL || window.webkitURL;
  2331. var link = url.createObjectURL(fileBlob);
  2332. return link;
  2333. };
  2334. /**
  2335. * Format the given number to a specific decimal format
  2336. * @param value defines the number to format
  2337. * @param decimals defines the number of decimals to use
  2338. * @returns the formatted string
  2339. */
  2340. Tools.Format = function (value, decimals) {
  2341. if (decimals === void 0) { decimals = 2; }
  2342. return value.toFixed(decimals);
  2343. };
  2344. /**
  2345. * Checks if a given vector is inside a specific range
  2346. * @param v defines the vector to test
  2347. * @param min defines the minimum range
  2348. * @param max defines the maximum range
  2349. */
  2350. Tools.CheckExtends = function (v, min, max) {
  2351. min.minimizeInPlace(v);
  2352. max.maximizeInPlace(v);
  2353. };
  2354. /**
  2355. * Tries to copy an object by duplicating every property
  2356. * @param source defines the source object
  2357. * @param destination defines the target object
  2358. * @param doNotCopyList defines a list of properties to avoid
  2359. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  2360. */
  2361. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2362. for (var prop in source) {
  2363. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2364. continue;
  2365. }
  2366. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2367. continue;
  2368. }
  2369. var sourceValue = source[prop];
  2370. var typeOfSourceValue = typeof sourceValue;
  2371. if (typeOfSourceValue === "function") {
  2372. continue;
  2373. }
  2374. try {
  2375. if (typeOfSourceValue === "object") {
  2376. if (sourceValue instanceof Array) {
  2377. destination[prop] = [];
  2378. if (sourceValue.length > 0) {
  2379. if (typeof sourceValue[0] == "object") {
  2380. for (var index = 0; index < sourceValue.length; index++) {
  2381. var clonedValue = cloneValue(sourceValue[index], destination);
  2382. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  2383. destination[prop].push(clonedValue);
  2384. }
  2385. }
  2386. }
  2387. else {
  2388. destination[prop] = sourceValue.slice(0);
  2389. }
  2390. }
  2391. }
  2392. else {
  2393. destination[prop] = cloneValue(sourceValue, destination);
  2394. }
  2395. }
  2396. else {
  2397. destination[prop] = sourceValue;
  2398. }
  2399. }
  2400. catch (e) {
  2401. // Just ignore error (it could be because of a read-only property)
  2402. }
  2403. }
  2404. };
  2405. /**
  2406. * Gets a boolean indicating if the given object has no own property
  2407. * @param obj defines the object to test
  2408. * @returns true if object has no own property
  2409. */
  2410. Tools.IsEmpty = function (obj) {
  2411. for (var i in obj) {
  2412. if (obj.hasOwnProperty(i)) {
  2413. return false;
  2414. }
  2415. }
  2416. return true;
  2417. };
  2418. /**
  2419. * Function used to register events at window level
  2420. * @param events defines the events to register
  2421. */
  2422. Tools.RegisterTopRootEvents = function (events) {
  2423. for (var index = 0; index < events.length; index++) {
  2424. var event = events[index];
  2425. window.addEventListener(event.name, event.handler, false);
  2426. try {
  2427. if (window.parent) {
  2428. window.parent.addEventListener(event.name, event.handler, false);
  2429. }
  2430. }
  2431. catch (e) {
  2432. // Silently fails...
  2433. }
  2434. }
  2435. };
  2436. /**
  2437. * Function used to unregister events from window level
  2438. * @param events defines the events to unregister
  2439. */
  2440. Tools.UnregisterTopRootEvents = function (events) {
  2441. for (var index = 0; index < events.length; index++) {
  2442. var event = events[index];
  2443. window.removeEventListener(event.name, event.handler);
  2444. try {
  2445. if (window.parent) {
  2446. window.parent.removeEventListener(event.name, event.handler);
  2447. }
  2448. }
  2449. catch (e) {
  2450. // Silently fails...
  2451. }
  2452. }
  2453. };
  2454. /**
  2455. * Dumps the current bound framebuffer
  2456. * @param width defines the rendering width
  2457. * @param height defines the rendering height
  2458. * @param engine defines the hosting engine
  2459. * @param successCallback defines the callback triggered once the data are available
  2460. * @param mimeType defines the mime type of the result
  2461. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  2462. */
  2463. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  2464. if (mimeType === void 0) { mimeType = "image/png"; }
  2465. // Read the contents of the framebuffer
  2466. var numberOfChannelsByLine = width * 4;
  2467. var halfHeight = height / 2;
  2468. //Reading datas from WebGL
  2469. var data = engine.readPixels(0, 0, width, height);
  2470. //To flip image on Y axis.
  2471. for (var i = 0; i < halfHeight; i++) {
  2472. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2473. var currentCell = j + i * numberOfChannelsByLine;
  2474. var targetLine = height - i - 1;
  2475. var targetCell = j + targetLine * numberOfChannelsByLine;
  2476. var temp = data[currentCell];
  2477. data[currentCell] = data[targetCell];
  2478. data[targetCell] = temp;
  2479. }
  2480. }
  2481. // Create a 2D canvas to store the result
  2482. if (!screenshotCanvas) {
  2483. screenshotCanvas = document.createElement('canvas');
  2484. }
  2485. screenshotCanvas.width = width;
  2486. screenshotCanvas.height = height;
  2487. var context = screenshotCanvas.getContext('2d');
  2488. if (context) {
  2489. // Copy the pixels to a 2D canvas
  2490. var imageData = context.createImageData(width, height);
  2491. var castData = (imageData.data);
  2492. castData.set(data);
  2493. context.putImageData(imageData, 0, 0);
  2494. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  2495. }
  2496. };
  2497. /**
  2498. * Converts the canvas data to blob.
  2499. * This acts as a polyfill for browsers not supporting the to blob function.
  2500. * @param canvas Defines the canvas to extract the data from
  2501. * @param successCallback Defines the callback triggered once the data are available
  2502. * @param mimeType Defines the mime type of the result
  2503. */
  2504. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  2505. if (mimeType === void 0) { mimeType = "image/png"; }
  2506. // We need HTMLCanvasElement.toBlob for HD screenshots
  2507. if (!canvas.toBlob) {
  2508. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  2509. canvas.toBlob = function (callback, type, quality) {
  2510. var _this = this;
  2511. setTimeout(function () {
  2512. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  2513. for (var i = 0; i < len; i++) {
  2514. arr[i] = binStr.charCodeAt(i);
  2515. }
  2516. callback(new Blob([arr]));
  2517. });
  2518. };
  2519. }
  2520. canvas.toBlob(function (blob) {
  2521. successCallback(blob);
  2522. }, mimeType);
  2523. };
  2524. /**
  2525. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  2526. * @param successCallback defines the callback triggered once the data are available
  2527. * @param mimeType defines the mime type of the result
  2528. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  2529. */
  2530. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  2531. if (mimeType === void 0) { mimeType = "image/png"; }
  2532. if (successCallback) {
  2533. var base64Image = screenshotCanvas.toDataURL(mimeType);
  2534. successCallback(base64Image);
  2535. }
  2536. else {
  2537. this.ToBlob(screenshotCanvas, function (blob) {
  2538. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2539. if (("download" in document.createElement("a"))) {
  2540. if (!fileName) {
  2541. var date = new Date();
  2542. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  2543. fileName = "screenshot_" + stringDate + ".png";
  2544. }
  2545. Tools.Download(blob, fileName);
  2546. }
  2547. else {
  2548. var url = URL.createObjectURL(blob);
  2549. var newWindow = window.open("");
  2550. if (!newWindow) {
  2551. return;
  2552. }
  2553. var img = newWindow.document.createElement("img");
  2554. img.onload = function () {
  2555. // no longer need to read the blob so it's revoked
  2556. URL.revokeObjectURL(url);
  2557. };
  2558. img.src = url;
  2559. newWindow.document.body.appendChild(img);
  2560. }
  2561. }, mimeType);
  2562. }
  2563. };
  2564. /**
  2565. * Downloads a blob in the browser
  2566. * @param blob defines the blob to download
  2567. * @param fileName defines the name of the downloaded file
  2568. */
  2569. Tools.Download = function (blob, fileName) {
  2570. if (navigator && navigator.msSaveBlob) {
  2571. navigator.msSaveBlob(blob, fileName);
  2572. return;
  2573. }
  2574. var url = window.URL.createObjectURL(blob);
  2575. var a = document.createElement("a");
  2576. document.body.appendChild(a);
  2577. a.style.display = "none";
  2578. a.href = url;
  2579. a.download = fileName;
  2580. a.addEventListener("click", function () {
  2581. if (a.parentElement) {
  2582. a.parentElement.removeChild(a);
  2583. }
  2584. });
  2585. a.click();
  2586. window.URL.revokeObjectURL(url);
  2587. };
  2588. /**
  2589. * Captures a screenshot of the current rendering
  2590. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  2591. * @param engine defines the rendering engine
  2592. * @param camera defines the source camera
  2593. * @param size This parameter can be set to a single number or to an object with the
  2594. * following (optional) properties: precision, width, height. If a single number is passed,
  2595. * it will be used for both width and height. If an object is passed, the screenshot size
  2596. * will be derived from the parameters. The precision property is a multiplier allowing
  2597. * rendering at a higher or lower resolution
  2598. * @param successCallback defines the callback receives a single parameter which contains the
  2599. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  2600. * src parameter of an <img> to display it
  2601. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  2602. * Check your browser for supported MIME types
  2603. */
  2604. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  2605. if (mimeType === void 0) { mimeType = "image/png"; }
  2606. var width;
  2607. var height;
  2608. // If a precision value is specified
  2609. if (size.precision) {
  2610. width = Math.round(engine.getRenderWidth() * size.precision);
  2611. height = Math.round(width / engine.getAspectRatio(camera));
  2612. }
  2613. else if (size.width && size.height) {
  2614. width = size.width;
  2615. height = size.height;
  2616. }
  2617. //If passing only width, computing height to keep display canvas ratio.
  2618. else if (size.width && !size.height) {
  2619. width = size.width;
  2620. height = Math.round(width / engine.getAspectRatio(camera));
  2621. }
  2622. //If passing only height, computing width to keep display canvas ratio.
  2623. else if (size.height && !size.width) {
  2624. height = size.height;
  2625. width = Math.round(height * engine.getAspectRatio(camera));
  2626. }
  2627. //Assuming here that "size" parameter is a number
  2628. else if (!isNaN(size)) {
  2629. height = size;
  2630. width = size;
  2631. }
  2632. else {
  2633. Tools.Error("Invalid 'size' parameter !");
  2634. return;
  2635. }
  2636. if (!screenshotCanvas) {
  2637. screenshotCanvas = document.createElement('canvas');
  2638. }
  2639. screenshotCanvas.width = width;
  2640. screenshotCanvas.height = height;
  2641. var renderContext = screenshotCanvas.getContext("2d");
  2642. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  2643. var newWidth = width;
  2644. var newHeight = newWidth / ratio;
  2645. if (newHeight > height) {
  2646. newHeight = height;
  2647. newWidth = newHeight * ratio;
  2648. }
  2649. var offsetX = Math.max(0, width - newWidth) / 2;
  2650. var offsetY = Math.max(0, height - newHeight) / 2;
  2651. var renderingCanvas = engine.getRenderingCanvas();
  2652. if (renderContext && renderingCanvas) {
  2653. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  2654. }
  2655. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  2656. };
  2657. /**
  2658. * Generates an image screenshot from the specified camera.
  2659. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  2660. * @param engine The engine to use for rendering
  2661. * @param camera The camera to use for rendering
  2662. * @param size This parameter can be set to a single number or to an object with the
  2663. * following (optional) properties: precision, width, height. If a single number is passed,
  2664. * it will be used for both width and height. If an object is passed, the screenshot size
  2665. * will be derived from the parameters. The precision property is a multiplier allowing
  2666. * rendering at a higher or lower resolution
  2667. * @param successCallback The callback receives a single parameter which contains the
  2668. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  2669. * src parameter of an <img> to display it
  2670. * @param mimeType The MIME type of the screenshot image (default: image/png).
  2671. * Check your browser for supported MIME types
  2672. * @param samples Texture samples (default: 1)
  2673. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  2674. * @param fileName A name for for the downloaded file.
  2675. */
  2676. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  2677. if (mimeType === void 0) { mimeType = "image/png"; }
  2678. if (samples === void 0) { samples = 1; }
  2679. if (antialiasing === void 0) { antialiasing = false; }
  2680. var width;
  2681. var height;
  2682. //If a precision value is specified
  2683. if (size.precision) {
  2684. width = Math.round(engine.getRenderWidth() * size.precision);
  2685. height = Math.round(width / engine.getAspectRatio(camera));
  2686. size = { width: width, height: height };
  2687. }
  2688. else if (size.width && size.height) {
  2689. width = size.width;
  2690. height = size.height;
  2691. }
  2692. //If passing only width, computing height to keep display canvas ratio.
  2693. else if (size.width && !size.height) {
  2694. width = size.width;
  2695. height = Math.round(width / engine.getAspectRatio(camera));
  2696. size = { width: width, height: height };
  2697. }
  2698. //If passing only height, computing width to keep display canvas ratio.
  2699. else if (size.height && !size.width) {
  2700. height = size.height;
  2701. width = Math.round(height * engine.getAspectRatio(camera));
  2702. size = { width: width, height: height };
  2703. }
  2704. //Assuming here that "size" parameter is a number
  2705. else if (!isNaN(size)) {
  2706. height = size;
  2707. width = size;
  2708. }
  2709. else {
  2710. Tools.Error("Invalid 'size' parameter !");
  2711. return;
  2712. }
  2713. var scene = camera.getScene();
  2714. var previousCamera = null;
  2715. if (scene.activeCamera !== camera) {
  2716. previousCamera = scene.activeCamera;
  2717. scene.activeCamera = camera;
  2718. }
  2719. // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2720. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  2721. texture.renderList = null;
  2722. texture.samples = samples;
  2723. if (antialiasing) {
  2724. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  2725. }
  2726. texture.onAfterRenderObservable.add(function () {
  2727. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  2728. });
  2729. scene.incrementRenderId();
  2730. scene.resetCachedMaterial();
  2731. texture.render(true);
  2732. texture.dispose();
  2733. if (previousCamera) {
  2734. scene.activeCamera = previousCamera;
  2735. }
  2736. camera.getProjectionMatrix(true); // Force cache refresh;
  2737. };
  2738. /**
  2739. * Validates if xhr data is correct
  2740. * @param xhr defines the request to validate
  2741. * @param dataType defines the expected data type
  2742. * @returns true if data is correct
  2743. */
  2744. Tools.ValidateXHRData = function (xhr, dataType) {
  2745. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  2746. if (dataType === void 0) { dataType = 7; }
  2747. try {
  2748. if (dataType & 1) {
  2749. if (xhr.responseText && xhr.responseText.length > 0) {
  2750. return true;
  2751. }
  2752. else if (dataType === 1) {
  2753. return false;
  2754. }
  2755. }
  2756. if (dataType & 2) {
  2757. // Check header width and height since there is no "TGA" magic number
  2758. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  2759. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2760. return true;
  2761. }
  2762. else if (dataType === 2) {
  2763. return false;
  2764. }
  2765. }
  2766. if (dataType & 4) {
  2767. // Check for the "DDS" magic number
  2768. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2769. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  2770. return true;
  2771. }
  2772. else {
  2773. return false;
  2774. }
  2775. }
  2776. }
  2777. catch (e) {
  2778. // Global protection
  2779. }
  2780. return false;
  2781. };
  2782. /**
  2783. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  2784. * Be aware Math.random() could cause collisions, but:
  2785. * "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"
  2786. * @returns a pseudo random id
  2787. */
  2788. Tools.RandomId = function () {
  2789. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  2790. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  2791. return v.toString(16);
  2792. });
  2793. };
  2794. /**
  2795. * Test if the given uri is a base64 string
  2796. * @param uri The uri to test
  2797. * @return True if the uri is a base64 string or false otherwise
  2798. */
  2799. Tools.IsBase64 = function (uri) {
  2800. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  2801. };
  2802. /**
  2803. * Decode the given base64 uri.
  2804. * @param uri The uri to decode
  2805. * @return The decoded base64 data.
  2806. */
  2807. Tools.DecodeBase64 = function (uri) {
  2808. var decodedString = atob(uri.split(",")[1]);
  2809. var bufferLength = decodedString.length;
  2810. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  2811. for (var i = 0; i < bufferLength; i++) {
  2812. bufferView[i] = decodedString.charCodeAt(i);
  2813. }
  2814. return bufferView.buffer;
  2815. };
  2816. Tools._AddLogEntry = function (entry) {
  2817. Tools._LogCache = entry + Tools._LogCache;
  2818. if (Tools.OnNewCacheEntry) {
  2819. Tools.OnNewCacheEntry(entry);
  2820. }
  2821. };
  2822. Tools._FormatMessage = function (message) {
  2823. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  2824. var date = new Date();
  2825. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2826. };
  2827. Tools._LogDisabled = function (message) {
  2828. // nothing to do
  2829. };
  2830. Tools._LogEnabled = function (message) {
  2831. var formattedMessage = Tools._FormatMessage(message);
  2832. console.log("BJS - " + formattedMessage);
  2833. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2834. Tools._AddLogEntry(entry);
  2835. };
  2836. Tools._WarnDisabled = function (message) {
  2837. // nothing to do
  2838. };
  2839. Tools._WarnEnabled = function (message) {
  2840. var formattedMessage = Tools._FormatMessage(message);
  2841. console.warn("BJS - " + formattedMessage);
  2842. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2843. Tools._AddLogEntry(entry);
  2844. };
  2845. Tools._ErrorDisabled = function (message) {
  2846. // nothing to do
  2847. };
  2848. Tools._ErrorEnabled = function (message) {
  2849. Tools.errorsCount++;
  2850. var formattedMessage = Tools._FormatMessage(message);
  2851. console.error("BJS - " + formattedMessage);
  2852. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2853. Tools._AddLogEntry(entry);
  2854. };
  2855. Object.defineProperty(Tools, "LogCache", {
  2856. /**
  2857. * Gets current log cache (list of logs)
  2858. */
  2859. get: function () {
  2860. return Tools._LogCache;
  2861. },
  2862. enumerable: true,
  2863. configurable: true
  2864. });
  2865. /**
  2866. * Clears the log cache
  2867. */
  2868. Tools.ClearLogCache = function () {
  2869. Tools._LogCache = "";
  2870. Tools.errorsCount = 0;
  2871. };
  2872. Object.defineProperty(Tools, "LogLevels", {
  2873. /**
  2874. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  2875. */
  2876. set: function (level) {
  2877. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2878. Tools.Log = Tools._LogEnabled;
  2879. }
  2880. else {
  2881. Tools.Log = Tools._LogDisabled;
  2882. }
  2883. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2884. Tools.Warn = Tools._WarnEnabled;
  2885. }
  2886. else {
  2887. Tools.Warn = Tools._WarnDisabled;
  2888. }
  2889. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2890. Tools.Error = Tools._ErrorEnabled;
  2891. }
  2892. else {
  2893. Tools.Error = Tools._ErrorDisabled;
  2894. }
  2895. },
  2896. enumerable: true,
  2897. configurable: true
  2898. });
  2899. /**
  2900. * Checks if the loaded document was accessed via `file:`-Protocol.
  2901. * @returns boolean
  2902. */
  2903. Tools.IsFileURL = function () {
  2904. return location.protocol === "file:";
  2905. };
  2906. /**
  2907. * Checks if the window object exists
  2908. * @returns true if the window object exists
  2909. */
  2910. Tools.IsWindowObjectExist = function () {
  2911. return (typeof window) !== "undefined";
  2912. };
  2913. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2914. /**
  2915. * Sets the current performance log level
  2916. */
  2917. set: function (level) {
  2918. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2919. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2920. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2921. return;
  2922. }
  2923. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2924. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2925. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2926. return;
  2927. }
  2928. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2929. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2930. },
  2931. enumerable: true,
  2932. configurable: true
  2933. });
  2934. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2935. };
  2936. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2937. };
  2938. Tools._StartUserMark = function (counterName, condition) {
  2939. if (condition === void 0) { condition = true; }
  2940. if (!Tools._performance) {
  2941. if (!Tools.IsWindowObjectExist()) {
  2942. return;
  2943. }
  2944. Tools._performance = window.performance;
  2945. }
  2946. if (!condition || !Tools._performance.mark) {
  2947. return;
  2948. }
  2949. Tools._performance.mark(counterName + "-Begin");
  2950. };
  2951. Tools._EndUserMark = function (counterName, condition) {
  2952. if (condition === void 0) { condition = true; }
  2953. if (!condition || !Tools._performance.mark) {
  2954. return;
  2955. }
  2956. Tools._performance.mark(counterName + "-End");
  2957. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2958. };
  2959. Tools._StartPerformanceConsole = function (counterName, condition) {
  2960. if (condition === void 0) { condition = true; }
  2961. if (!condition) {
  2962. return;
  2963. }
  2964. Tools._StartUserMark(counterName, condition);
  2965. if (console.time) {
  2966. console.time(counterName);
  2967. }
  2968. };
  2969. Tools._EndPerformanceConsole = function (counterName, condition) {
  2970. if (condition === void 0) { condition = true; }
  2971. if (!condition) {
  2972. return;
  2973. }
  2974. Tools._EndUserMark(counterName, condition);
  2975. if (console.time) {
  2976. console.timeEnd(counterName);
  2977. }
  2978. };
  2979. Object.defineProperty(Tools, "Now", {
  2980. /**
  2981. * Gets either window.performance.now() if supported or Date.now() else
  2982. */
  2983. get: function () {
  2984. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  2985. return window.performance.now();
  2986. }
  2987. return Date.now();
  2988. },
  2989. enumerable: true,
  2990. configurable: true
  2991. });
  2992. /**
  2993. * This method will return the name of the class used to create the instance of the given object.
  2994. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  2995. * @param object the object to get the class name from
  2996. * @param isType defines if the object is actually a type
  2997. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  2998. */
  2999. Tools.GetClassName = function (object, isType) {
  3000. if (isType === void 0) { isType = false; }
  3001. var name = null;
  3002. if (!isType && object.getClassName) {
  3003. name = object.getClassName();
  3004. }
  3005. else {
  3006. if (object instanceof Object) {
  3007. var classObj = isType ? object : Object.getPrototypeOf(object);
  3008. name = classObj.constructor["__bjsclassName__"];
  3009. }
  3010. if (!name) {
  3011. name = typeof object;
  3012. }
  3013. }
  3014. return name;
  3015. };
  3016. /**
  3017. * Gets the first element of an array satisfying a given predicate
  3018. * @param array defines the array to browse
  3019. * @param predicate defines the predicate to use
  3020. * @returns null if not found or the element
  3021. */
  3022. Tools.First = function (array, predicate) {
  3023. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  3024. var el = array_1[_i];
  3025. if (predicate(el)) {
  3026. return el;
  3027. }
  3028. }
  3029. return null;
  3030. };
  3031. /**
  3032. * This method will return the name of the full name of the class, including its owning module (if any).
  3033. * 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).
  3034. * @param object the object to get the class name from
  3035. * @param isType defines if the object is actually a type
  3036. * @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.
  3037. * @ignorenaming
  3038. */
  3039. Tools.getFullClassName = function (object, isType) {
  3040. if (isType === void 0) { isType = false; }
  3041. var className = null;
  3042. var moduleName = null;
  3043. if (!isType && object.getClassName) {
  3044. className = object.getClassName();
  3045. }
  3046. else {
  3047. if (object instanceof Object) {
  3048. var classObj = isType ? object : Object.getPrototypeOf(object);
  3049. className = classObj.constructor["__bjsclassName__"];
  3050. moduleName = classObj.constructor["__bjsmoduleName__"];
  3051. }
  3052. if (!className) {
  3053. className = typeof object;
  3054. }
  3055. }
  3056. if (!className) {
  3057. return null;
  3058. }
  3059. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  3060. };
  3061. /**
  3062. * Returns a promise that resolves after the given amount of time.
  3063. * @param delay Number of milliseconds to delay
  3064. * @returns Promise that resolves after the given amount of time
  3065. */
  3066. Tools.DelayAsync = function (delay) {
  3067. return new Promise(function (resolve) {
  3068. setTimeout(function () {
  3069. resolve();
  3070. }, delay);
  3071. });
  3072. };
  3073. /**
  3074. * Gets the current gradient from an array of IValueGradient
  3075. * @param ratio defines the current ratio to get
  3076. * @param gradients defines the array of IValueGradient
  3077. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  3078. */
  3079. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  3080. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  3081. var currentGradient = gradients[gradientIndex];
  3082. var nextGradient = gradients[gradientIndex + 1];
  3083. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  3084. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  3085. updateFunc(currentGradient, nextGradient, scale);
  3086. return;
  3087. }
  3088. }
  3089. // Use last index if over
  3090. var lastIndex = gradients.length - 1;
  3091. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  3092. };
  3093. /**
  3094. * Gets or sets the base URL to use to load assets
  3095. */
  3096. Tools.BaseUrl = "";
  3097. /**
  3098. * Gets or sets the retry strategy to apply when an error happens while loading an asset
  3099. */
  3100. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  3101. /**
  3102. * Default behaviour for cors in the application.
  3103. * It can be a string if the expected behavior is identical in the entire app.
  3104. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  3105. */
  3106. Tools.CorsBehavior = "anonymous";
  3107. /**
  3108. * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
  3109. * @ignorenaming
  3110. */
  3111. Tools.UseFallbackTexture = true;
  3112. /**
  3113. * Use this object to register external classes like custom textures or material
  3114. * to allow the laoders to instantiate them
  3115. */
  3116. Tools.RegisteredExternalClasses = {};
  3117. /**
  3118. * Texture content used if a texture cannot loaded
  3119. * @ignorenaming
  3120. */
  3121. 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";
  3122. Tools._tmpFloatArray = new Float32Array(1);
  3123. /**
  3124. * Gets or sets a function used to pre-process url before using them to load assets
  3125. */
  3126. Tools.PreprocessUrl = function (url) {
  3127. return url;
  3128. };
  3129. // Logs
  3130. /**
  3131. * No log
  3132. */
  3133. Tools.NoneLogLevel = 0;
  3134. /**
  3135. * Only message logs
  3136. */
  3137. Tools.MessageLogLevel = 1;
  3138. /**
  3139. * Only warning logs
  3140. */
  3141. Tools.WarningLogLevel = 2;
  3142. /**
  3143. * Only error logs
  3144. */
  3145. Tools.ErrorLogLevel = 4;
  3146. /**
  3147. * All logs
  3148. */
  3149. Tools.AllLogLevel = 7;
  3150. Tools._LogCache = "";
  3151. /**
  3152. * Gets a value indicating the number of loading errors
  3153. * @ignorenaming
  3154. */
  3155. Tools.errorsCount = 0;
  3156. /**
  3157. * Log a message to the console
  3158. */
  3159. Tools.Log = Tools._LogEnabled;
  3160. /**
  3161. * Write a warning message to the console
  3162. */
  3163. Tools.Warn = Tools._WarnEnabled;
  3164. /**
  3165. * Write an error message to the console
  3166. */
  3167. Tools.Error = Tools._ErrorEnabled;
  3168. // Performances
  3169. /**
  3170. * No performance log
  3171. */
  3172. Tools.PerformanceNoneLogLevel = 0;
  3173. /**
  3174. * Use user marks to log performance
  3175. */
  3176. Tools.PerformanceUserMarkLogLevel = 1;
  3177. /**
  3178. * Log performance to the console
  3179. */
  3180. Tools.PerformanceConsoleLogLevel = 2;
  3181. /**
  3182. * Starts a performance counter
  3183. */
  3184. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3185. /**
  3186. * Ends a specific performance coutner
  3187. */
  3188. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3189. return Tools;
  3190. }());
  3191. BABYLON.Tools = Tools;
  3192. /**
  3193. * This class is used to track a performance counter which is number based.
  3194. * The user has access to many properties which give statistics of different nature.
  3195. *
  3196. * The implementer can track two kinds of Performance Counter: time and count.
  3197. * 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.
  3198. * 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.
  3199. */
  3200. var PerfCounter = /** @class */ (function () {
  3201. /**
  3202. * Creates a new counter
  3203. */
  3204. function PerfCounter() {
  3205. this._startMonitoringTime = 0;
  3206. this._min = 0;
  3207. this._max = 0;
  3208. this._average = 0;
  3209. this._lastSecAverage = 0;
  3210. this._current = 0;
  3211. this._totalValueCount = 0;
  3212. this._totalAccumulated = 0;
  3213. this._lastSecAccumulated = 0;
  3214. this._lastSecTime = 0;
  3215. this._lastSecValueCount = 0;
  3216. }
  3217. Object.defineProperty(PerfCounter.prototype, "min", {
  3218. /**
  3219. * Returns the smallest value ever
  3220. */
  3221. get: function () {
  3222. return this._min;
  3223. },
  3224. enumerable: true,
  3225. configurable: true
  3226. });
  3227. Object.defineProperty(PerfCounter.prototype, "max", {
  3228. /**
  3229. * Returns the biggest value ever
  3230. */
  3231. get: function () {
  3232. return this._max;
  3233. },
  3234. enumerable: true,
  3235. configurable: true
  3236. });
  3237. Object.defineProperty(PerfCounter.prototype, "average", {
  3238. /**
  3239. * Returns the average value since the performance counter is running
  3240. */
  3241. get: function () {
  3242. return this._average;
  3243. },
  3244. enumerable: true,
  3245. configurable: true
  3246. });
  3247. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  3248. /**
  3249. * Returns the average value of the last second the counter was monitored
  3250. */
  3251. get: function () {
  3252. return this._lastSecAverage;
  3253. },
  3254. enumerable: true,
  3255. configurable: true
  3256. });
  3257. Object.defineProperty(PerfCounter.prototype, "current", {
  3258. /**
  3259. * Returns the current value
  3260. */
  3261. get: function () {
  3262. return this._current;
  3263. },
  3264. enumerable: true,
  3265. configurable: true
  3266. });
  3267. Object.defineProperty(PerfCounter.prototype, "total", {
  3268. /**
  3269. * Gets the accumulated total
  3270. */
  3271. get: function () {
  3272. return this._totalAccumulated;
  3273. },
  3274. enumerable: true,
  3275. configurable: true
  3276. });
  3277. Object.defineProperty(PerfCounter.prototype, "count", {
  3278. /**
  3279. * Gets the total value count
  3280. */
  3281. get: function () {
  3282. return this._totalValueCount;
  3283. },
  3284. enumerable: true,
  3285. configurable: true
  3286. });
  3287. /**
  3288. * Call this method to start monitoring a new frame.
  3289. * 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.
  3290. */
  3291. PerfCounter.prototype.fetchNewFrame = function () {
  3292. this._totalValueCount++;
  3293. this._current = 0;
  3294. this._lastSecValueCount++;
  3295. };
  3296. /**
  3297. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  3298. * @param newCount the count value to add to the monitored count
  3299. * @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.
  3300. */
  3301. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  3302. if (!PerfCounter.Enabled) {
  3303. return;
  3304. }
  3305. this._current += newCount;
  3306. if (fetchResult) {
  3307. this._fetchResult();
  3308. }
  3309. };
  3310. /**
  3311. * Start monitoring this performance counter
  3312. */
  3313. PerfCounter.prototype.beginMonitoring = function () {
  3314. if (!PerfCounter.Enabled) {
  3315. return;
  3316. }
  3317. this._startMonitoringTime = Tools.Now;
  3318. };
  3319. /**
  3320. * Compute the time lapsed since the previous beginMonitoring() call.
  3321. * @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
  3322. */
  3323. PerfCounter.prototype.endMonitoring = function (newFrame) {
  3324. if (newFrame === void 0) { newFrame = true; }
  3325. if (!PerfCounter.Enabled) {
  3326. return;
  3327. }
  3328. if (newFrame) {
  3329. this.fetchNewFrame();
  3330. }
  3331. var currentTime = Tools.Now;
  3332. this._current = currentTime - this._startMonitoringTime;
  3333. if (newFrame) {
  3334. this._fetchResult();
  3335. }
  3336. };
  3337. PerfCounter.prototype._fetchResult = function () {
  3338. this._totalAccumulated += this._current;
  3339. this._lastSecAccumulated += this._current;
  3340. // Min/Max update
  3341. this._min = Math.min(this._min, this._current);
  3342. this._max = Math.max(this._max, this._current);
  3343. this._average = this._totalAccumulated / this._totalValueCount;
  3344. // Reset last sec?
  3345. var now = Tools.Now;
  3346. if ((now - this._lastSecTime) > 1000) {
  3347. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  3348. this._lastSecTime = now;
  3349. this._lastSecAccumulated = 0;
  3350. this._lastSecValueCount = 0;
  3351. }
  3352. };
  3353. /**
  3354. * Gets or sets a global boolean to turn on and off all the counters
  3355. */
  3356. PerfCounter.Enabled = true;
  3357. return PerfCounter;
  3358. }());
  3359. BABYLON.PerfCounter = PerfCounter;
  3360. /**
  3361. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  3362. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  3363. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  3364. * @param name The name of the class, case should be preserved
  3365. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  3366. */
  3367. function className(name, module) {
  3368. return function (target) {
  3369. target["__bjsclassName__"] = name;
  3370. target["__bjsmoduleName__"] = (module != null) ? module : null;
  3371. };
  3372. }
  3373. BABYLON.className = className;
  3374. /**
  3375. * An implementation of a loop for asynchronous functions.
  3376. */
  3377. var AsyncLoop = /** @class */ (function () {
  3378. /**
  3379. * Constructor.
  3380. * @param iterations the number of iterations.
  3381. * @param func the function to run each iteration
  3382. * @param successCallback the callback that will be called upon succesful execution
  3383. * @param offset starting offset.
  3384. */
  3385. function AsyncLoop(
  3386. /**
  3387. * Defines the number of iterations for the loop
  3388. */
  3389. iterations, func, successCallback, offset) {
  3390. if (offset === void 0) { offset = 0; }
  3391. this.iterations = iterations;
  3392. this.index = offset - 1;
  3393. this._done = false;
  3394. this._fn = func;
  3395. this._successCallback = successCallback;
  3396. }
  3397. /**
  3398. * Execute the next iteration. Must be called after the last iteration was finished.
  3399. */
  3400. AsyncLoop.prototype.executeNext = function () {
  3401. if (!this._done) {
  3402. if (this.index + 1 < this.iterations) {
  3403. ++this.index;
  3404. this._fn(this);
  3405. }
  3406. else {
  3407. this.breakLoop();
  3408. }
  3409. }
  3410. };
  3411. /**
  3412. * Break the loop and run the success callback.
  3413. */
  3414. AsyncLoop.prototype.breakLoop = function () {
  3415. this._done = true;
  3416. this._successCallback();
  3417. };
  3418. /**
  3419. * Create and run an async loop.
  3420. * @param iterations the number of iterations.
  3421. * @param fn the function to run each iteration
  3422. * @param successCallback the callback that will be called upon succesful execution
  3423. * @param offset starting offset.
  3424. * @returns the created async loop object
  3425. */
  3426. AsyncLoop.Run = function (iterations, fn, successCallback, offset) {
  3427. if (offset === void 0) { offset = 0; }
  3428. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  3429. loop.executeNext();
  3430. return loop;
  3431. };
  3432. /**
  3433. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3434. * @param iterations total number of iterations
  3435. * @param syncedIterations number of synchronous iterations in each async iteration.
  3436. * @param fn the function to call each iteration.
  3437. * @param callback a success call back that will be called when iterating stops.
  3438. * @param breakFunction a break condition (optional)
  3439. * @param timeout timeout settings for the setTimeout function. default - 0.
  3440. * @returns the created async loop object
  3441. */
  3442. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3443. if (timeout === void 0) { timeout = 0; }
  3444. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3445. if (breakFunction && breakFunction()) {
  3446. loop.breakLoop();
  3447. }
  3448. else {
  3449. setTimeout(function () {
  3450. for (var i = 0; i < syncedIterations; ++i) {
  3451. var iteration = (loop.index * syncedIterations) + i;
  3452. if (iteration >= iterations) {
  3453. break;
  3454. }
  3455. fn(iteration);
  3456. if (breakFunction && breakFunction()) {
  3457. loop.breakLoop();
  3458. break;
  3459. }
  3460. }
  3461. loop.executeNext();
  3462. }, timeout);
  3463. }
  3464. }, callback);
  3465. };
  3466. return AsyncLoop;
  3467. }());
  3468. BABYLON.AsyncLoop = AsyncLoop;
  3469. })(BABYLON || (BABYLON = {}));
  3470. //# sourceMappingURL=tools.js.map
  3471. var BABYLON;
  3472. (function (BABYLON) {
  3473. /**
  3474. * Constant used to convert a value to gamma space
  3475. * @ignorenaming
  3476. */
  3477. BABYLON.ToGammaSpace = 1 / 2.2;
  3478. /**
  3479. * Constant used to convert a value to linear space
  3480. * @ignorenaming
  3481. */
  3482. BABYLON.ToLinearSpace = 2.2;
  3483. /**
  3484. * Constant used to define the minimal number value in Babylon.js
  3485. * @ignorenaming
  3486. */
  3487. BABYLON.Epsilon = 0.001;
  3488. /**
  3489. * Class used to hold a RBG color
  3490. */
  3491. var Color3 = /** @class */ (function () {
  3492. /**
  3493. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  3494. * @param r defines the red component (between 0 and 1, default is 0)
  3495. * @param g defines the green component (between 0 and 1, default is 0)
  3496. * @param b defines the blue component (between 0 and 1, default is 0)
  3497. */
  3498. function Color3(
  3499. /**
  3500. * Defines the red component (between 0 and 1, default is 0)
  3501. */
  3502. r,
  3503. /**
  3504. * Defines the green component (between 0 and 1, default is 0)
  3505. */
  3506. g,
  3507. /**
  3508. * Defines the blue component (between 0 and 1, default is 0)
  3509. */
  3510. b) {
  3511. if (r === void 0) { r = 0; }
  3512. if (g === void 0) { g = 0; }
  3513. if (b === void 0) { b = 0; }
  3514. this.r = r;
  3515. this.g = g;
  3516. this.b = b;
  3517. }
  3518. /**
  3519. * Creates a string with the Color3 current values
  3520. * @returns the string representation of the Color3 object
  3521. */
  3522. Color3.prototype.toString = function () {
  3523. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  3524. };
  3525. /**
  3526. * Returns the string "Color3"
  3527. * @returns "Color3"
  3528. */
  3529. Color3.prototype.getClassName = function () {
  3530. return "Color3";
  3531. };
  3532. /**
  3533. * Compute the Color3 hash code
  3534. * @returns an unique number that can be used to hash Color3 objects
  3535. */
  3536. Color3.prototype.getHashCode = function () {
  3537. var hash = this.r || 0;
  3538. hash = (hash * 397) ^ (this.g || 0);
  3539. hash = (hash * 397) ^ (this.b || 0);
  3540. return hash;
  3541. };
  3542. // Operators
  3543. /**
  3544. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  3545. * @param array defines the array where to store the r,g,b components
  3546. * @param index defines an optional index in the target array to define where to start storing values
  3547. * @returns the current Color3 object
  3548. */
  3549. Color3.prototype.toArray = function (array, index) {
  3550. if (index === void 0) { index = 0; }
  3551. array[index] = this.r;
  3552. array[index + 1] = this.g;
  3553. array[index + 2] = this.b;
  3554. return this;
  3555. };
  3556. /**
  3557. * Returns a new Color4 object from the current Color3 and the given alpha
  3558. * @param alpha defines the alpha component on the new Color4 object (default is 1)
  3559. * @returns a new Color4 object
  3560. */
  3561. Color3.prototype.toColor4 = function (alpha) {
  3562. if (alpha === void 0) { alpha = 1; }
  3563. return new Color4(this.r, this.g, this.b, alpha);
  3564. };
  3565. /**
  3566. * Returns a new array populated with 3 numeric elements : red, green and blue values
  3567. * @returns the new array
  3568. */
  3569. Color3.prototype.asArray = function () {
  3570. var result = new Array();
  3571. this.toArray(result, 0);
  3572. return result;
  3573. };
  3574. /**
  3575. * Returns the luminance value
  3576. * @returns a float value
  3577. */
  3578. Color3.prototype.toLuminance = function () {
  3579. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  3580. };
  3581. /**
  3582. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  3583. * @param otherColor defines the second operand
  3584. * @returns the new Color3 object
  3585. */
  3586. Color3.prototype.multiply = function (otherColor) {
  3587. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  3588. };
  3589. /**
  3590. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  3591. * @param otherColor defines the second operand
  3592. * @param result defines the Color3 object where to store the result
  3593. * @returns the current Color3
  3594. */
  3595. Color3.prototype.multiplyToRef = function (otherColor, result) {
  3596. result.r = this.r * otherColor.r;
  3597. result.g = this.g * otherColor.g;
  3598. result.b = this.b * otherColor.b;
  3599. return this;
  3600. };
  3601. /**
  3602. * Determines equality between Color3 objects
  3603. * @param otherColor defines the second operand
  3604. * @returns true if the rgb values are equal to the given ones
  3605. */
  3606. Color3.prototype.equals = function (otherColor) {
  3607. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  3608. };
  3609. /**
  3610. * Determines equality between the current Color3 object and a set of r,b,g values
  3611. * @param r defines the red component to check
  3612. * @param g defines the green component to check
  3613. * @param b defines the blue component to check
  3614. * @returns true if the rgb values are equal to the given ones
  3615. */
  3616. Color3.prototype.equalsFloats = function (r, g, b) {
  3617. return this.r === r && this.g === g && this.b === b;
  3618. };
  3619. /**
  3620. * Multiplies in place each rgb value by scale
  3621. * @param scale defines the scaling factor
  3622. * @returns the updated Color3
  3623. */
  3624. Color3.prototype.scale = function (scale) {
  3625. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  3626. };
  3627. /**
  3628. * Multiplies the rgb values by scale and stores the result into "result"
  3629. * @param scale defines the scaling factor
  3630. * @param result defines the Color3 object where to store the result
  3631. * @returns the unmodified current Color3
  3632. */
  3633. Color3.prototype.scaleToRef = function (scale, result) {
  3634. result.r = this.r * scale;
  3635. result.g = this.g * scale;
  3636. result.b = this.b * scale;
  3637. return this;
  3638. };
  3639. /**
  3640. * Scale the current Color3 values by a factor and add the result to a given Color3
  3641. * @param scale defines the scale factor
  3642. * @param result defines color to store the result into
  3643. * @returns the unmodified current Color3
  3644. */
  3645. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  3646. result.r += this.r * scale;
  3647. result.g += this.g * scale;
  3648. result.b += this.b * scale;
  3649. return this;
  3650. };
  3651. /**
  3652. * Clamps the rgb values by the min and max values and stores the result into "result"
  3653. * @param min defines minimum clamping value (default is 0)
  3654. * @param max defines maximum clamping value (default is 1)
  3655. * @param result defines color to store the result into
  3656. * @returns the original Color3
  3657. */
  3658. Color3.prototype.clampToRef = function (min, max, result) {
  3659. if (min === void 0) { min = 0; }
  3660. if (max === void 0) { max = 1; }
  3661. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  3662. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  3663. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  3664. return this;
  3665. };
  3666. /**
  3667. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  3668. * @param otherColor defines the second operand
  3669. * @returns the new Color3
  3670. */
  3671. Color3.prototype.add = function (otherColor) {
  3672. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  3673. };
  3674. /**
  3675. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  3676. * @param otherColor defines the second operand
  3677. * @param result defines Color3 object to store the result into
  3678. * @returns the unmodified current Color3
  3679. */
  3680. Color3.prototype.addToRef = function (otherColor, result) {
  3681. result.r = this.r + otherColor.r;
  3682. result.g = this.g + otherColor.g;
  3683. result.b = this.b + otherColor.b;
  3684. return this;
  3685. };
  3686. /**
  3687. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  3688. * @param otherColor defines the second operand
  3689. * @returns the new Color3
  3690. */
  3691. Color3.prototype.subtract = function (otherColor) {
  3692. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  3693. };
  3694. /**
  3695. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  3696. * @param otherColor defines the second operand
  3697. * @param result defines Color3 object to store the result into
  3698. * @returns the unmodified current Color3
  3699. */
  3700. Color3.prototype.subtractToRef = function (otherColor, result) {
  3701. result.r = this.r - otherColor.r;
  3702. result.g = this.g - otherColor.g;
  3703. result.b = this.b - otherColor.b;
  3704. return this;
  3705. };
  3706. /**
  3707. * Copy the current object
  3708. * @returns a new Color3 copied the current one
  3709. */
  3710. Color3.prototype.clone = function () {
  3711. return new Color3(this.r, this.g, this.b);
  3712. };
  3713. /**
  3714. * Copies the rgb values from the source in the current Color3
  3715. * @param source defines the source Color3 object
  3716. * @returns the updated Color3 object
  3717. */
  3718. Color3.prototype.copyFrom = function (source) {
  3719. this.r = source.r;
  3720. this.g = source.g;
  3721. this.b = source.b;
  3722. return this;
  3723. };
  3724. /**
  3725. * Updates the Color3 rgb values from the given floats
  3726. * @param r defines the red component to read from
  3727. * @param g defines the green component to read from
  3728. * @param b defines the blue component to read from
  3729. * @returns the current Color3 object
  3730. */
  3731. Color3.prototype.copyFromFloats = function (r, g, b) {
  3732. this.r = r;
  3733. this.g = g;
  3734. this.b = b;
  3735. return this;
  3736. };
  3737. /**
  3738. * Updates the Color3 rgb values from the given floats
  3739. * @param r defines the red component to read from
  3740. * @param g defines the green component to read from
  3741. * @param b defines the blue component to read from
  3742. * @returns the current Color3 object
  3743. */
  3744. Color3.prototype.set = function (r, g, b) {
  3745. return this.copyFromFloats(r, g, b);
  3746. };
  3747. /**
  3748. * Compute the Color3 hexadecimal code as a string
  3749. * @returns a string containing the hexadecimal representation of the Color3 object
  3750. */
  3751. Color3.prototype.toHexString = function () {
  3752. var intR = (this.r * 255) | 0;
  3753. var intG = (this.g * 255) | 0;
  3754. var intB = (this.b * 255) | 0;
  3755. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  3756. };
  3757. /**
  3758. * Computes a new Color3 converted from the current one to linear space
  3759. * @returns a new Color3 object
  3760. */
  3761. Color3.prototype.toLinearSpace = function () {
  3762. var convertedColor = new Color3();
  3763. this.toLinearSpaceToRef(convertedColor);
  3764. return convertedColor;
  3765. };
  3766. /**
  3767. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  3768. * @param convertedColor defines the Color3 object where to store the linear space version
  3769. * @returns the unmodified Color3
  3770. */
  3771. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  3772. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  3773. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  3774. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  3775. return this;
  3776. };
  3777. /**
  3778. * Computes a new Color3 converted from the current one to gamma space
  3779. * @returns a new Color3 object
  3780. */
  3781. Color3.prototype.toGammaSpace = function () {
  3782. var convertedColor = new Color3();
  3783. this.toGammaSpaceToRef(convertedColor);
  3784. return convertedColor;
  3785. };
  3786. /**
  3787. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  3788. * @param convertedColor defines the Color3 object where to store the gamma space version
  3789. * @returns the unmodified Color3
  3790. */
  3791. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  3792. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  3793. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  3794. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  3795. return this;
  3796. };
  3797. // Statics
  3798. /**
  3799. * Creates a new Color3 from the string containing valid hexadecimal values
  3800. * @param hex defines a string containing valid hexadecimal values
  3801. * @returns a new Color3 object
  3802. */
  3803. Color3.FromHexString = function (hex) {
  3804. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  3805. return new Color3(0, 0, 0);
  3806. }
  3807. var r = parseInt(hex.substring(1, 3), 16);
  3808. var g = parseInt(hex.substring(3, 5), 16);
  3809. var b = parseInt(hex.substring(5, 7), 16);
  3810. return Color3.FromInts(r, g, b);
  3811. };
  3812. /**
  3813. * Creates a new Vector3 from the starting index of the given array
  3814. * @param array defines the source array
  3815. * @param offset defines an offset in the source array
  3816. * @returns a new Color3 object
  3817. */
  3818. Color3.FromArray = function (array, offset) {
  3819. if (offset === void 0) { offset = 0; }
  3820. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  3821. };
  3822. /**
  3823. * Creates a new Color3 from integer values (< 256)
  3824. * @param r defines the red component to read from (value between 0 and 255)
  3825. * @param g defines the green component to read from (value between 0 and 255)
  3826. * @param b defines the blue component to read from (value between 0 and 255)
  3827. * @returns a new Color3 object
  3828. */
  3829. Color3.FromInts = function (r, g, b) {
  3830. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  3831. };
  3832. /**
  3833. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  3834. * @param start defines the start Color3 value
  3835. * @param end defines the end Color3 value
  3836. * @param amount defines the gradient value between start and end
  3837. * @returns a new Color3 object
  3838. */
  3839. Color3.Lerp = function (start, end, amount) {
  3840. var result = new Color3(0.0, 0.0, 0.0);
  3841. Color3.LerpToRef(start, end, amount, result);
  3842. return result;
  3843. };
  3844. /**
  3845. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  3846. * @param left defines the start value
  3847. * @param right defines the end value
  3848. * @param amount defines the gradient factor
  3849. * @param result defines the Color3 object where to store the result
  3850. */
  3851. Color3.LerpToRef = function (left, right, amount, result) {
  3852. result.r = left.r + ((right.r - left.r) * amount);
  3853. result.g = left.g + ((right.g - left.g) * amount);
  3854. result.b = left.b + ((right.b - left.b) * amount);
  3855. };
  3856. /**
  3857. * Returns a Color3 value containing a red color
  3858. * @returns a new Color3 object
  3859. */
  3860. Color3.Red = function () { return new Color3(1, 0, 0); };
  3861. /**
  3862. * Returns a Color3 value containing a green color
  3863. * @returns a new Color3 object
  3864. */
  3865. Color3.Green = function () { return new Color3(0, 1, 0); };
  3866. /**
  3867. * Returns a Color3 value containing a blue color
  3868. * @returns a new Color3 object
  3869. */
  3870. Color3.Blue = function () { return new Color3(0, 0, 1); };
  3871. /**
  3872. * Returns a Color3 value containing a black color
  3873. * @returns a new Color3 object
  3874. */
  3875. Color3.Black = function () { return new Color3(0, 0, 0); };
  3876. /**
  3877. * Returns a Color3 value containing a white color
  3878. * @returns a new Color3 object
  3879. */
  3880. Color3.White = function () { return new Color3(1, 1, 1); };
  3881. /**
  3882. * Returns a Color3 value containing a purple color
  3883. * @returns a new Color3 object
  3884. */
  3885. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  3886. /**
  3887. * Returns a Color3 value containing a magenta color
  3888. * @returns a new Color3 object
  3889. */
  3890. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  3891. /**
  3892. * Returns a Color3 value containing a yellow color
  3893. * @returns a new Color3 object
  3894. */
  3895. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  3896. /**
  3897. * Returns a Color3 value containing a gray color
  3898. * @returns a new Color3 object
  3899. */
  3900. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  3901. /**
  3902. * Returns a Color3 value containing a teal color
  3903. * @returns a new Color3 object
  3904. */
  3905. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  3906. /**
  3907. * Returns a Color3 value containing a random color
  3908. * @returns a new Color3 object
  3909. */
  3910. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  3911. return Color3;
  3912. }());
  3913. BABYLON.Color3 = Color3;
  3914. /**
  3915. * Class used to hold a RBGA color
  3916. */
  3917. var Color4 = /** @class */ (function () {
  3918. /**
  3919. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  3920. * @param r defines the red component (between 0 and 1, default is 0)
  3921. * @param g defines the green component (between 0 and 1, default is 0)
  3922. * @param b defines the blue component (between 0 and 1, default is 0)
  3923. * @param a defines the alpha component (between 0 and 1, default is 1)
  3924. */
  3925. function Color4(
  3926. /**
  3927. * Defines the red component (between 0 and 1, default is 0)
  3928. */
  3929. r,
  3930. /**
  3931. * Defines the green component (between 0 and 1, default is 0)
  3932. */
  3933. g,
  3934. /**
  3935. * Defines the blue component (between 0 and 1, default is 0)
  3936. */
  3937. b,
  3938. /**
  3939. * Defines the alpha component (between 0 and 1, default is 1)
  3940. */
  3941. a) {
  3942. if (r === void 0) { r = 0; }
  3943. if (g === void 0) { g = 0; }
  3944. if (b === void 0) { b = 0; }
  3945. if (a === void 0) { a = 1; }
  3946. this.r = r;
  3947. this.g = g;
  3948. this.b = b;
  3949. this.a = a;
  3950. }
  3951. // Operators
  3952. /**
  3953. * Adds in place the given Color4 values to the current Color4 object
  3954. * @param right defines the second operand
  3955. * @returns the current updated Color4 object
  3956. */
  3957. Color4.prototype.addInPlace = function (right) {
  3958. this.r += right.r;
  3959. this.g += right.g;
  3960. this.b += right.b;
  3961. this.a += right.a;
  3962. return this;
  3963. };
  3964. /**
  3965. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  3966. * @returns the new array
  3967. */
  3968. Color4.prototype.asArray = function () {
  3969. var result = new Array();
  3970. this.toArray(result, 0);
  3971. return result;
  3972. };
  3973. /**
  3974. * Stores from the starting index in the given array the Color4 successive values
  3975. * @param array defines the array where to store the r,g,b components
  3976. * @param index defines an optional index in the target array to define where to start storing values
  3977. * @returns the current Color4 object
  3978. */
  3979. Color4.prototype.toArray = function (array, index) {
  3980. if (index === void 0) { index = 0; }
  3981. array[index] = this.r;
  3982. array[index + 1] = this.g;
  3983. array[index + 2] = this.b;
  3984. array[index + 3] = this.a;
  3985. return this;
  3986. };
  3987. /**
  3988. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  3989. * @param right defines the second operand
  3990. * @returns a new Color4 object
  3991. */
  3992. Color4.prototype.add = function (right) {
  3993. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  3994. };
  3995. /**
  3996. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  3997. * @param right defines the second operand
  3998. * @returns a new Color4 object
  3999. */
  4000. Color4.prototype.subtract = function (right) {
  4001. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  4002. };
  4003. /**
  4004. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  4005. * @param right defines the second operand
  4006. * @param result defines the Color4 object where to store the result
  4007. * @returns the current Color4 object
  4008. */
  4009. Color4.prototype.subtractToRef = function (right, result) {
  4010. result.r = this.r - right.r;
  4011. result.g = this.g - right.g;
  4012. result.b = this.b - right.b;
  4013. result.a = this.a - right.a;
  4014. return this;
  4015. };
  4016. /**
  4017. * Creates a new Color4 with the current Color4 values multiplied by scale
  4018. * @param scale defines the scaling factor to apply
  4019. * @returns a new Color4 object
  4020. */
  4021. Color4.prototype.scale = function (scale) {
  4022. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  4023. };
  4024. /**
  4025. * Multiplies the current Color4 values by scale and stores the result in "result"
  4026. * @param scale defines the scaling factor to apply
  4027. * @param result defines the Color4 object where to store the result
  4028. * @returns the current unmodified Color4
  4029. */
  4030. Color4.prototype.scaleToRef = function (scale, result) {
  4031. result.r = this.r * scale;
  4032. result.g = this.g * scale;
  4033. result.b = this.b * scale;
  4034. result.a = this.a * scale;
  4035. return this;
  4036. };
  4037. /**
  4038. * Scale the current Color4 values by a factor and add the result to a given Color4
  4039. * @param scale defines the scale factor
  4040. * @param result defines the Color4 object where to store the result
  4041. * @returns the unmodified current Color4
  4042. */
  4043. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  4044. result.r += this.r * scale;
  4045. result.g += this.g * scale;
  4046. result.b += this.b * scale;
  4047. result.a += this.a * scale;
  4048. return this;
  4049. };
  4050. /**
  4051. * Clamps the rgb values by the min and max values and stores the result into "result"
  4052. * @param min defines minimum clamping value (default is 0)
  4053. * @param max defines maximum clamping value (default is 1)
  4054. * @param result defines color to store the result into.
  4055. * @returns the cuurent Color4
  4056. */
  4057. Color4.prototype.clampToRef = function (min, max, result) {
  4058. if (min === void 0) { min = 0; }
  4059. if (max === void 0) { max = 1; }
  4060. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  4061. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  4062. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  4063. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  4064. return this;
  4065. };
  4066. /**
  4067. * Multipy an Color4 value by another and return a new Color4 object
  4068. * @param color defines the Color4 value to multiply by
  4069. * @returns a new Color4 object
  4070. */
  4071. Color4.prototype.multiply = function (color) {
  4072. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  4073. };
  4074. /**
  4075. * Multipy a Color4 value by another and push the result in a reference value
  4076. * @param color defines the Color4 value to multiply by
  4077. * @param result defines the Color4 to fill the result in
  4078. * @returns the result Color4
  4079. */
  4080. Color4.prototype.multiplyToRef = function (color, result) {
  4081. result.r = this.r * color.r;
  4082. result.g = this.g * color.g;
  4083. result.b = this.b * color.b;
  4084. result.a = this.a * color.a;
  4085. return result;
  4086. };
  4087. /**
  4088. * Creates a string with the Color4 current values
  4089. * @returns the string representation of the Color4 object
  4090. */
  4091. Color4.prototype.toString = function () {
  4092. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  4093. };
  4094. /**
  4095. * Returns the string "Color4"
  4096. * @returns "Color4"
  4097. */
  4098. Color4.prototype.getClassName = function () {
  4099. return "Color4";
  4100. };
  4101. /**
  4102. * Compute the Color4 hash code
  4103. * @returns an unique number that can be used to hash Color4 objects
  4104. */
  4105. Color4.prototype.getHashCode = function () {
  4106. var hash = this.r || 0;
  4107. hash = (hash * 397) ^ (this.g || 0);
  4108. hash = (hash * 397) ^ (this.b || 0);
  4109. hash = (hash * 397) ^ (this.a || 0);
  4110. return hash;
  4111. };
  4112. /**
  4113. * Creates a new Color4 copied from the current one
  4114. * @returns a new Color4 object
  4115. */
  4116. Color4.prototype.clone = function () {
  4117. return new Color4(this.r, this.g, this.b, this.a);
  4118. };
  4119. /**
  4120. * Copies the given Color4 values into the current one
  4121. * @param source defines the source Color4 object
  4122. * @returns the current updated Color4 object
  4123. */
  4124. Color4.prototype.copyFrom = function (source) {
  4125. this.r = source.r;
  4126. this.g = source.g;
  4127. this.b = source.b;
  4128. this.a = source.a;
  4129. return this;
  4130. };
  4131. /**
  4132. * Copies the given float values into the current one
  4133. * @param r defines the red component to read from
  4134. * @param g defines the green component to read from
  4135. * @param b defines the blue component to read from
  4136. * @param a defines the alpha component to read from
  4137. * @returns the current updated Color4 object
  4138. */
  4139. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  4140. this.r = r;
  4141. this.g = g;
  4142. this.b = b;
  4143. this.a = a;
  4144. return this;
  4145. };
  4146. /**
  4147. * Copies the given float values into the current one
  4148. * @param r defines the red component to read from
  4149. * @param g defines the green component to read from
  4150. * @param b defines the blue component to read from
  4151. * @param a defines the alpha component to read from
  4152. * @returns the current updated Color4 object
  4153. */
  4154. Color4.prototype.set = function (r, g, b, a) {
  4155. return this.copyFromFloats(r, g, b, a);
  4156. };
  4157. /**
  4158. * Compute the Color4 hexadecimal code as a string
  4159. * @returns a string containing the hexadecimal representation of the Color4 object
  4160. */
  4161. Color4.prototype.toHexString = function () {
  4162. var intR = (this.r * 255) | 0;
  4163. var intG = (this.g * 255) | 0;
  4164. var intB = (this.b * 255) | 0;
  4165. var intA = (this.a * 255) | 0;
  4166. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  4167. };
  4168. /**
  4169. * Computes a new Color4 converted from the current one to linear space
  4170. * @returns a new Color4 object
  4171. */
  4172. Color4.prototype.toLinearSpace = function () {
  4173. var convertedColor = new Color4();
  4174. this.toLinearSpaceToRef(convertedColor);
  4175. return convertedColor;
  4176. };
  4177. /**
  4178. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  4179. * @param convertedColor defines the Color4 object where to store the linear space version
  4180. * @returns the unmodified Color4
  4181. */
  4182. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  4183. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  4184. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  4185. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  4186. convertedColor.a = this.a;
  4187. return this;
  4188. };
  4189. /**
  4190. * Computes a new Color4 converted from the current one to gamma space
  4191. * @returns a new Color4 object
  4192. */
  4193. Color4.prototype.toGammaSpace = function () {
  4194. var convertedColor = new Color4();
  4195. this.toGammaSpaceToRef(convertedColor);
  4196. return convertedColor;
  4197. };
  4198. /**
  4199. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  4200. * @param convertedColor defines the Color4 object where to store the gamma space version
  4201. * @returns the unmodified Color4
  4202. */
  4203. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  4204. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  4205. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  4206. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  4207. convertedColor.a = this.a;
  4208. return this;
  4209. };
  4210. // Statics
  4211. /**
  4212. * Creates a new Color4 from the string containing valid hexadecimal values
  4213. * @param hex defines a string containing valid hexadecimal values
  4214. * @returns a new Color4 object
  4215. */
  4216. Color4.FromHexString = function (hex) {
  4217. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  4218. return new Color4(0.0, 0.0, 0.0, 0.0);
  4219. }
  4220. var r = parseInt(hex.substring(1, 3), 16);
  4221. var g = parseInt(hex.substring(3, 5), 16);
  4222. var b = parseInt(hex.substring(5, 7), 16);
  4223. var a = parseInt(hex.substring(7, 9), 16);
  4224. return Color4.FromInts(r, g, b, a);
  4225. };
  4226. /**
  4227. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  4228. * @param left defines the start value
  4229. * @param right defines the end value
  4230. * @param amount defines the gradient factor
  4231. * @returns a new Color4 object
  4232. */
  4233. Color4.Lerp = function (left, right, amount) {
  4234. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  4235. Color4.LerpToRef(left, right, amount, result);
  4236. return result;
  4237. };
  4238. /**
  4239. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  4240. * @param left defines the start value
  4241. * @param right defines the end value
  4242. * @param amount defines the gradient factor
  4243. * @param result defines the Color4 object where to store data
  4244. */
  4245. Color4.LerpToRef = function (left, right, amount, result) {
  4246. result.r = left.r + (right.r - left.r) * amount;
  4247. result.g = left.g + (right.g - left.g) * amount;
  4248. result.b = left.b + (right.b - left.b) * amount;
  4249. result.a = left.a + (right.a - left.a) * amount;
  4250. };
  4251. /**
  4252. * Creates a new Color4 from a Color3 and an alpha value
  4253. * @param color3 defines the source Color3 to read from
  4254. * @param alpha defines the alpha component (1.0 by default)
  4255. * @returns a new Color4 object
  4256. */
  4257. Color4.FromColor3 = function (color3, alpha) {
  4258. if (alpha === void 0) { alpha = 1.0; }
  4259. return new Color4(color3.r, color3.g, color3.b, alpha);
  4260. };
  4261. /**
  4262. * Creates a new Color4 from the starting index element of the given array
  4263. * @param array defines the source array to read from
  4264. * @param offset defines the offset in the source array
  4265. * @returns a new Color4 object
  4266. */
  4267. Color4.FromArray = function (array, offset) {
  4268. if (offset === void 0) { offset = 0; }
  4269. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4270. };
  4271. /**
  4272. * Creates a new Color3 from integer values (< 256)
  4273. * @param r defines the red component to read from (value between 0 and 255)
  4274. * @param g defines the green component to read from (value between 0 and 255)
  4275. * @param b defines the blue component to read from (value between 0 and 255)
  4276. * @param a defines the alpha component to read from (value between 0 and 255)
  4277. * @returns a new Color3 object
  4278. */
  4279. Color4.FromInts = function (r, g, b, a) {
  4280. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  4281. };
  4282. /**
  4283. * Check the content of a given array and convert it to an array containing RGBA data
  4284. * If the original array was already containing count * 4 values then it is returned directly
  4285. * @param colors defines the array to check
  4286. * @param count defines the number of RGBA data to expect
  4287. * @returns an array containing count * 4 values (RGBA)
  4288. */
  4289. Color4.CheckColors4 = function (colors, count) {
  4290. // Check if color3 was used
  4291. if (colors.length === count * 3) {
  4292. var colors4 = [];
  4293. for (var index = 0; index < colors.length; index += 3) {
  4294. var newIndex = (index / 3) * 4;
  4295. colors4[newIndex] = colors[index];
  4296. colors4[newIndex + 1] = colors[index + 1];
  4297. colors4[newIndex + 2] = colors[index + 2];
  4298. colors4[newIndex + 3] = 1.0;
  4299. }
  4300. return colors4;
  4301. }
  4302. return colors;
  4303. };
  4304. return Color4;
  4305. }());
  4306. BABYLON.Color4 = Color4;
  4307. /**
  4308. * Class representing a vector containing 2 coordinates
  4309. */
  4310. var Vector2 = /** @class */ (function () {
  4311. /**
  4312. * Creates a new Vector2 from the given x and y coordinates
  4313. * @param x defines the first coordinate
  4314. * @param y defines the second coordinate
  4315. */
  4316. function Vector2(
  4317. /** defines the first coordinate */
  4318. x,
  4319. /** defines the second coordinate */
  4320. y) {
  4321. if (x === void 0) { x = 0; }
  4322. if (y === void 0) { y = 0; }
  4323. this.x = x;
  4324. this.y = y;
  4325. }
  4326. /**
  4327. * Gets a string with the Vector2 coordinates
  4328. * @returns a string with the Vector2 coordinates
  4329. */
  4330. Vector2.prototype.toString = function () {
  4331. return "{X: " + this.x + " Y:" + this.y + "}";
  4332. };
  4333. /**
  4334. * Gets class name
  4335. * @returns the string "Vector2"
  4336. */
  4337. Vector2.prototype.getClassName = function () {
  4338. return "Vector2";
  4339. };
  4340. /**
  4341. * Gets current vector hash code
  4342. * @returns the Vector2 hash code as a number
  4343. */
  4344. Vector2.prototype.getHashCode = function () {
  4345. var hash = this.x || 0;
  4346. hash = (hash * 397) ^ (this.y || 0);
  4347. return hash;
  4348. };
  4349. // Operators
  4350. /**
  4351. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  4352. * @param array defines the source array
  4353. * @param index defines the offset in source array
  4354. * @returns the current Vector2
  4355. */
  4356. Vector2.prototype.toArray = function (array, index) {
  4357. if (index === void 0) { index = 0; }
  4358. array[index] = this.x;
  4359. array[index + 1] = this.y;
  4360. return this;
  4361. };
  4362. /**
  4363. * Copy the current vector to an array
  4364. * @returns a new array with 2 elements: the Vector2 coordinates.
  4365. */
  4366. Vector2.prototype.asArray = function () {
  4367. var result = new Array();
  4368. this.toArray(result, 0);
  4369. return result;
  4370. };
  4371. /**
  4372. * Sets the Vector2 coordinates with the given Vector2 coordinates
  4373. * @param source defines the source Vector2
  4374. * @returns the current updated Vector2
  4375. */
  4376. Vector2.prototype.copyFrom = function (source) {
  4377. this.x = source.x;
  4378. this.y = source.y;
  4379. return this;
  4380. };
  4381. /**
  4382. * Sets the Vector2 coordinates with the given floats
  4383. * @param x defines the first coordinate
  4384. * @param y defines the second coordinate
  4385. * @returns the current updated Vector2
  4386. */
  4387. Vector2.prototype.copyFromFloats = function (x, y) {
  4388. this.x = x;
  4389. this.y = y;
  4390. return this;
  4391. };
  4392. /**
  4393. * Sets the Vector2 coordinates with the given floats
  4394. * @param x defines the first coordinate
  4395. * @param y defines the second coordinate
  4396. * @returns the current updated Vector2
  4397. */
  4398. Vector2.prototype.set = function (x, y) {
  4399. return this.copyFromFloats(x, y);
  4400. };
  4401. /**
  4402. * Add another vector with the current one
  4403. * @param otherVector defines the other vector
  4404. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  4405. */
  4406. Vector2.prototype.add = function (otherVector) {
  4407. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  4408. };
  4409. /**
  4410. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  4411. * @param otherVector defines the other vector
  4412. * @param result defines the target vector
  4413. * @returns the unmodified current Vector2
  4414. */
  4415. Vector2.prototype.addToRef = function (otherVector, result) {
  4416. result.x = this.x + otherVector.x;
  4417. result.y = this.y + otherVector.y;
  4418. return this;
  4419. };
  4420. /**
  4421. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  4422. * @param otherVector defines the other vector
  4423. * @returns the current updated Vector2
  4424. */
  4425. Vector2.prototype.addInPlace = function (otherVector) {
  4426. this.x += otherVector.x;
  4427. this.y += otherVector.y;
  4428. return this;
  4429. };
  4430. /**
  4431. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  4432. * @param otherVector defines the other vector
  4433. * @returns a new Vector2
  4434. */
  4435. Vector2.prototype.addVector3 = function (otherVector) {
  4436. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  4437. };
  4438. /**
  4439. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  4440. * @param otherVector defines the other vector
  4441. * @returns a new Vector2
  4442. */
  4443. Vector2.prototype.subtract = function (otherVector) {
  4444. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  4445. };
  4446. /**
  4447. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  4448. * @param otherVector defines the other vector
  4449. * @param result defines the target vector
  4450. * @returns the unmodified current Vector2
  4451. */
  4452. Vector2.prototype.subtractToRef = function (otherVector, result) {
  4453. result.x = this.x - otherVector.x;
  4454. result.y = this.y - otherVector.y;
  4455. return this;
  4456. };
  4457. /**
  4458. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  4459. * @param otherVector defines the other vector
  4460. * @returns the current updated Vector2
  4461. */
  4462. Vector2.prototype.subtractInPlace = function (otherVector) {
  4463. this.x -= otherVector.x;
  4464. this.y -= otherVector.y;
  4465. return this;
  4466. };
  4467. /**
  4468. * Multiplies in place the current Vector2 coordinates by the given ones
  4469. * @param otherVector defines the other vector
  4470. * @returns the current updated Vector2
  4471. */
  4472. Vector2.prototype.multiplyInPlace = function (otherVector) {
  4473. this.x *= otherVector.x;
  4474. this.y *= otherVector.y;
  4475. return this;
  4476. };
  4477. /**
  4478. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  4479. * @param otherVector defines the other vector
  4480. * @returns a new Vector2
  4481. */
  4482. Vector2.prototype.multiply = function (otherVector) {
  4483. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  4484. };
  4485. /**
  4486. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  4487. * @param otherVector defines the other vector
  4488. * @param result defines the target vector
  4489. * @returns the unmodified current Vector2
  4490. */
  4491. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  4492. result.x = this.x * otherVector.x;
  4493. result.y = this.y * otherVector.y;
  4494. return this;
  4495. };
  4496. /**
  4497. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  4498. * @param x defines the first coordinate
  4499. * @param y defines the second coordinate
  4500. * @returns a new Vector2
  4501. */
  4502. Vector2.prototype.multiplyByFloats = function (x, y) {
  4503. return new Vector2(this.x * x, this.y * y);
  4504. };
  4505. /**
  4506. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  4507. * @param otherVector defines the other vector
  4508. * @returns a new Vector2
  4509. */
  4510. Vector2.prototype.divide = function (otherVector) {
  4511. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  4512. };
  4513. /**
  4514. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  4515. * @param otherVector defines the other vector
  4516. * @param result defines the target vector
  4517. * @returns the unmodified current Vector2
  4518. */
  4519. Vector2.prototype.divideToRef = function (otherVector, result) {
  4520. result.x = this.x / otherVector.x;
  4521. result.y = this.y / otherVector.y;
  4522. return this;
  4523. };
  4524. /**
  4525. * Divides the current Vector2 coordinates by the given ones
  4526. * @param otherVector defines the other vector
  4527. * @returns the current updated Vector2
  4528. */
  4529. Vector2.prototype.divideInPlace = function (otherVector) {
  4530. return this.divideToRef(otherVector, this);
  4531. };
  4532. /**
  4533. * Gets a new Vector2 with current Vector2 negated coordinates
  4534. * @returns a new Vector2
  4535. */
  4536. Vector2.prototype.negate = function () {
  4537. return new Vector2(-this.x, -this.y);
  4538. };
  4539. /**
  4540. * Multiply the Vector2 coordinates by scale
  4541. * @param scale defines the scaling factor
  4542. * @returns the current updated Vector2
  4543. */
  4544. Vector2.prototype.scaleInPlace = function (scale) {
  4545. this.x *= scale;
  4546. this.y *= scale;
  4547. return this;
  4548. };
  4549. /**
  4550. * Returns a new Vector2 scaled by "scale" from the current Vector2
  4551. * @param scale defines the scaling factor
  4552. * @returns a new Vector2
  4553. */
  4554. Vector2.prototype.scale = function (scale) {
  4555. var result = new Vector2(0, 0);
  4556. this.scaleToRef(scale, result);
  4557. return result;
  4558. };
  4559. /**
  4560. * Scale the current Vector2 values by a factor to a given Vector2
  4561. * @param scale defines the scale factor
  4562. * @param result defines the Vector2 object where to store the result
  4563. * @returns the unmodified current Vector2
  4564. */
  4565. Vector2.prototype.scaleToRef = function (scale, result) {
  4566. result.x = this.x * scale;
  4567. result.y = this.y * scale;
  4568. return this;
  4569. };
  4570. /**
  4571. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  4572. * @param scale defines the scale factor
  4573. * @param result defines the Vector2 object where to store the result
  4574. * @returns the unmodified current Vector2
  4575. */
  4576. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  4577. result.x += this.x * scale;
  4578. result.y += this.y * scale;
  4579. return this;
  4580. };
  4581. /**
  4582. * Gets a boolean if two vectors are equals
  4583. * @param otherVector defines the other vector
  4584. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  4585. */
  4586. Vector2.prototype.equals = function (otherVector) {
  4587. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  4588. };
  4589. /**
  4590. * Gets a boolean if two vectors are equals (using an epsilon value)
  4591. * @param otherVector defines the other vector
  4592. * @param epsilon defines the minimal distance to consider equality
  4593. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  4594. */
  4595. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4596. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4597. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  4598. };
  4599. /**
  4600. * Gets a new Vector2 from current Vector2 floored values
  4601. * @returns a new Vector2
  4602. */
  4603. Vector2.prototype.floor = function () {
  4604. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  4605. };
  4606. /**
  4607. * Gets a new Vector2 from current Vector2 floored values
  4608. * @returns a new Vector2
  4609. */
  4610. Vector2.prototype.fract = function () {
  4611. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  4612. };
  4613. // Properties
  4614. /**
  4615. * Gets the length of the vector
  4616. * @returns the vector length (float)
  4617. */
  4618. Vector2.prototype.length = function () {
  4619. return Math.sqrt(this.x * this.x + this.y * this.y);
  4620. };
  4621. /**
  4622. * Gets the vector squared length
  4623. * @returns the vector squared length (float)
  4624. */
  4625. Vector2.prototype.lengthSquared = function () {
  4626. return (this.x * this.x + this.y * this.y);
  4627. };
  4628. // Methods
  4629. /**
  4630. * Normalize the vector
  4631. * @returns the current updated Vector2
  4632. */
  4633. Vector2.prototype.normalize = function () {
  4634. var len = this.length();
  4635. if (len === 0) {
  4636. return this;
  4637. }
  4638. var num = 1.0 / len;
  4639. this.x *= num;
  4640. this.y *= num;
  4641. return this;
  4642. };
  4643. /**
  4644. * Gets a new Vector2 copied from the Vector2
  4645. * @returns a new Vector2
  4646. */
  4647. Vector2.prototype.clone = function () {
  4648. return new Vector2(this.x, this.y);
  4649. };
  4650. // Statics
  4651. /**
  4652. * Gets a new Vector2(0, 0)
  4653. * @returns a new Vector2
  4654. */
  4655. Vector2.Zero = function () {
  4656. return new Vector2(0, 0);
  4657. };
  4658. /**
  4659. * Gets a new Vector2(1, 1)
  4660. * @returns a new Vector2
  4661. */
  4662. Vector2.One = function () {
  4663. return new Vector2(1, 1);
  4664. };
  4665. /**
  4666. * Gets a new Vector2 set from the given index element of the given array
  4667. * @param array defines the data source
  4668. * @param offset defines the offset in the data source
  4669. * @returns a new Vector2
  4670. */
  4671. Vector2.FromArray = function (array, offset) {
  4672. if (offset === void 0) { offset = 0; }
  4673. return new Vector2(array[offset], array[offset + 1]);
  4674. };
  4675. /**
  4676. * Sets "result" from the given index element of the given array
  4677. * @param array defines the data source
  4678. * @param offset defines the offset in the data source
  4679. * @param result defines the target vector
  4680. */
  4681. Vector2.FromArrayToRef = function (array, offset, result) {
  4682. result.x = array[offset];
  4683. result.y = array[offset + 1];
  4684. };
  4685. /**
  4686. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  4687. * @param value1 defines 1st point of control
  4688. * @param value2 defines 2nd point of control
  4689. * @param value3 defines 3rd point of control
  4690. * @param value4 defines 4th point of control
  4691. * @param amount defines the interpolation factor
  4692. * @returns a new Vector2
  4693. */
  4694. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  4695. var squared = amount * amount;
  4696. var cubed = amount * squared;
  4697. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  4698. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  4699. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  4700. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  4701. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  4702. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  4703. return new Vector2(x, y);
  4704. };
  4705. /**
  4706. * 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".
  4707. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  4708. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  4709. * @param value defines the value to clamp
  4710. * @param min defines the lower limit
  4711. * @param max defines the upper limit
  4712. * @returns a new Vector2
  4713. */
  4714. Vector2.Clamp = function (value, min, max) {
  4715. var x = value.x;
  4716. x = (x > max.x) ? max.x : x;
  4717. x = (x < min.x) ? min.x : x;
  4718. var y = value.y;
  4719. y = (y > max.y) ? max.y : y;
  4720. y = (y < min.y) ? min.y : y;
  4721. return new Vector2(x, y);
  4722. };
  4723. /**
  4724. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  4725. * @param value1 defines the 1st control point
  4726. * @param tangent1 defines the outgoing tangent
  4727. * @param value2 defines the 2nd control point
  4728. * @param tangent2 defines the incoming tangent
  4729. * @param amount defines the interpolation factor
  4730. * @returns a new Vector2
  4731. */
  4732. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4733. var squared = amount * amount;
  4734. var cubed = amount * squared;
  4735. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4736. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4737. var part3 = (cubed - (2.0 * squared)) + amount;
  4738. var part4 = cubed - squared;
  4739. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4740. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4741. return new Vector2(x, y);
  4742. };
  4743. /**
  4744. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  4745. * @param start defines the start vector
  4746. * @param end defines the end vector
  4747. * @param amount defines the interpolation factor
  4748. * @returns a new Vector2
  4749. */
  4750. Vector2.Lerp = function (start, end, amount) {
  4751. var x = start.x + ((end.x - start.x) * amount);
  4752. var y = start.y + ((end.y - start.y) * amount);
  4753. return new Vector2(x, y);
  4754. };
  4755. /**
  4756. * Gets the dot product of the vector "left" and the vector "right"
  4757. * @param left defines first vector
  4758. * @param right defines second vector
  4759. * @returns the dot product (float)
  4760. */
  4761. Vector2.Dot = function (left, right) {
  4762. return left.x * right.x + left.y * right.y;
  4763. };
  4764. /**
  4765. * Returns a new Vector2 equal to the normalized given vector
  4766. * @param vector defines the vector to normalize
  4767. * @returns a new Vector2
  4768. */
  4769. Vector2.Normalize = function (vector) {
  4770. var newVector = vector.clone();
  4771. newVector.normalize();
  4772. return newVector;
  4773. };
  4774. /**
  4775. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  4776. * @param left defines 1st vector
  4777. * @param right defines 2nd vector
  4778. * @returns a new Vector2
  4779. */
  4780. Vector2.Minimize = function (left, right) {
  4781. var x = (left.x < right.x) ? left.x : right.x;
  4782. var y = (left.y < right.y) ? left.y : right.y;
  4783. return new Vector2(x, y);
  4784. };
  4785. /**
  4786. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  4787. * @param left defines 1st vector
  4788. * @param right defines 2nd vector
  4789. * @returns a new Vector2
  4790. */
  4791. Vector2.Maximize = function (left, right) {
  4792. var x = (left.x > right.x) ? left.x : right.x;
  4793. var y = (left.y > right.y) ? left.y : right.y;
  4794. return new Vector2(x, y);
  4795. };
  4796. /**
  4797. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  4798. * @param vector defines the vector to transform
  4799. * @param transformation defines the matrix to apply
  4800. * @returns a new Vector2
  4801. */
  4802. Vector2.Transform = function (vector, transformation) {
  4803. var r = Vector2.Zero();
  4804. Vector2.TransformToRef(vector, transformation, r);
  4805. return r;
  4806. };
  4807. /**
  4808. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  4809. * @param vector defines the vector to transform
  4810. * @param transformation defines the matrix to apply
  4811. * @param result defines the target vector
  4812. */
  4813. Vector2.TransformToRef = function (vector, transformation, result) {
  4814. var m = transformation.m;
  4815. var x = (vector.x * m[0]) + (vector.y * m[4]) + m[12];
  4816. var y = (vector.x * m[1]) + (vector.y * m[5]) + m[13];
  4817. result.x = x;
  4818. result.y = y;
  4819. };
  4820. /**
  4821. * Determines if a given vector is included in a triangle
  4822. * @param p defines the vector to test
  4823. * @param p0 defines 1st triangle point
  4824. * @param p1 defines 2nd triangle point
  4825. * @param p2 defines 3rd triangle point
  4826. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  4827. */
  4828. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  4829. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  4830. var sign = a < 0 ? -1 : 1;
  4831. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  4832. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  4833. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  4834. };
  4835. /**
  4836. * Gets the distance between the vectors "value1" and "value2"
  4837. * @param value1 defines first vector
  4838. * @param value2 defines second vector
  4839. * @returns the distance between vectors
  4840. */
  4841. Vector2.Distance = function (value1, value2) {
  4842. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  4843. };
  4844. /**
  4845. * Returns the squared distance between the vectors "value1" and "value2"
  4846. * @param value1 defines first vector
  4847. * @param value2 defines second vector
  4848. * @returns the squared distance between vectors
  4849. */
  4850. Vector2.DistanceSquared = function (value1, value2) {
  4851. var x = value1.x - value2.x;
  4852. var y = value1.y - value2.y;
  4853. return (x * x) + (y * y);
  4854. };
  4855. /**
  4856. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  4857. * @param value1 defines first vector
  4858. * @param value2 defines second vector
  4859. * @returns a new Vector2
  4860. */
  4861. Vector2.Center = function (value1, value2) {
  4862. var center = value1.add(value2);
  4863. center.scaleInPlace(0.5);
  4864. return center;
  4865. };
  4866. /**
  4867. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  4868. * @param p defines the middle point
  4869. * @param segA defines one point of the segment
  4870. * @param segB defines the other point of the segment
  4871. * @returns the shortest distance
  4872. */
  4873. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  4874. var l2 = Vector2.DistanceSquared(segA, segB);
  4875. if (l2 === 0.0) {
  4876. return Vector2.Distance(p, segA);
  4877. }
  4878. var v = segB.subtract(segA);
  4879. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  4880. var proj = segA.add(v.multiplyByFloats(t, t));
  4881. return Vector2.Distance(p, proj);
  4882. };
  4883. return Vector2;
  4884. }());
  4885. BABYLON.Vector2 = Vector2;
  4886. /**
  4887. * Classed used to store (x,y,z) vector representation
  4888. * A Vector3 is the main object used in 3D geometry
  4889. * It can represent etiher the coordinates of a point the space, either a direction
  4890. * Reminder: Babylon.js uses a left handed forward facing system
  4891. */
  4892. var Vector3 = /** @class */ (function () {
  4893. /**
  4894. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  4895. * @param x defines the first coordinates (on X axis)
  4896. * @param y defines the second coordinates (on Y axis)
  4897. * @param z defines the third coordinates (on Z axis)
  4898. */
  4899. function Vector3(
  4900. /**
  4901. * Defines the first coordinates (on X axis)
  4902. */
  4903. x,
  4904. /**
  4905. * Defines the second coordinates (on Y axis)
  4906. */
  4907. y,
  4908. /**
  4909. * Defines the third coordinates (on Z axis)
  4910. */
  4911. z) {
  4912. if (x === void 0) { x = 0; }
  4913. if (y === void 0) { y = 0; }
  4914. if (z === void 0) { z = 0; }
  4915. this.x = x;
  4916. this.y = y;
  4917. this.z = z;
  4918. }
  4919. /**
  4920. * Creates a string representation of the Vector3
  4921. * @returns a string with the Vector3 coordinates.
  4922. */
  4923. Vector3.prototype.toString = function () {
  4924. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  4925. };
  4926. /**
  4927. * Gets the class name
  4928. * @returns the string "Vector3"
  4929. */
  4930. Vector3.prototype.getClassName = function () {
  4931. return "Vector3";
  4932. };
  4933. /**
  4934. * Creates the Vector3 hash code
  4935. * @returns a number which tends to be unique between Vector3 instances
  4936. */
  4937. Vector3.prototype.getHashCode = function () {
  4938. var hash = this.x || 0;
  4939. hash = (hash * 397) ^ (this.y || 0);
  4940. hash = (hash * 397) ^ (this.z || 0);
  4941. return hash;
  4942. };
  4943. // Operators
  4944. /**
  4945. * Creates an array containing three elements : the coordinates of the Vector3
  4946. * @returns a new array of numbers
  4947. */
  4948. Vector3.prototype.asArray = function () {
  4949. var result = [];
  4950. this.toArray(result, 0);
  4951. return result;
  4952. };
  4953. /**
  4954. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  4955. * @param array defines the destination array
  4956. * @param index defines the offset in the destination array
  4957. * @returns the current Vector3
  4958. */
  4959. Vector3.prototype.toArray = function (array, index) {
  4960. if (index === void 0) { index = 0; }
  4961. array[index] = this.x;
  4962. array[index + 1] = this.y;
  4963. array[index + 2] = this.z;
  4964. return this;
  4965. };
  4966. /**
  4967. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  4968. * @returns a new Quaternion object, computed from the Vector3 coordinates
  4969. */
  4970. Vector3.prototype.toQuaternion = function () {
  4971. return BABYLON.Quaternion.RotationYawPitchRoll(this.y, this.x, this.z);
  4972. };
  4973. /**
  4974. * Adds the given vector to the current Vector3
  4975. * @param otherVector defines the second operand
  4976. * @returns the current updated Vector3
  4977. */
  4978. Vector3.prototype.addInPlace = function (otherVector) {
  4979. return this.addInPlaceFromFloats(otherVector.x, otherVector.y, otherVector.z);
  4980. };
  4981. /**
  4982. * Adds the given coordinates to the current Vector3
  4983. * @param x defines the x coordinate of the operand
  4984. * @param y defines the y coordinate of the operand
  4985. * @param z defines the z coordinate of the operand
  4986. * @returns the current updated Vector3
  4987. */
  4988. Vector3.prototype.addInPlaceFromFloats = function (x, y, z) {
  4989. this.x += x;
  4990. this.y += y;
  4991. this.z += z;
  4992. return this;
  4993. };
  4994. /**
  4995. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  4996. * @param otherVector defines the second operand
  4997. * @returns the resulting Vector3
  4998. */
  4999. Vector3.prototype.add = function (otherVector) {
  5000. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  5001. };
  5002. /**
  5003. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  5004. * @param otherVector defines the second operand
  5005. * @param result defines the Vector3 object where to store the result
  5006. * @returns the current Vector3
  5007. */
  5008. Vector3.prototype.addToRef = function (otherVector, result) {
  5009. return result.copyFromFloats(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  5010. };
  5011. /**
  5012. * Subtract the given vector from the current Vector3
  5013. * @param otherVector defines the second operand
  5014. * @returns the current updated Vector3
  5015. */
  5016. Vector3.prototype.subtractInPlace = function (otherVector) {
  5017. this.x -= otherVector.x;
  5018. this.y -= otherVector.y;
  5019. this.z -= otherVector.z;
  5020. return this;
  5021. };
  5022. /**
  5023. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  5024. * @param otherVector defines the second operand
  5025. * @returns the resulting Vector3
  5026. */
  5027. Vector3.prototype.subtract = function (otherVector) {
  5028. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  5029. };
  5030. /**
  5031. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  5032. * @param otherVector defines the second operand
  5033. * @param result defines the Vector3 object where to store the result
  5034. * @returns the current Vector3
  5035. */
  5036. Vector3.prototype.subtractToRef = function (otherVector, result) {
  5037. return this.subtractFromFloatsToRef(otherVector.x, otherVector.y, otherVector.z, result);
  5038. };
  5039. /**
  5040. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  5041. * @param x defines the x coordinate of the operand
  5042. * @param y defines the y coordinate of the operand
  5043. * @param z defines the z coordinate of the operand
  5044. * @returns the resulting Vector3
  5045. */
  5046. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  5047. return new Vector3(this.x - x, this.y - y, this.z - z);
  5048. };
  5049. /**
  5050. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  5051. * @param x defines the x coordinate of the operand
  5052. * @param y defines the y coordinate of the operand
  5053. * @param z defines the z coordinate of the operand
  5054. * @param result defines the Vector3 object where to store the result
  5055. * @returns the current Vector3
  5056. */
  5057. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  5058. return result.copyFromFloats(this.x - x, this.y - y, this.z - z);
  5059. };
  5060. /**
  5061. * Gets a new Vector3 set with the current Vector3 negated coordinates
  5062. * @returns a new Vector3
  5063. */
  5064. Vector3.prototype.negate = function () {
  5065. return new Vector3(-this.x, -this.y, -this.z);
  5066. };
  5067. /**
  5068. * Multiplies the Vector3 coordinates by the float "scale"
  5069. * @param scale defines the multiplier factor
  5070. * @returns the current updated Vector3
  5071. */
  5072. Vector3.prototype.scaleInPlace = function (scale) {
  5073. this.x *= scale;
  5074. this.y *= scale;
  5075. this.z *= scale;
  5076. return this;
  5077. };
  5078. /**
  5079. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  5080. * @param scale defines the multiplier factor
  5081. * @returns a new Vector3
  5082. */
  5083. Vector3.prototype.scale = function (scale) {
  5084. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  5085. };
  5086. /**
  5087. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  5088. * @param scale defines the multiplier factor
  5089. * @param result defines the Vector3 object where to store the result
  5090. * @returns the current Vector3
  5091. */
  5092. Vector3.prototype.scaleToRef = function (scale, result) {
  5093. return result.copyFromFloats(this.x * scale, this.y * scale, this.z * scale);
  5094. };
  5095. /**
  5096. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  5097. * @param scale defines the scale factor
  5098. * @param result defines the Vector3 object where to store the result
  5099. * @returns the unmodified current Vector3
  5100. */
  5101. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  5102. return result.addInPlaceFromFloats(this.x * scale, this.y * scale, this.z * scale);
  5103. };
  5104. /**
  5105. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  5106. * @param otherVector defines the second operand
  5107. * @returns true if both vectors are equals
  5108. */
  5109. Vector3.prototype.equals = function (otherVector) {
  5110. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  5111. };
  5112. /**
  5113. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  5114. * @param otherVector defines the second operand
  5115. * @param epsilon defines the minimal distance to define values as equals
  5116. * @returns true if both vectors are distant less than epsilon
  5117. */
  5118. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  5119. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  5120. 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);
  5121. };
  5122. /**
  5123. * Returns true if the current Vector3 coordinates equals the given floats
  5124. * @param x defines the x coordinate of the operand
  5125. * @param y defines the y coordinate of the operand
  5126. * @param z defines the z coordinate of the operand
  5127. * @returns true if both vectors are equals
  5128. */
  5129. Vector3.prototype.equalsToFloats = function (x, y, z) {
  5130. return this.x === x && this.y === y && this.z === z;
  5131. };
  5132. /**
  5133. * Multiplies the current Vector3 coordinates by the given ones
  5134. * @param otherVector defines the second operand
  5135. * @returns the current updated Vector3
  5136. */
  5137. Vector3.prototype.multiplyInPlace = function (otherVector) {
  5138. this.x *= otherVector.x;
  5139. this.y *= otherVector.y;
  5140. this.z *= otherVector.z;
  5141. return this;
  5142. };
  5143. /**
  5144. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  5145. * @param otherVector defines the second operand
  5146. * @returns the new Vector3
  5147. */
  5148. Vector3.prototype.multiply = function (otherVector) {
  5149. return this.multiplyByFloats(otherVector.x, otherVector.y, otherVector.z);
  5150. };
  5151. /**
  5152. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  5153. * @param otherVector defines the second operand
  5154. * @param result defines the Vector3 object where to store the result
  5155. * @returns the current Vector3
  5156. */
  5157. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  5158. return result.copyFromFloats(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  5159. };
  5160. /**
  5161. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  5162. * @param x defines the x coordinate of the operand
  5163. * @param y defines the y coordinate of the operand
  5164. * @param z defines the z coordinate of the operand
  5165. * @returns the new Vector3
  5166. */
  5167. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  5168. return new Vector3(this.x * x, this.y * y, this.z * z);
  5169. };
  5170. /**
  5171. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  5172. * @param otherVector defines the second operand
  5173. * @returns the new Vector3
  5174. */
  5175. Vector3.prototype.divide = function (otherVector) {
  5176. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  5177. };
  5178. /**
  5179. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  5180. * @param otherVector defines the second operand
  5181. * @param result defines the Vector3 object where to store the result
  5182. * @returns the current Vector3
  5183. */
  5184. Vector3.prototype.divideToRef = function (otherVector, result) {
  5185. return result.copyFromFloats(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  5186. };
  5187. /**
  5188. * Divides the current Vector3 coordinates by the given ones.
  5189. * @param otherVector defines the second operand
  5190. * @returns the current updated Vector3
  5191. */
  5192. Vector3.prototype.divideInPlace = function (otherVector) {
  5193. return this.divideToRef(otherVector, this);
  5194. };
  5195. /**
  5196. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  5197. * @param other defines the second operand
  5198. * @returns the current updated Vector3
  5199. */
  5200. Vector3.prototype.minimizeInPlace = function (other) {
  5201. return this.minimizeInPlaceFromFloats(other.x, other.y, other.z);
  5202. };
  5203. /**
  5204. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  5205. * @param other defines the second operand
  5206. * @returns the current updated Vector3
  5207. */
  5208. Vector3.prototype.maximizeInPlace = function (other) {
  5209. return this.maximizeInPlaceFromFloats(other.x, other.y, other.z);
  5210. };
  5211. /**
  5212. * Updates the current Vector3 with the minimal coordinate values between its and the given coordinates
  5213. * @param x defines the x coordinate of the operand
  5214. * @param y defines the y coordinate of the operand
  5215. * @param z defines the z coordinate of the operand
  5216. * @returns the current updated Vector3
  5217. */
  5218. Vector3.prototype.minimizeInPlaceFromFloats = function (x, y, z) {
  5219. if (x < this.x) {
  5220. this.x = x;
  5221. }
  5222. if (y < this.y) {
  5223. this.y = y;
  5224. }
  5225. if (z < this.z) {
  5226. this.z = z;
  5227. }
  5228. return this;
  5229. };
  5230. /**
  5231. * Updates the current Vector3 with the maximal coordinate values between its and the given coordinates.
  5232. * @param x defines the x coordinate of the operand
  5233. * @param y defines the y coordinate of the operand
  5234. * @param z defines the z coordinate of the operand
  5235. * @returns the current updated Vector3
  5236. */
  5237. Vector3.prototype.maximizeInPlaceFromFloats = function (x, y, z) {
  5238. if (x > this.x) {
  5239. this.x = x;
  5240. }
  5241. if (y > this.y) {
  5242. this.y = y;
  5243. }
  5244. if (z > this.z) {
  5245. this.z = z;
  5246. }
  5247. return this;
  5248. };
  5249. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  5250. /**
  5251. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  5252. */
  5253. get: function () {
  5254. var absX = Math.abs(this.x);
  5255. var absY = Math.abs(this.y);
  5256. if (absX !== absY) {
  5257. return true;
  5258. }
  5259. var absZ = Math.abs(this.z);
  5260. if (absX !== absZ) {
  5261. return true;
  5262. }
  5263. if (absY !== absZ) {
  5264. return true;
  5265. }
  5266. return false;
  5267. },
  5268. enumerable: true,
  5269. configurable: true
  5270. });
  5271. /**
  5272. * Gets a new Vector3 from current Vector3 floored values
  5273. * @returns a new Vector3
  5274. */
  5275. Vector3.prototype.floor = function () {
  5276. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  5277. };
  5278. /**
  5279. * Gets a new Vector3 from current Vector3 floored values
  5280. * @returns a new Vector3
  5281. */
  5282. Vector3.prototype.fract = function () {
  5283. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  5284. };
  5285. // Properties
  5286. /**
  5287. * Gets the length of the Vector3
  5288. * @returns the length of the Vecto3
  5289. */
  5290. Vector3.prototype.length = function () {
  5291. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  5292. };
  5293. /**
  5294. * Gets the squared length of the Vector3
  5295. * @returns squared length of the Vector3
  5296. */
  5297. Vector3.prototype.lengthSquared = function () {
  5298. return (this.x * this.x + this.y * this.y + this.z * this.z);
  5299. };
  5300. /**
  5301. * Normalize the current Vector3.
  5302. * Please note that this is an in place operation.
  5303. * @returns the current updated Vector3
  5304. */
  5305. Vector3.prototype.normalize = function () {
  5306. return this.normalizeFromLength(this.length());
  5307. };
  5308. /**
  5309. * Reorders the x y z properties of the vector in place
  5310. * @param order new ordering of the properties (eg. for vector 1,2,3 with "ZYX" will produce 3,2,1)
  5311. * @returns the current updated vector
  5312. */
  5313. Vector3.prototype.reorderInPlace = function (order) {
  5314. var _this = this;
  5315. order = order.toLowerCase();
  5316. if (order === "xyz") {
  5317. return this;
  5318. }
  5319. MathTmp.Vector3[0].copyFrom(this);
  5320. ["x", "y", "z"].forEach(function (val, i) {
  5321. _this[val] = MathTmp.Vector3[0][order[i]];
  5322. });
  5323. return this;
  5324. };
  5325. /**
  5326. * Rotates the vector around 0,0,0 by a quaternion
  5327. * @param quaternion the rotation quaternion
  5328. * @param result vector to store the result
  5329. * @returns the resulting vector
  5330. */
  5331. Vector3.prototype.rotateByQuaternionToRef = function (quaternion, result) {
  5332. quaternion.toRotationMatrix(MathTmp.Matrix[0]);
  5333. Vector3.TransformCoordinatesToRef(this, MathTmp.Matrix[0], result);
  5334. return result;
  5335. };
  5336. /**
  5337. * Rotates a vector around a given point
  5338. * @param quaternion the rotation quaternion
  5339. * @param point the point to rotate around
  5340. * @param result vector to store the result
  5341. * @returns the resulting vector
  5342. */
  5343. Vector3.prototype.rotateByQuaternionAroundPointToRef = function (quaternion, point, result) {
  5344. this.subtractToRef(point, MathTmp.Vector3[0]);
  5345. MathTmp.Vector3[0].rotateByQuaternionToRef(quaternion, MathTmp.Vector3[0]);
  5346. point.addToRef(MathTmp.Vector3[0], result);
  5347. return result;
  5348. };
  5349. /**
  5350. * Normalize the current Vector3 with the given input length.
  5351. * Please note that this is an in place operation.
  5352. * @param len the length of the vector
  5353. * @returns the current updated Vector3
  5354. */
  5355. Vector3.prototype.normalizeFromLength = function (len) {
  5356. if (len === 0 || len === 1.0) {
  5357. return this;
  5358. }
  5359. return this.scaleInPlace(1.0 / len);
  5360. };
  5361. /**
  5362. * Normalize the current Vector3 to a new vector
  5363. * @returns the new Vector3
  5364. */
  5365. Vector3.prototype.normalizeToNew = function () {
  5366. var normalized = new Vector3(0, 0, 0);
  5367. this.normalizeToRef(normalized);
  5368. return normalized;
  5369. };
  5370. /**
  5371. * Normalize the current Vector3 to the reference
  5372. * @param reference define the Vector3 to update
  5373. * @returns the updated Vector3
  5374. */
  5375. Vector3.prototype.normalizeToRef = function (reference) {
  5376. var len = this.length();
  5377. if (len === 0 || len === 1.0) {
  5378. return reference.copyFromFloats(this.x, this.y, this.z);
  5379. }
  5380. return this.scaleToRef(1.0 / len, reference);
  5381. };
  5382. /**
  5383. * Creates a new Vector3 copied from the current Vector3
  5384. * @returns the new Vector3
  5385. */
  5386. Vector3.prototype.clone = function () {
  5387. return new Vector3(this.x, this.y, this.z);
  5388. };
  5389. /**
  5390. * Copies the given vector coordinates to the current Vector3 ones
  5391. * @param source defines the source Vector3
  5392. * @returns the current updated Vector3
  5393. */
  5394. Vector3.prototype.copyFrom = function (source) {
  5395. return this.copyFromFloats(source.x, source.y, source.z);
  5396. };
  5397. /**
  5398. * Copies the given floats to the current Vector3 coordinates
  5399. * @param x defines the x coordinate of the operand
  5400. * @param y defines the y coordinate of the operand
  5401. * @param z defines the z coordinate of the operand
  5402. * @returns the current updated Vector3
  5403. */
  5404. Vector3.prototype.copyFromFloats = function (x, y, z) {
  5405. this.x = x;
  5406. this.y = y;
  5407. this.z = z;
  5408. return this;
  5409. };
  5410. /**
  5411. * Copies the given floats to the current Vector3 coordinates
  5412. * @param x defines the x coordinate of the operand
  5413. * @param y defines the y coordinate of the operand
  5414. * @param z defines the z coordinate of the operand
  5415. * @returns the current updated Vector3
  5416. */
  5417. Vector3.prototype.set = function (x, y, z) {
  5418. return this.copyFromFloats(x, y, z);
  5419. };
  5420. /**
  5421. * Copies the given float to the current Vector3 coordinates
  5422. * @param v defines the x, y and z coordinates of the operand
  5423. * @returns the current updated Vector3
  5424. */
  5425. Vector3.prototype.setAll = function (v) {
  5426. this.x = this.y = this.z = v;
  5427. return this;
  5428. };
  5429. // Statics
  5430. /**
  5431. * Get the clip factor between two vectors
  5432. * @param vector0 defines the first operand
  5433. * @param vector1 defines the second operand
  5434. * @param axis defines the axis to use
  5435. * @param size defines the size along the axis
  5436. * @returns the clip factor
  5437. */
  5438. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  5439. var d0 = Vector3.Dot(vector0, axis) - size;
  5440. var d1 = Vector3.Dot(vector1, axis) - size;
  5441. var s = d0 / (d0 - d1);
  5442. return s;
  5443. };
  5444. /**
  5445. * Get angle between two vectors
  5446. * @param vector0 angle between vector0 and vector1
  5447. * @param vector1 angle between vector0 and vector1
  5448. * @param normal direction of the normal
  5449. * @return the angle between vector0 and vector1
  5450. */
  5451. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  5452. var v0 = vector0.normalizeToRef(MathTmp.Vector3[1]);
  5453. var v1 = vector1.normalizeToRef(MathTmp.Vector3[2]);
  5454. var dot = Vector3.Dot(v0, v1);
  5455. var n = MathTmp.Vector3[3];
  5456. Vector3.CrossToRef(v0, v1, n);
  5457. if (Vector3.Dot(n, normal) > 0) {
  5458. return Math.acos(dot);
  5459. }
  5460. return -Math.acos(dot);
  5461. };
  5462. /**
  5463. * Returns a new Vector3 set from the index "offset" of the given array
  5464. * @param array defines the source array
  5465. * @param offset defines the offset in the source array
  5466. * @returns the new Vector3
  5467. */
  5468. Vector3.FromArray = function (array, offset) {
  5469. if (offset === void 0) { offset = 0; }
  5470. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  5471. };
  5472. /**
  5473. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  5474. * This function is deprecated. Use FromArray instead
  5475. * @param array defines the source array
  5476. * @param offset defines the offset in the source array
  5477. * @returns the new Vector3
  5478. */
  5479. Vector3.FromFloatArray = function (array, offset) {
  5480. return Vector3.FromArray(array, offset);
  5481. };
  5482. /**
  5483. * Sets the given vector "result" with the element values from the index "offset" of the given array
  5484. * @param array defines the source array
  5485. * @param offset defines the offset in the source array
  5486. * @param result defines the Vector3 where to store the result
  5487. */
  5488. Vector3.FromArrayToRef = function (array, offset, result) {
  5489. result.x = array[offset];
  5490. result.y = array[offset + 1];
  5491. result.z = array[offset + 2];
  5492. };
  5493. /**
  5494. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  5495. * This function is deprecated. Use FromArrayToRef instead.
  5496. * @param array defines the source array
  5497. * @param offset defines the offset in the source array
  5498. * @param result defines the Vector3 where to store the result
  5499. */
  5500. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  5501. return Vector3.FromArrayToRef(array, offset, result);
  5502. };
  5503. /**
  5504. * Sets the given vector "result" with the given floats.
  5505. * @param x defines the x coordinate of the source
  5506. * @param y defines the y coordinate of the source
  5507. * @param z defines the z coordinate of the source
  5508. * @param result defines the Vector3 where to store the result
  5509. */
  5510. Vector3.FromFloatsToRef = function (x, y, z, result) {
  5511. result.copyFromFloats(x, y, z);
  5512. };
  5513. /**
  5514. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  5515. * @returns a new empty Vector3
  5516. */
  5517. Vector3.Zero = function () {
  5518. return new Vector3(0.0, 0.0, 0.0);
  5519. };
  5520. /**
  5521. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  5522. * @returns a new unit Vector3
  5523. */
  5524. Vector3.One = function () {
  5525. return new Vector3(1.0, 1.0, 1.0);
  5526. };
  5527. /**
  5528. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  5529. * @returns a new up Vector3
  5530. */
  5531. Vector3.Up = function () {
  5532. return new Vector3(0.0, 1.0, 0.0);
  5533. };
  5534. /**
  5535. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  5536. * @returns a new down Vector3
  5537. */
  5538. Vector3.Down = function () {
  5539. return new Vector3(0.0, -1.0, 0.0);
  5540. };
  5541. /**
  5542. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  5543. * @returns a new forward Vector3
  5544. */
  5545. Vector3.Forward = function () {
  5546. return new Vector3(0.0, 0.0, 1.0);
  5547. };
  5548. /**
  5549. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  5550. * @returns a new forward Vector3
  5551. */
  5552. Vector3.Backward = function () {
  5553. return new Vector3(0.0, 0.0, -1.0);
  5554. };
  5555. /**
  5556. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  5557. * @returns a new right Vector3
  5558. */
  5559. Vector3.Right = function () {
  5560. return new Vector3(1.0, 0.0, 0.0);
  5561. };
  5562. /**
  5563. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  5564. * @returns a new left Vector3
  5565. */
  5566. Vector3.Left = function () {
  5567. return new Vector3(-1.0, 0.0, 0.0);
  5568. };
  5569. /**
  5570. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  5571. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  5572. * @param vector defines the Vector3 to transform
  5573. * @param transformation defines the transformation matrix
  5574. * @returns the transformed Vector3
  5575. */
  5576. Vector3.TransformCoordinates = function (vector, transformation) {
  5577. var result = Vector3.Zero();
  5578. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  5579. return result;
  5580. };
  5581. /**
  5582. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  5583. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  5584. * @param vector defines the Vector3 to transform
  5585. * @param transformation defines the transformation matrix
  5586. * @param result defines the Vector3 where to store the result
  5587. */
  5588. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  5589. return Vector3.TransformCoordinatesFromFloatsToRef(vector.x, vector.y, vector.z, transformation, result);
  5590. };
  5591. /**
  5592. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  5593. * This method computes tranformed coordinates only, not transformed direction vectors
  5594. * @param x define the x coordinate of the source vector
  5595. * @param y define the y coordinate of the source vector
  5596. * @param z define the z coordinate of the source vector
  5597. * @param transformation defines the transformation matrix
  5598. * @param result defines the Vector3 where to store the result
  5599. */
  5600. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  5601. var m = transformation.m;
  5602. var rx = x * m[0] + y * m[4] + z * m[8] + m[12];
  5603. var ry = x * m[1] + y * m[5] + z * m[9] + m[13];
  5604. var rz = x * m[2] + y * m[6] + z * m[10] + m[14];
  5605. var rw = 1 / (x * m[3] + y * m[7] + z * m[11] + m[15]);
  5606. result.x = rx * rw;
  5607. result.y = ry * rw;
  5608. result.z = rz * rw;
  5609. };
  5610. /**
  5611. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  5612. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  5613. * @param vector defines the Vector3 to transform
  5614. * @param transformation defines the transformation matrix
  5615. * @returns the new Vector3
  5616. */
  5617. Vector3.TransformNormal = function (vector, transformation) {
  5618. var result = Vector3.Zero();
  5619. Vector3.TransformNormalToRef(vector, transformation, result);
  5620. return result;
  5621. };
  5622. /**
  5623. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  5624. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  5625. * @param vector defines the Vector3 to transform
  5626. * @param transformation defines the transformation matrix
  5627. * @param result defines the Vector3 where to store the result
  5628. */
  5629. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  5630. this.TransformNormalFromFloatsToRef(vector.x, vector.y, vector.z, transformation, result);
  5631. };
  5632. /**
  5633. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  5634. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  5635. * @param x define the x coordinate of the source vector
  5636. * @param y define the y coordinate of the source vector
  5637. * @param z define the z coordinate of the source vector
  5638. * @param transformation defines the transformation matrix
  5639. * @param result defines the Vector3 where to store the result
  5640. */
  5641. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  5642. var m = transformation.m;
  5643. result.x = x * m[0] + y * m[4] + z * m[8];
  5644. result.y = x * m[1] + y * m[5] + z * m[9];
  5645. result.z = x * m[2] + y * m[6] + z * m[10];
  5646. };
  5647. /**
  5648. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  5649. * @param value1 defines the first control point
  5650. * @param value2 defines the second control point
  5651. * @param value3 defines the third control point
  5652. * @param value4 defines the fourth control point
  5653. * @param amount defines the amount on the spline to use
  5654. * @returns the new Vector3
  5655. */
  5656. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  5657. var squared = amount * amount;
  5658. var cubed = amount * squared;
  5659. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  5660. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  5661. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  5662. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  5663. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  5664. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  5665. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  5666. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  5667. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  5668. return new Vector3(x, y, z);
  5669. };
  5670. /**
  5671. * 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"
  5672. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  5673. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  5674. * @param value defines the current value
  5675. * @param min defines the lower range value
  5676. * @param max defines the upper range value
  5677. * @returns the new Vector3
  5678. */
  5679. Vector3.Clamp = function (value, min, max) {
  5680. var v = new Vector3();
  5681. Vector3.ClampToRef(value, min, max, v);
  5682. return v;
  5683. };
  5684. /**
  5685. * Sets the given vector "result" with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  5686. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  5687. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  5688. * @param value defines the current value
  5689. * @param min defines the lower range value
  5690. * @param max defines the upper range value
  5691. * @param result defines the Vector3 where to store the result
  5692. */
  5693. Vector3.ClampToRef = function (value, min, max, result) {
  5694. var x = value.x;
  5695. x = (x > max.x) ? max.x : x;
  5696. x = (x < min.x) ? min.x : x;
  5697. var y = value.y;
  5698. y = (y > max.y) ? max.y : y;
  5699. y = (y < min.y) ? min.y : y;
  5700. var z = value.z;
  5701. z = (z > max.z) ? max.z : z;
  5702. z = (z < min.z) ? min.z : z;
  5703. result.copyFromFloats(x, y, z);
  5704. };
  5705. /**
  5706. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  5707. * @param value1 defines the first control point
  5708. * @param tangent1 defines the first tangent vector
  5709. * @param value2 defines the second control point
  5710. * @param tangent2 defines the second tangent vector
  5711. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  5712. * @returns the new Vector3
  5713. */
  5714. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5715. var squared = amount * amount;
  5716. var cubed = amount * squared;
  5717. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5718. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5719. var part3 = (cubed - (2.0 * squared)) + amount;
  5720. var part4 = cubed - squared;
  5721. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5722. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5723. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5724. return new Vector3(x, y, z);
  5725. };
  5726. /**
  5727. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  5728. * @param start defines the start value
  5729. * @param end defines the end value
  5730. * @param amount max defines amount between both (between 0 and 1)
  5731. * @returns the new Vector3
  5732. */
  5733. Vector3.Lerp = function (start, end, amount) {
  5734. var result = new Vector3(0, 0, 0);
  5735. Vector3.LerpToRef(start, end, amount, result);
  5736. return result;
  5737. };
  5738. /**
  5739. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  5740. * @param start defines the start value
  5741. * @param end defines the end value
  5742. * @param amount max defines amount between both (between 0 and 1)
  5743. * @param result defines the Vector3 where to store the result
  5744. */
  5745. Vector3.LerpToRef = function (start, end, amount, result) {
  5746. result.x = start.x + ((end.x - start.x) * amount);
  5747. result.y = start.y + ((end.y - start.y) * amount);
  5748. result.z = start.z + ((end.z - start.z) * amount);
  5749. };
  5750. /**
  5751. * Returns the dot product (float) between the vectors "left" and "right"
  5752. * @param left defines the left operand
  5753. * @param right defines the right operand
  5754. * @returns the dot product
  5755. */
  5756. Vector3.Dot = function (left, right) {
  5757. return (left.x * right.x + left.y * right.y + left.z * right.z);
  5758. };
  5759. /**
  5760. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  5761. * The cross product is then orthogonal to both "left" and "right"
  5762. * @param left defines the left operand
  5763. * @param right defines the right operand
  5764. * @returns the cross product
  5765. */
  5766. Vector3.Cross = function (left, right) {
  5767. var result = Vector3.Zero();
  5768. Vector3.CrossToRef(left, right, result);
  5769. return result;
  5770. };
  5771. /**
  5772. * Sets the given vector "result" with the cross product of "left" and "right"
  5773. * The cross product is then orthogonal to both "left" and "right"
  5774. * @param left defines the left operand
  5775. * @param right defines the right operand
  5776. * @param result defines the Vector3 where to store the result
  5777. */
  5778. Vector3.CrossToRef = function (left, right, result) {
  5779. var x = left.y * right.z - left.z * right.y;
  5780. var y = left.z * right.x - left.x * right.z;
  5781. var z = left.x * right.y - left.y * right.x;
  5782. result.copyFromFloats(x, y, z);
  5783. };
  5784. /**
  5785. * Returns a new Vector3 as the normalization of the given vector
  5786. * @param vector defines the Vector3 to normalize
  5787. * @returns the new Vector3
  5788. */
  5789. Vector3.Normalize = function (vector) {
  5790. var result = Vector3.Zero();
  5791. Vector3.NormalizeToRef(vector, result);
  5792. return result;
  5793. };
  5794. /**
  5795. * Sets the given vector "result" with the normalization of the given first vector
  5796. * @param vector defines the Vector3 to normalize
  5797. * @param result defines the Vector3 where to store the result
  5798. */
  5799. Vector3.NormalizeToRef = function (vector, result) {
  5800. vector.normalizeToRef(result);
  5801. };
  5802. /**
  5803. * Project a Vector3 onto screen space
  5804. * @param vector defines the Vector3 to project
  5805. * @param world defines the world matrix to use
  5806. * @param transform defines the transform (view x projection) matrix to use
  5807. * @param viewport defines the screen viewport to use
  5808. * @returns the new Vector3
  5809. */
  5810. Vector3.Project = function (vector, world, transform, viewport) {
  5811. var cw = viewport.width;
  5812. var ch = viewport.height;
  5813. var cx = viewport.x;
  5814. var cy = viewport.y;
  5815. var viewportMatrix = MathTmp.Matrix[1];
  5816. 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);
  5817. var matrix = MathTmp.Matrix[0];
  5818. world.multiplyToRef(transform, matrix);
  5819. matrix.multiplyToRef(viewportMatrix, matrix);
  5820. return Vector3.TransformCoordinates(vector, matrix);
  5821. };
  5822. /** @hidden */
  5823. Vector3.UnprojectFromInvertedMatrixToRef = function (source, matrix, result) {
  5824. Vector3.TransformCoordinatesToRef(source, matrix, result);
  5825. var m = matrix.m;
  5826. var num = source.x * m[3] + source.y * m[7] + source.z * m[11] + m[15];
  5827. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  5828. result.scaleInPlace(1.0 / num);
  5829. }
  5830. };
  5831. /**
  5832. * Unproject from screen space to object space
  5833. * @param source defines the screen space Vector3 to use
  5834. * @param viewportWidth defines the current width of the viewport
  5835. * @param viewportHeight defines the current height of the viewport
  5836. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5837. * @param transform defines the transform (view x projection) matrix to use
  5838. * @returns the new Vector3
  5839. */
  5840. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  5841. var matrix = MathTmp.Matrix[0];
  5842. world.multiplyToRef(transform, matrix);
  5843. matrix.invert();
  5844. source.x = source.x / viewportWidth * 2 - 1;
  5845. source.y = -(source.y / viewportHeight * 2 - 1);
  5846. var vector = new Vector3();
  5847. Vector3.UnprojectFromInvertedMatrixToRef(source, matrix, vector);
  5848. return vector;
  5849. };
  5850. /**
  5851. * Unproject from screen space to object space
  5852. * @param source defines the screen space Vector3 to use
  5853. * @param viewportWidth defines the current width of the viewport
  5854. * @param viewportHeight defines the current height of the viewport
  5855. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5856. * @param view defines the view matrix to use
  5857. * @param projection defines the projection matrix to use
  5858. * @returns the new Vector3
  5859. */
  5860. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  5861. var result = Vector3.Zero();
  5862. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  5863. return result;
  5864. };
  5865. /**
  5866. * Unproject from screen space to object space
  5867. * @param source defines the screen space Vector3 to use
  5868. * @param viewportWidth defines the current width of the viewport
  5869. * @param viewportHeight defines the current height of the viewport
  5870. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5871. * @param view defines the view matrix to use
  5872. * @param projection defines the projection matrix to use
  5873. * @param result defines the Vector3 where to store the result
  5874. */
  5875. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  5876. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  5877. };
  5878. /**
  5879. * Unproject from screen space to object space
  5880. * @param sourceX defines the screen space x coordinate to use
  5881. * @param sourceY defines the screen space y coordinate to use
  5882. * @param sourceZ defines the screen space z coordinate to use
  5883. * @param viewportWidth defines the current width of the viewport
  5884. * @param viewportHeight defines the current height of the viewport
  5885. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5886. * @param view defines the view matrix to use
  5887. * @param projection defines the projection matrix to use
  5888. * @param result defines the Vector3 where to store the result
  5889. */
  5890. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  5891. var matrix = MathTmp.Matrix[0];
  5892. world.multiplyToRef(view, matrix);
  5893. matrix.multiplyToRef(projection, matrix);
  5894. matrix.invert();
  5895. var screenSource = MathTmp.Vector3[0];
  5896. screenSource.x = sourceX / viewportWidth * 2 - 1;
  5897. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  5898. screenSource.z = 2 * sourceZ - 1.0;
  5899. Vector3.UnprojectFromInvertedMatrixToRef(screenSource, matrix, result);
  5900. };
  5901. /**
  5902. * Unproject a ray from screen space to object space
  5903. * @param sourceX defines the screen space x coordinate to use
  5904. * @param sourceY defines the screen space y coordinate to use
  5905. * @param viewportWidth defines the current width of the viewport
  5906. * @param viewportHeight defines the current height of the viewport
  5907. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  5908. * @param view defines the view matrix to use
  5909. * @param projection defines the projection matrix to use
  5910. * @param ray defines the Ray where to store the result
  5911. */
  5912. Vector3.UnprojectRayToRef = function (sourceX, sourceY, viewportWidth, viewportHeight, world, view, projection, ray) {
  5913. var matrix = MathTmp.Matrix[0];
  5914. world.multiplyToRef(view, matrix);
  5915. matrix.multiplyToRef(projection, matrix);
  5916. matrix.invert();
  5917. var nearScreenSource = MathTmp.Vector3[0];
  5918. nearScreenSource.x = sourceX / viewportWidth * 2 - 1;
  5919. nearScreenSource.y = -(sourceY / viewportHeight * 2 - 1);
  5920. nearScreenSource.z = -1.0;
  5921. var farScreenSource = MathTmp.Vector3[1].copyFromFloats(nearScreenSource.x, nearScreenSource.y, 1.0);
  5922. var nearVec3 = MathTmp.Vector3[2];
  5923. var farVec3 = MathTmp.Vector3[3];
  5924. Vector3.UnprojectFromInvertedMatrixToRef(nearScreenSource, matrix, nearVec3);
  5925. Vector3.UnprojectFromInvertedMatrixToRef(farScreenSource, matrix, farVec3);
  5926. ray.origin.copyFrom(nearVec3);
  5927. farVec3.subtractToRef(nearVec3, ray.direction);
  5928. ray.direction.normalize();
  5929. };
  5930. /**
  5931. * Gets the minimal coordinate values between two Vector3
  5932. * @param left defines the first operand
  5933. * @param right defines the second operand
  5934. * @returns the new Vector3
  5935. */
  5936. Vector3.Minimize = function (left, right) {
  5937. var min = left.clone();
  5938. min.minimizeInPlace(right);
  5939. return min;
  5940. };
  5941. /**
  5942. * Gets the maximal coordinate values between two Vector3
  5943. * @param left defines the first operand
  5944. * @param right defines the second operand
  5945. * @returns the new Vector3
  5946. */
  5947. Vector3.Maximize = function (left, right) {
  5948. var max = left.clone();
  5949. max.maximizeInPlace(right);
  5950. return max;
  5951. };
  5952. /**
  5953. * Returns the distance between the vectors "value1" and "value2"
  5954. * @param value1 defines the first operand
  5955. * @param value2 defines the second operand
  5956. * @returns the distance
  5957. */
  5958. Vector3.Distance = function (value1, value2) {
  5959. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  5960. };
  5961. /**
  5962. * Returns the squared distance between the vectors "value1" and "value2"
  5963. * @param value1 defines the first operand
  5964. * @param value2 defines the second operand
  5965. * @returns the squared distance
  5966. */
  5967. Vector3.DistanceSquared = function (value1, value2) {
  5968. var x = value1.x - value2.x;
  5969. var y = value1.y - value2.y;
  5970. var z = value1.z - value2.z;
  5971. return (x * x) + (y * y) + (z * z);
  5972. };
  5973. /**
  5974. * Returns a new Vector3 located at the center between "value1" and "value2"
  5975. * @param value1 defines the first operand
  5976. * @param value2 defines the second operand
  5977. * @returns the new Vector3
  5978. */
  5979. Vector3.Center = function (value1, value2) {
  5980. var center = value1.add(value2);
  5981. center.scaleInPlace(0.5);
  5982. return center;
  5983. };
  5984. /**
  5985. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  5986. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  5987. * to something in order to rotate it from its local system to the given target system
  5988. * Note: axis1, axis2 and axis3 are normalized during this operation
  5989. * @param axis1 defines the first axis
  5990. * @param axis2 defines the second axis
  5991. * @param axis3 defines the third axis
  5992. * @returns a new Vector3
  5993. */
  5994. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  5995. var rotation = Vector3.Zero();
  5996. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  5997. return rotation;
  5998. };
  5999. /**
  6000. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  6001. * @param axis1 defines the first axis
  6002. * @param axis2 defines the second axis
  6003. * @param axis3 defines the third axis
  6004. * @param ref defines the Vector3 where to store the result
  6005. */
  6006. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  6007. var quat = MathTmp.Quaternion[0];
  6008. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  6009. quat.toEulerAnglesToRef(ref);
  6010. };
  6011. return Vector3;
  6012. }());
  6013. BABYLON.Vector3 = Vector3;
  6014. /**
  6015. * Vector4 class created for EulerAngle class conversion to Quaternion
  6016. */
  6017. var Vector4 = /** @class */ (function () {
  6018. /**
  6019. * Creates a Vector4 object from the given floats.
  6020. * @param x x value of the vector
  6021. * @param y y value of the vector
  6022. * @param z z value of the vector
  6023. * @param w w value of the vector
  6024. */
  6025. function Vector4(
  6026. /** x value of the vector */
  6027. x,
  6028. /** y value of the vector */
  6029. y,
  6030. /** z value of the vector */
  6031. z,
  6032. /** w value of the vector */
  6033. w) {
  6034. this.x = x;
  6035. this.y = y;
  6036. this.z = z;
  6037. this.w = w;
  6038. }
  6039. /**
  6040. * Returns the string with the Vector4 coordinates.
  6041. * @returns a string containing all the vector values
  6042. */
  6043. Vector4.prototype.toString = function () {
  6044. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  6045. };
  6046. /**
  6047. * Returns the string "Vector4".
  6048. * @returns "Vector4"
  6049. */
  6050. Vector4.prototype.getClassName = function () {
  6051. return "Vector4";
  6052. };
  6053. /**
  6054. * Returns the Vector4 hash code.
  6055. * @returns a unique hash code
  6056. */
  6057. Vector4.prototype.getHashCode = function () {
  6058. var hash = this.x || 0;
  6059. hash = (hash * 397) ^ (this.y || 0);
  6060. hash = (hash * 397) ^ (this.z || 0);
  6061. hash = (hash * 397) ^ (this.w || 0);
  6062. return hash;
  6063. };
  6064. // Operators
  6065. /**
  6066. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  6067. * @returns the resulting array
  6068. */
  6069. Vector4.prototype.asArray = function () {
  6070. var result = new Array();
  6071. this.toArray(result, 0);
  6072. return result;
  6073. };
  6074. /**
  6075. * Populates the given array from the given index with the Vector4 coordinates.
  6076. * @param array array to populate
  6077. * @param index index of the array to start at (default: 0)
  6078. * @returns the Vector4.
  6079. */
  6080. Vector4.prototype.toArray = function (array, index) {
  6081. if (index === undefined) {
  6082. index = 0;
  6083. }
  6084. array[index] = this.x;
  6085. array[index + 1] = this.y;
  6086. array[index + 2] = this.z;
  6087. array[index + 3] = this.w;
  6088. return this;
  6089. };
  6090. /**
  6091. * Adds the given vector to the current Vector4.
  6092. * @param otherVector the vector to add
  6093. * @returns the updated Vector4.
  6094. */
  6095. Vector4.prototype.addInPlace = function (otherVector) {
  6096. this.x += otherVector.x;
  6097. this.y += otherVector.y;
  6098. this.z += otherVector.z;
  6099. this.w += otherVector.w;
  6100. return this;
  6101. };
  6102. /**
  6103. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  6104. * @param otherVector the vector to add
  6105. * @returns the resulting vector
  6106. */
  6107. Vector4.prototype.add = function (otherVector) {
  6108. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  6109. };
  6110. /**
  6111. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  6112. * @param otherVector the vector to add
  6113. * @param result the vector to store the result
  6114. * @returns the current Vector4.
  6115. */
  6116. Vector4.prototype.addToRef = function (otherVector, result) {
  6117. result.x = this.x + otherVector.x;
  6118. result.y = this.y + otherVector.y;
  6119. result.z = this.z + otherVector.z;
  6120. result.w = this.w + otherVector.w;
  6121. return this;
  6122. };
  6123. /**
  6124. * Subtract in place the given vector from the current Vector4.
  6125. * @param otherVector the vector to subtract
  6126. * @returns the updated Vector4.
  6127. */
  6128. Vector4.prototype.subtractInPlace = function (otherVector) {
  6129. this.x -= otherVector.x;
  6130. this.y -= otherVector.y;
  6131. this.z -= otherVector.z;
  6132. this.w -= otherVector.w;
  6133. return this;
  6134. };
  6135. /**
  6136. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  6137. * @param otherVector the vector to add
  6138. * @returns the new vector with the result
  6139. */
  6140. Vector4.prototype.subtract = function (otherVector) {
  6141. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  6142. };
  6143. /**
  6144. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  6145. * @param otherVector the vector to subtract
  6146. * @param result the vector to store the result
  6147. * @returns the current Vector4.
  6148. */
  6149. Vector4.prototype.subtractToRef = function (otherVector, result) {
  6150. result.x = this.x - otherVector.x;
  6151. result.y = this.y - otherVector.y;
  6152. result.z = this.z - otherVector.z;
  6153. result.w = this.w - otherVector.w;
  6154. return this;
  6155. };
  6156. /**
  6157. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  6158. */
  6159. /**
  6160. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  6161. * @param x value to subtract
  6162. * @param y value to subtract
  6163. * @param z value to subtract
  6164. * @param w value to subtract
  6165. * @returns new vector containing the result
  6166. */
  6167. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  6168. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  6169. };
  6170. /**
  6171. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  6172. * @param x value to subtract
  6173. * @param y value to subtract
  6174. * @param z value to subtract
  6175. * @param w value to subtract
  6176. * @param result the vector to store the result in
  6177. * @returns the current Vector4.
  6178. */
  6179. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  6180. result.x = this.x - x;
  6181. result.y = this.y - y;
  6182. result.z = this.z - z;
  6183. result.w = this.w - w;
  6184. return this;
  6185. };
  6186. /**
  6187. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  6188. * @returns a new vector with the negated values
  6189. */
  6190. Vector4.prototype.negate = function () {
  6191. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  6192. };
  6193. /**
  6194. * Multiplies the current Vector4 coordinates by scale (float).
  6195. * @param scale the number to scale with
  6196. * @returns the updated Vector4.
  6197. */
  6198. Vector4.prototype.scaleInPlace = function (scale) {
  6199. this.x *= scale;
  6200. this.y *= scale;
  6201. this.z *= scale;
  6202. this.w *= scale;
  6203. return this;
  6204. };
  6205. /**
  6206. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  6207. * @param scale the number to scale with
  6208. * @returns a new vector with the result
  6209. */
  6210. Vector4.prototype.scale = function (scale) {
  6211. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  6212. };
  6213. /**
  6214. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  6215. * @param scale the number to scale with
  6216. * @param result a vector to store the result in
  6217. * @returns the current Vector4.
  6218. */
  6219. Vector4.prototype.scaleToRef = function (scale, result) {
  6220. result.x = this.x * scale;
  6221. result.y = this.y * scale;
  6222. result.z = this.z * scale;
  6223. result.w = this.w * scale;
  6224. return this;
  6225. };
  6226. /**
  6227. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  6228. * @param scale defines the scale factor
  6229. * @param result defines the Vector4 object where to store the result
  6230. * @returns the unmodified current Vector4
  6231. */
  6232. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  6233. result.x += this.x * scale;
  6234. result.y += this.y * scale;
  6235. result.z += this.z * scale;
  6236. result.w += this.w * scale;
  6237. return this;
  6238. };
  6239. /**
  6240. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  6241. * @param otherVector the vector to compare against
  6242. * @returns true if they are equal
  6243. */
  6244. Vector4.prototype.equals = function (otherVector) {
  6245. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  6246. };
  6247. /**
  6248. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  6249. * @param otherVector vector to compare against
  6250. * @param epsilon (Default: very small number)
  6251. * @returns true if they are equal
  6252. */
  6253. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  6254. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  6255. return otherVector
  6256. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  6257. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  6258. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  6259. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  6260. };
  6261. /**
  6262. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  6263. * @param x x value to compare against
  6264. * @param y y value to compare against
  6265. * @param z z value to compare against
  6266. * @param w w value to compare against
  6267. * @returns true if equal
  6268. */
  6269. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  6270. return this.x === x && this.y === y && this.z === z && this.w === w;
  6271. };
  6272. /**
  6273. * Multiplies in place the current Vector4 by the given one.
  6274. * @param otherVector vector to multiple with
  6275. * @returns the updated Vector4.
  6276. */
  6277. Vector4.prototype.multiplyInPlace = function (otherVector) {
  6278. this.x *= otherVector.x;
  6279. this.y *= otherVector.y;
  6280. this.z *= otherVector.z;
  6281. this.w *= otherVector.w;
  6282. return this;
  6283. };
  6284. /**
  6285. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  6286. * @param otherVector vector to multiple with
  6287. * @returns resulting new vector
  6288. */
  6289. Vector4.prototype.multiply = function (otherVector) {
  6290. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  6291. };
  6292. /**
  6293. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  6294. * @param otherVector vector to multiple with
  6295. * @param result vector to store the result
  6296. * @returns the current Vector4.
  6297. */
  6298. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  6299. result.x = this.x * otherVector.x;
  6300. result.y = this.y * otherVector.y;
  6301. result.z = this.z * otherVector.z;
  6302. result.w = this.w * otherVector.w;
  6303. return this;
  6304. };
  6305. /**
  6306. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  6307. * @param x x value multiply with
  6308. * @param y y value multiply with
  6309. * @param z z value multiply with
  6310. * @param w w value multiply with
  6311. * @returns resulting new vector
  6312. */
  6313. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  6314. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  6315. };
  6316. /**
  6317. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  6318. * @param otherVector vector to devide with
  6319. * @returns resulting new vector
  6320. */
  6321. Vector4.prototype.divide = function (otherVector) {
  6322. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  6323. };
  6324. /**
  6325. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  6326. * @param otherVector vector to devide with
  6327. * @param result vector to store the result
  6328. * @returns the current Vector4.
  6329. */
  6330. Vector4.prototype.divideToRef = function (otherVector, result) {
  6331. result.x = this.x / otherVector.x;
  6332. result.y = this.y / otherVector.y;
  6333. result.z = this.z / otherVector.z;
  6334. result.w = this.w / otherVector.w;
  6335. return this;
  6336. };
  6337. /**
  6338. * Divides the current Vector3 coordinates by the given ones.
  6339. * @param otherVector vector to devide with
  6340. * @returns the updated Vector3.
  6341. */
  6342. Vector4.prototype.divideInPlace = function (otherVector) {
  6343. return this.divideToRef(otherVector, this);
  6344. };
  6345. /**
  6346. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  6347. * @param other defines the second operand
  6348. * @returns the current updated Vector4
  6349. */
  6350. Vector4.prototype.minimizeInPlace = function (other) {
  6351. if (other.x < this.x) {
  6352. this.x = other.x;
  6353. }
  6354. if (other.y < this.y) {
  6355. this.y = other.y;
  6356. }
  6357. if (other.z < this.z) {
  6358. this.z = other.z;
  6359. }
  6360. if (other.w < this.w) {
  6361. this.w = other.w;
  6362. }
  6363. return this;
  6364. };
  6365. /**
  6366. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  6367. * @param other defines the second operand
  6368. * @returns the current updated Vector4
  6369. */
  6370. Vector4.prototype.maximizeInPlace = function (other) {
  6371. if (other.x > this.x) {
  6372. this.x = other.x;
  6373. }
  6374. if (other.y > this.y) {
  6375. this.y = other.y;
  6376. }
  6377. if (other.z > this.z) {
  6378. this.z = other.z;
  6379. }
  6380. if (other.w > this.w) {
  6381. this.w = other.w;
  6382. }
  6383. return this;
  6384. };
  6385. /**
  6386. * Gets a new Vector4 from current Vector4 floored values
  6387. * @returns a new Vector4
  6388. */
  6389. Vector4.prototype.floor = function () {
  6390. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  6391. };
  6392. /**
  6393. * Gets a new Vector4 from current Vector3 floored values
  6394. * @returns a new Vector4
  6395. */
  6396. Vector4.prototype.fract = function () {
  6397. 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));
  6398. };
  6399. // Properties
  6400. /**
  6401. * Returns the Vector4 length (float).
  6402. * @returns the length
  6403. */
  6404. Vector4.prototype.length = function () {
  6405. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  6406. };
  6407. /**
  6408. * Returns the Vector4 squared length (float).
  6409. * @returns the length squared
  6410. */
  6411. Vector4.prototype.lengthSquared = function () {
  6412. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  6413. };
  6414. // Methods
  6415. /**
  6416. * Normalizes in place the Vector4.
  6417. * @returns the updated Vector4.
  6418. */
  6419. Vector4.prototype.normalize = function () {
  6420. var len = this.length();
  6421. if (len === 0) {
  6422. return this;
  6423. }
  6424. return this.scaleInPlace(1.0 / len);
  6425. };
  6426. /**
  6427. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  6428. * @returns this converted to a new vector3
  6429. */
  6430. Vector4.prototype.toVector3 = function () {
  6431. return new Vector3(this.x, this.y, this.z);
  6432. };
  6433. /**
  6434. * Returns a new Vector4 copied from the current one.
  6435. * @returns the new cloned vector
  6436. */
  6437. Vector4.prototype.clone = function () {
  6438. return new Vector4(this.x, this.y, this.z, this.w);
  6439. };
  6440. /**
  6441. * Updates the current Vector4 with the given one coordinates.
  6442. * @param source the source vector to copy from
  6443. * @returns the updated Vector4.
  6444. */
  6445. Vector4.prototype.copyFrom = function (source) {
  6446. this.x = source.x;
  6447. this.y = source.y;
  6448. this.z = source.z;
  6449. this.w = source.w;
  6450. return this;
  6451. };
  6452. /**
  6453. * Updates the current Vector4 coordinates with the given floats.
  6454. * @param x float to copy from
  6455. * @param y float to copy from
  6456. * @param z float to copy from
  6457. * @param w float to copy from
  6458. * @returns the updated Vector4.
  6459. */
  6460. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  6461. this.x = x;
  6462. this.y = y;
  6463. this.z = z;
  6464. this.w = w;
  6465. return this;
  6466. };
  6467. /**
  6468. * Updates the current Vector4 coordinates with the given floats.
  6469. * @param x float to set from
  6470. * @param y float to set from
  6471. * @param z float to set from
  6472. * @param w float to set from
  6473. * @returns the updated Vector4.
  6474. */
  6475. Vector4.prototype.set = function (x, y, z, w) {
  6476. return this.copyFromFloats(x, y, z, w);
  6477. };
  6478. /**
  6479. * Copies the given float to the current Vector3 coordinates
  6480. * @param v defines the x, y, z and w coordinates of the operand
  6481. * @returns the current updated Vector3
  6482. */
  6483. Vector4.prototype.setAll = function (v) {
  6484. this.x = this.y = this.z = this.w = v;
  6485. return this;
  6486. };
  6487. // Statics
  6488. /**
  6489. * Returns a new Vector4 set from the starting index of the given array.
  6490. * @param array the array to pull values from
  6491. * @param offset the offset into the array to start at
  6492. * @returns the new vector
  6493. */
  6494. Vector4.FromArray = function (array, offset) {
  6495. if (!offset) {
  6496. offset = 0;
  6497. }
  6498. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  6499. };
  6500. /**
  6501. * Updates the given vector "result" from the starting index of the given array.
  6502. * @param array the array to pull values from
  6503. * @param offset the offset into the array to start at
  6504. * @param result the vector to store the result in
  6505. */
  6506. Vector4.FromArrayToRef = function (array, offset, result) {
  6507. result.x = array[offset];
  6508. result.y = array[offset + 1];
  6509. result.z = array[offset + 2];
  6510. result.w = array[offset + 3];
  6511. };
  6512. /**
  6513. * Updates the given vector "result" from the starting index of the given Float32Array.
  6514. * @param array the array to pull values from
  6515. * @param offset the offset into the array to start at
  6516. * @param result the vector to store the result in
  6517. */
  6518. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  6519. Vector4.FromArrayToRef(array, offset, result);
  6520. };
  6521. /**
  6522. * Updates the given vector "result" coordinates from the given floats.
  6523. * @param x float to set from
  6524. * @param y float to set from
  6525. * @param z float to set from
  6526. * @param w float to set from
  6527. * @param result the vector to the floats in
  6528. */
  6529. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  6530. result.x = x;
  6531. result.y = y;
  6532. result.z = z;
  6533. result.w = w;
  6534. };
  6535. /**
  6536. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  6537. * @returns the new vector
  6538. */
  6539. Vector4.Zero = function () {
  6540. return new Vector4(0.0, 0.0, 0.0, 0.0);
  6541. };
  6542. /**
  6543. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  6544. * @returns the new vector
  6545. */
  6546. Vector4.One = function () {
  6547. return new Vector4(1.0, 1.0, 1.0, 1.0);
  6548. };
  6549. /**
  6550. * Returns a new normalized Vector4 from the given one.
  6551. * @param vector the vector to normalize
  6552. * @returns the vector
  6553. */
  6554. Vector4.Normalize = function (vector) {
  6555. var result = Vector4.Zero();
  6556. Vector4.NormalizeToRef(vector, result);
  6557. return result;
  6558. };
  6559. /**
  6560. * Updates the given vector "result" from the normalization of the given one.
  6561. * @param vector the vector to normalize
  6562. * @param result the vector to store the result in
  6563. */
  6564. Vector4.NormalizeToRef = function (vector, result) {
  6565. result.copyFrom(vector);
  6566. result.normalize();
  6567. };
  6568. /**
  6569. * Returns a vector with the minimum values from the left and right vectors
  6570. * @param left left vector to minimize
  6571. * @param right right vector to minimize
  6572. * @returns a new vector with the minimum of the left and right vector values
  6573. */
  6574. Vector4.Minimize = function (left, right) {
  6575. var min = left.clone();
  6576. min.minimizeInPlace(right);
  6577. return min;
  6578. };
  6579. /**
  6580. * Returns a vector with the maximum values from the left and right vectors
  6581. * @param left left vector to maximize
  6582. * @param right right vector to maximize
  6583. * @returns a new vector with the maximum of the left and right vector values
  6584. */
  6585. Vector4.Maximize = function (left, right) {
  6586. var max = left.clone();
  6587. max.maximizeInPlace(right);
  6588. return max;
  6589. };
  6590. /**
  6591. * Returns the distance (float) between the vectors "value1" and "value2".
  6592. * @param value1 value to calulate the distance between
  6593. * @param value2 value to calulate the distance between
  6594. * @return the distance between the two vectors
  6595. */
  6596. Vector4.Distance = function (value1, value2) {
  6597. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  6598. };
  6599. /**
  6600. * Returns the squared distance (float) between the vectors "value1" and "value2".
  6601. * @param value1 value to calulate the distance between
  6602. * @param value2 value to calulate the distance between
  6603. * @return the distance between the two vectors squared
  6604. */
  6605. Vector4.DistanceSquared = function (value1, value2) {
  6606. var x = value1.x - value2.x;
  6607. var y = value1.y - value2.y;
  6608. var z = value1.z - value2.z;
  6609. var w = value1.w - value2.w;
  6610. return (x * x) + (y * y) + (z * z) + (w * w);
  6611. };
  6612. /**
  6613. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  6614. * @param value1 value to calulate the center between
  6615. * @param value2 value to calulate the center between
  6616. * @return the center between the two vectors
  6617. */
  6618. Vector4.Center = function (value1, value2) {
  6619. var center = value1.add(value2);
  6620. center.scaleInPlace(0.5);
  6621. return center;
  6622. };
  6623. /**
  6624. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  6625. * This methods computes transformed normalized direction vectors only.
  6626. * @param vector the vector to transform
  6627. * @param transformation the transformation matrix to apply
  6628. * @returns the new vector
  6629. */
  6630. Vector4.TransformNormal = function (vector, transformation) {
  6631. var result = Vector4.Zero();
  6632. Vector4.TransformNormalToRef(vector, transformation, result);
  6633. return result;
  6634. };
  6635. /**
  6636. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  6637. * This methods computes transformed normalized direction vectors only.
  6638. * @param vector the vector to transform
  6639. * @param transformation the transformation matrix to apply
  6640. * @param result the vector to store the result in
  6641. */
  6642. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  6643. var m = transformation.m;
  6644. var x = (vector.x * m[0]) + (vector.y * m[4]) + (vector.z * m[8]);
  6645. var y = (vector.x * m[1]) + (vector.y * m[5]) + (vector.z * m[9]);
  6646. var z = (vector.x * m[2]) + (vector.y * m[6]) + (vector.z * m[10]);
  6647. result.x = x;
  6648. result.y = y;
  6649. result.z = z;
  6650. result.w = vector.w;
  6651. };
  6652. /**
  6653. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  6654. * This methods computes transformed normalized direction vectors only.
  6655. * @param x value to transform
  6656. * @param y value to transform
  6657. * @param z value to transform
  6658. * @param w value to transform
  6659. * @param transformation the transformation matrix to apply
  6660. * @param result the vector to store the results in
  6661. */
  6662. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  6663. var m = transformation.m;
  6664. result.x = (x * m[0]) + (y * m[4]) + (z * m[8]);
  6665. result.y = (x * m[1]) + (y * m[5]) + (z * m[9]);
  6666. result.z = (x * m[2]) + (y * m[6]) + (z * m[10]);
  6667. result.w = w;
  6668. };
  6669. return Vector4;
  6670. }());
  6671. BABYLON.Vector4 = Vector4;
  6672. /**
  6673. * Size containing widht and height
  6674. */
  6675. var Size = /** @class */ (function () {
  6676. /**
  6677. * Creates a Size object from the given width and height (floats).
  6678. * @param width width of the new size
  6679. * @param height height of the new size
  6680. */
  6681. function Size(width, height) {
  6682. this.width = width;
  6683. this.height = height;
  6684. }
  6685. /**
  6686. * Returns a string with the Size width and height
  6687. * @returns a string with the Size width and height
  6688. */
  6689. Size.prototype.toString = function () {
  6690. return "{W: " + this.width + ", H: " + this.height + "}";
  6691. };
  6692. /**
  6693. * "Size"
  6694. * @returns the string "Size"
  6695. */
  6696. Size.prototype.getClassName = function () {
  6697. return "Size";
  6698. };
  6699. /**
  6700. * Returns the Size hash code.
  6701. * @returns a hash code for a unique width and height
  6702. */
  6703. Size.prototype.getHashCode = function () {
  6704. var hash = this.width || 0;
  6705. hash = (hash * 397) ^ (this.height || 0);
  6706. return hash;
  6707. };
  6708. /**
  6709. * Updates the current size from the given one.
  6710. * @param src the given size
  6711. */
  6712. Size.prototype.copyFrom = function (src) {
  6713. this.width = src.width;
  6714. this.height = src.height;
  6715. };
  6716. /**
  6717. * Updates in place the current Size from the given floats.
  6718. * @param width width of the new size
  6719. * @param height height of the new size
  6720. * @returns the updated Size.
  6721. */
  6722. Size.prototype.copyFromFloats = function (width, height) {
  6723. this.width = width;
  6724. this.height = height;
  6725. return this;
  6726. };
  6727. /**
  6728. * Updates in place the current Size from the given floats.
  6729. * @param width width to set
  6730. * @param height height to set
  6731. * @returns the updated Size.
  6732. */
  6733. Size.prototype.set = function (width, height) {
  6734. return this.copyFromFloats(width, height);
  6735. };
  6736. /**
  6737. * Multiplies the width and height by numbers
  6738. * @param w factor to multiple the width by
  6739. * @param h factor to multiple the height by
  6740. * @returns a new Size set with the multiplication result of the current Size and the given floats.
  6741. */
  6742. Size.prototype.multiplyByFloats = function (w, h) {
  6743. return new Size(this.width * w, this.height * h);
  6744. };
  6745. /**
  6746. * Clones the size
  6747. * @returns a new Size copied from the given one.
  6748. */
  6749. Size.prototype.clone = function () {
  6750. return new Size(this.width, this.height);
  6751. };
  6752. /**
  6753. * True if the current Size and the given one width and height are strictly equal.
  6754. * @param other the other size to compare against
  6755. * @returns True if the current Size and the given one width and height are strictly equal.
  6756. */
  6757. Size.prototype.equals = function (other) {
  6758. if (!other) {
  6759. return false;
  6760. }
  6761. return (this.width === other.width) && (this.height === other.height);
  6762. };
  6763. Object.defineProperty(Size.prototype, "surface", {
  6764. /**
  6765. * The surface of the Size : width * height (float).
  6766. */
  6767. get: function () {
  6768. return this.width * this.height;
  6769. },
  6770. enumerable: true,
  6771. configurable: true
  6772. });
  6773. /**
  6774. * Create a new size of zero
  6775. * @returns a new Size set to (0.0, 0.0)
  6776. */
  6777. Size.Zero = function () {
  6778. return new Size(0.0, 0.0);
  6779. };
  6780. /**
  6781. * Sums the width and height of two sizes
  6782. * @param otherSize size to add to this size
  6783. * @returns a new Size set as the addition result of the current Size and the given one.
  6784. */
  6785. Size.prototype.add = function (otherSize) {
  6786. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  6787. return r;
  6788. };
  6789. /**
  6790. * Subtracts the width and height of two
  6791. * @param otherSize size to subtract to this size
  6792. * @returns a new Size set as the subtraction result of the given one from the current Size.
  6793. */
  6794. Size.prototype.subtract = function (otherSize) {
  6795. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  6796. return r;
  6797. };
  6798. /**
  6799. * Creates a new Size set at the linear interpolation "amount" between "start" and "end"
  6800. * @param start starting size to lerp between
  6801. * @param end end size to lerp between
  6802. * @param amount amount to lerp between the start and end values
  6803. * @returns a new Size set at the linear interpolation "amount" between "start" and "end"
  6804. */
  6805. Size.Lerp = function (start, end, amount) {
  6806. var w = start.width + ((end.width - start.width) * amount);
  6807. var h = start.height + ((end.height - start.height) * amount);
  6808. return new Size(w, h);
  6809. };
  6810. return Size;
  6811. }());
  6812. BABYLON.Size = Size;
  6813. /**
  6814. * Class used to store quaternion data
  6815. * @see https://en.wikipedia.org/wiki/Quaternion
  6816. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  6817. */
  6818. var Quaternion = /** @class */ (function () {
  6819. /**
  6820. * Creates a new Quaternion from the given floats
  6821. * @param x defines the first component (0 by default)
  6822. * @param y defines the second component (0 by default)
  6823. * @param z defines the third component (0 by default)
  6824. * @param w defines the fourth component (1.0 by default)
  6825. */
  6826. function Quaternion(
  6827. /** defines the first component (0 by default) */
  6828. x,
  6829. /** defines the second component (0 by default) */
  6830. y,
  6831. /** defines the third component (0 by default) */
  6832. z,
  6833. /** defines the fourth component (1.0 by default) */
  6834. w) {
  6835. if (x === void 0) { x = 0.0; }
  6836. if (y === void 0) { y = 0.0; }
  6837. if (z === void 0) { z = 0.0; }
  6838. if (w === void 0) { w = 1.0; }
  6839. this.x = x;
  6840. this.y = y;
  6841. this.z = z;
  6842. this.w = w;
  6843. }
  6844. /**
  6845. * Gets a string representation for the current quaternion
  6846. * @returns a string with the Quaternion coordinates
  6847. */
  6848. Quaternion.prototype.toString = function () {
  6849. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  6850. };
  6851. /**
  6852. * Gets the class name of the quaternion
  6853. * @returns the string "Quaternion"
  6854. */
  6855. Quaternion.prototype.getClassName = function () {
  6856. return "Quaternion";
  6857. };
  6858. /**
  6859. * Gets a hash code for this quaternion
  6860. * @returns the quaternion hash code
  6861. */
  6862. Quaternion.prototype.getHashCode = function () {
  6863. var hash = this.x || 0;
  6864. hash = (hash * 397) ^ (this.y || 0);
  6865. hash = (hash * 397) ^ (this.z || 0);
  6866. hash = (hash * 397) ^ (this.w || 0);
  6867. return hash;
  6868. };
  6869. /**
  6870. * Copy the quaternion to an array
  6871. * @returns a new array populated with 4 elements from the quaternion coordinates
  6872. */
  6873. Quaternion.prototype.asArray = function () {
  6874. return [this.x, this.y, this.z, this.w];
  6875. };
  6876. /**
  6877. * Check if two quaternions are equals
  6878. * @param otherQuaternion defines the second operand
  6879. * @return true if the current quaternion and the given one coordinates are strictly equals
  6880. */
  6881. Quaternion.prototype.equals = function (otherQuaternion) {
  6882. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  6883. };
  6884. /**
  6885. * Clone the current quaternion
  6886. * @returns a new quaternion copied from the current one
  6887. */
  6888. Quaternion.prototype.clone = function () {
  6889. return new Quaternion(this.x, this.y, this.z, this.w);
  6890. };
  6891. /**
  6892. * Copy a quaternion to the current one
  6893. * @param other defines the other quaternion
  6894. * @returns the updated current quaternion
  6895. */
  6896. Quaternion.prototype.copyFrom = function (other) {
  6897. this.x = other.x;
  6898. this.y = other.y;
  6899. this.z = other.z;
  6900. this.w = other.w;
  6901. return this;
  6902. };
  6903. /**
  6904. * Updates the current quaternion with the given float coordinates
  6905. * @param x defines the x coordinate
  6906. * @param y defines the y coordinate
  6907. * @param z defines the z coordinate
  6908. * @param w defines the w coordinate
  6909. * @returns the updated current quaternion
  6910. */
  6911. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  6912. this.x = x;
  6913. this.y = y;
  6914. this.z = z;
  6915. this.w = w;
  6916. return this;
  6917. };
  6918. /**
  6919. * Updates the current quaternion from the given float coordinates
  6920. * @param x defines the x coordinate
  6921. * @param y defines the y coordinate
  6922. * @param z defines the z coordinate
  6923. * @param w defines the w coordinate
  6924. * @returns the updated current quaternion
  6925. */
  6926. Quaternion.prototype.set = function (x, y, z, w) {
  6927. return this.copyFromFloats(x, y, z, w);
  6928. };
  6929. /**
  6930. * Adds two quaternions
  6931. * @param other defines the second operand
  6932. * @returns a new quaternion as the addition result of the given one and the current quaternion
  6933. */
  6934. Quaternion.prototype.add = function (other) {
  6935. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  6936. };
  6937. /**
  6938. * Add a quaternion to the current one
  6939. * @param other defines the quaternion to add
  6940. * @returns the current quaternion
  6941. */
  6942. Quaternion.prototype.addInPlace = function (other) {
  6943. this.x += other.x;
  6944. this.y += other.y;
  6945. this.z += other.z;
  6946. this.w += other.w;
  6947. return this;
  6948. };
  6949. /**
  6950. * Subtract two quaternions
  6951. * @param other defines the second operand
  6952. * @returns a new quaternion as the subtraction result of the given one from the current one
  6953. */
  6954. Quaternion.prototype.subtract = function (other) {
  6955. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  6956. };
  6957. /**
  6958. * Multiplies the current quaternion by a scale factor
  6959. * @param value defines the scale factor
  6960. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  6961. */
  6962. Quaternion.prototype.scale = function (value) {
  6963. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  6964. };
  6965. /**
  6966. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  6967. * @param scale defines the scale factor
  6968. * @param result defines the Quaternion object where to store the result
  6969. * @returns the unmodified current quaternion
  6970. */
  6971. Quaternion.prototype.scaleToRef = function (scale, result) {
  6972. result.x = this.x * scale;
  6973. result.y = this.y * scale;
  6974. result.z = this.z * scale;
  6975. result.w = this.w * scale;
  6976. return this;
  6977. };
  6978. /**
  6979. * Multiplies in place the current quaternion by a scale factor
  6980. * @param value defines the scale factor
  6981. * @returns the current modified quaternion
  6982. */
  6983. Quaternion.prototype.scaleInPlace = function (value) {
  6984. this.x *= value;
  6985. this.y *= value;
  6986. this.z *= value;
  6987. this.w *= value;
  6988. return this;
  6989. };
  6990. /**
  6991. * Scale the current quaternion values by a factor and add the result to a given quaternion
  6992. * @param scale defines the scale factor
  6993. * @param result defines the Quaternion object where to store the result
  6994. * @returns the unmodified current quaternion
  6995. */
  6996. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  6997. result.x += this.x * scale;
  6998. result.y += this.y * scale;
  6999. result.z += this.z * scale;
  7000. result.w += this.w * scale;
  7001. return this;
  7002. };
  7003. /**
  7004. * Multiplies two quaternions
  7005. * @param q1 defines the second operand
  7006. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  7007. */
  7008. Quaternion.prototype.multiply = function (q1) {
  7009. var result = new Quaternion(0, 0, 0, 1.0);
  7010. this.multiplyToRef(q1, result);
  7011. return result;
  7012. };
  7013. /**
  7014. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  7015. * @param q1 defines the second operand
  7016. * @param result defines the target quaternion
  7017. * @returns the current quaternion
  7018. */
  7019. Quaternion.prototype.multiplyToRef = function (q1, result) {
  7020. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  7021. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  7022. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  7023. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  7024. result.copyFromFloats(x, y, z, w);
  7025. return this;
  7026. };
  7027. /**
  7028. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  7029. * @param q1 defines the second operand
  7030. * @returns the currentupdated quaternion
  7031. */
  7032. Quaternion.prototype.multiplyInPlace = function (q1) {
  7033. this.multiplyToRef(q1, this);
  7034. return this;
  7035. };
  7036. /**
  7037. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  7038. * @param ref defines the target quaternion
  7039. * @returns the current quaternion
  7040. */
  7041. Quaternion.prototype.conjugateToRef = function (ref) {
  7042. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  7043. return this;
  7044. };
  7045. /**
  7046. * Conjugates in place (1-q) the current quaternion
  7047. * @returns the current updated quaternion
  7048. */
  7049. Quaternion.prototype.conjugateInPlace = function () {
  7050. this.x *= -1;
  7051. this.y *= -1;
  7052. this.z *= -1;
  7053. return this;
  7054. };
  7055. /**
  7056. * Conjugates in place (1-q) the current quaternion
  7057. * @returns a new quaternion
  7058. */
  7059. Quaternion.prototype.conjugate = function () {
  7060. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  7061. return result;
  7062. };
  7063. /**
  7064. * Gets length of current quaternion
  7065. * @returns the quaternion length (float)
  7066. */
  7067. Quaternion.prototype.length = function () {
  7068. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  7069. };
  7070. /**
  7071. * Normalize in place the current quaternion
  7072. * @returns the current updated quaternion
  7073. */
  7074. Quaternion.prototype.normalize = function () {
  7075. var length = 1.0 / this.length();
  7076. this.x *= length;
  7077. this.y *= length;
  7078. this.z *= length;
  7079. this.w *= length;
  7080. return this;
  7081. };
  7082. /**
  7083. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  7084. * @param order is a reserved parameter and is ignore for now
  7085. * @returns a new Vector3 containing the Euler angles
  7086. */
  7087. Quaternion.prototype.toEulerAngles = function (order) {
  7088. if (order === void 0) { order = "YZX"; }
  7089. var result = Vector3.Zero();
  7090. this.toEulerAnglesToRef(result, order);
  7091. return result;
  7092. };
  7093. /**
  7094. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  7095. * @param result defines the vector which will be filled with the Euler angles
  7096. * @param order is a reserved parameter and is ignore for now
  7097. * @returns the current unchanged quaternion
  7098. */
  7099. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  7100. if (order === void 0) { order = "YZX"; }
  7101. var qz = this.z;
  7102. var qx = this.x;
  7103. var qy = this.y;
  7104. var qw = this.w;
  7105. var sqw = qw * qw;
  7106. var sqz = qz * qz;
  7107. var sqx = qx * qx;
  7108. var sqy = qy * qy;
  7109. var zAxisY = qy * qz - qx * qw;
  7110. var limit = .4999999;
  7111. if (zAxisY < -limit) {
  7112. result.y = 2 * Math.atan2(qy, qw);
  7113. result.x = Math.PI / 2;
  7114. result.z = 0;
  7115. }
  7116. else if (zAxisY > limit) {
  7117. result.y = 2 * Math.atan2(qy, qw);
  7118. result.x = -Math.PI / 2;
  7119. result.z = 0;
  7120. }
  7121. else {
  7122. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  7123. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  7124. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  7125. }
  7126. return this;
  7127. };
  7128. /**
  7129. * Updates the given rotation matrix with the current quaternion values
  7130. * @param result defines the target matrix
  7131. * @returns the current unchanged quaternion
  7132. */
  7133. Quaternion.prototype.toRotationMatrix = function (result) {
  7134. Matrix.FromQuaternionToRef(this, result);
  7135. return this;
  7136. };
  7137. /**
  7138. * Updates the current quaternion from the given rotation matrix values
  7139. * @param matrix defines the source matrix
  7140. * @returns the current updated quaternion
  7141. */
  7142. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  7143. Quaternion.FromRotationMatrixToRef(matrix, this);
  7144. return this;
  7145. };
  7146. // Statics
  7147. /**
  7148. * Creates a new quaternion from a rotation matrix
  7149. * @param matrix defines the source matrix
  7150. * @returns a new quaternion created from the given rotation matrix values
  7151. */
  7152. Quaternion.FromRotationMatrix = function (matrix) {
  7153. var result = new Quaternion();
  7154. Quaternion.FromRotationMatrixToRef(matrix, result);
  7155. return result;
  7156. };
  7157. /**
  7158. * Updates the given quaternion with the given rotation matrix values
  7159. * @param matrix defines the source matrix
  7160. * @param result defines the target quaternion
  7161. */
  7162. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  7163. var data = matrix.m;
  7164. var m11 = data[0], m12 = data[4], m13 = data[8];
  7165. var m21 = data[1], m22 = data[5], m23 = data[9];
  7166. var m31 = data[2], m32 = data[6], m33 = data[10];
  7167. var trace = m11 + m22 + m33;
  7168. var s;
  7169. if (trace > 0) {
  7170. s = 0.5 / Math.sqrt(trace + 1.0);
  7171. result.w = 0.25 / s;
  7172. result.x = (m32 - m23) * s;
  7173. result.y = (m13 - m31) * s;
  7174. result.z = (m21 - m12) * s;
  7175. }
  7176. else if (m11 > m22 && m11 > m33) {
  7177. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  7178. result.w = (m32 - m23) / s;
  7179. result.x = 0.25 * s;
  7180. result.y = (m12 + m21) / s;
  7181. result.z = (m13 + m31) / s;
  7182. }
  7183. else if (m22 > m33) {
  7184. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  7185. result.w = (m13 - m31) / s;
  7186. result.x = (m12 + m21) / s;
  7187. result.y = 0.25 * s;
  7188. result.z = (m23 + m32) / s;
  7189. }
  7190. else {
  7191. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  7192. result.w = (m21 - m12) / s;
  7193. result.x = (m13 + m31) / s;
  7194. result.y = (m23 + m32) / s;
  7195. result.z = 0.25 * s;
  7196. }
  7197. };
  7198. /**
  7199. * Returns the dot product (float) between the quaternions "left" and "right"
  7200. * @param left defines the left operand
  7201. * @param right defines the right operand
  7202. * @returns the dot product
  7203. */
  7204. Quaternion.Dot = function (left, right) {
  7205. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  7206. };
  7207. /**
  7208. * Checks if the two quaternions are close to each other
  7209. * @param quat0 defines the first quaternion to check
  7210. * @param quat1 defines the second quaternion to check
  7211. * @returns true if the two quaternions are close to each other
  7212. */
  7213. Quaternion.AreClose = function (quat0, quat1) {
  7214. var dot = Quaternion.Dot(quat0, quat1);
  7215. return dot >= 0;
  7216. };
  7217. /**
  7218. * Creates an empty quaternion
  7219. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  7220. */
  7221. Quaternion.Zero = function () {
  7222. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  7223. };
  7224. /**
  7225. * Inverse a given quaternion
  7226. * @param q defines the source quaternion
  7227. * @returns a new quaternion as the inverted current quaternion
  7228. */
  7229. Quaternion.Inverse = function (q) {
  7230. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  7231. };
  7232. /**
  7233. * Inverse a given quaternion
  7234. * @param q defines the source quaternion
  7235. * @param result the quaternion the result will be stored in
  7236. * @returns the result quaternion
  7237. */
  7238. Quaternion.InverseToRef = function (q, result) {
  7239. result.set(-q.x, -q.y, -q.z, q.w);
  7240. return result;
  7241. };
  7242. /**
  7243. * Creates an identity quaternion
  7244. * @returns the identity quaternion
  7245. */
  7246. Quaternion.Identity = function () {
  7247. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  7248. };
  7249. /**
  7250. * Gets a boolean indicating if the given quaternion is identity
  7251. * @param quaternion defines the quaternion to check
  7252. * @returns true if the quaternion is identity
  7253. */
  7254. Quaternion.IsIdentity = function (quaternion) {
  7255. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  7256. };
  7257. /**
  7258. * Creates a quaternion from a rotation around an axis
  7259. * @param axis defines the axis to use
  7260. * @param angle defines the angle to use
  7261. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  7262. */
  7263. Quaternion.RotationAxis = function (axis, angle) {
  7264. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  7265. };
  7266. /**
  7267. * Creates a rotation around an axis and stores it into the given quaternion
  7268. * @param axis defines the axis to use
  7269. * @param angle defines the angle to use
  7270. * @param result defines the target quaternion
  7271. * @returns the target quaternion
  7272. */
  7273. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  7274. var sin = Math.sin(angle / 2);
  7275. axis.normalize();
  7276. result.w = Math.cos(angle / 2);
  7277. result.x = axis.x * sin;
  7278. result.y = axis.y * sin;
  7279. result.z = axis.z * sin;
  7280. return result;
  7281. };
  7282. /**
  7283. * Creates a new quaternion from data stored into an array
  7284. * @param array defines the data source
  7285. * @param offset defines the offset in the source array where the data starts
  7286. * @returns a new quaternion
  7287. */
  7288. Quaternion.FromArray = function (array, offset) {
  7289. if (!offset) {
  7290. offset = 0;
  7291. }
  7292. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  7293. };
  7294. /**
  7295. * Create a quaternion from Euler rotation angles
  7296. * @param x Pitch
  7297. * @param y Yaw
  7298. * @param z Roll
  7299. * @returns the new Quaternion
  7300. */
  7301. Quaternion.FromEulerAngles = function (x, y, z) {
  7302. var q = new Quaternion();
  7303. Quaternion.RotationYawPitchRollToRef(y, x, z, q);
  7304. return q;
  7305. };
  7306. /**
  7307. * Updates a quaternion from Euler rotation angles
  7308. * @param x Pitch
  7309. * @param y Yaw
  7310. * @param z Roll
  7311. * @param result the quaternion to store the result
  7312. * @returns the updated quaternion
  7313. */
  7314. Quaternion.FromEulerAnglesToRef = function (x, y, z, result) {
  7315. Quaternion.RotationYawPitchRollToRef(y, x, z, result);
  7316. return result;
  7317. };
  7318. /**
  7319. * Create a quaternion from Euler rotation vector
  7320. * @param vec the Euler vector (x Pitch, y Yaw, z Roll)
  7321. * @returns the new Quaternion
  7322. */
  7323. Quaternion.FromEulerVector = function (vec) {
  7324. var q = new Quaternion();
  7325. Quaternion.RotationYawPitchRollToRef(vec.y, vec.x, vec.z, q);
  7326. return q;
  7327. };
  7328. /**
  7329. * Updates a quaternion from Euler rotation vector
  7330. * @param vec the Euler vector (x Pitch, y Yaw, z Roll)
  7331. * @param result the quaternion to store the result
  7332. * @returns the updated quaternion
  7333. */
  7334. Quaternion.FromEulerVectorToRef = function (vec, result) {
  7335. Quaternion.RotationYawPitchRollToRef(vec.y, vec.x, vec.z, result);
  7336. return result;
  7337. };
  7338. /**
  7339. * Creates a new quaternion from the given Euler float angles (y, x, z)
  7340. * @param yaw defines the rotation around Y axis
  7341. * @param pitch defines the rotation around X axis
  7342. * @param roll defines the rotation around Z axis
  7343. * @returns the new quaternion
  7344. */
  7345. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  7346. var q = new Quaternion();
  7347. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  7348. return q;
  7349. };
  7350. /**
  7351. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  7352. * @param yaw defines the rotation around Y axis
  7353. * @param pitch defines the rotation around X axis
  7354. * @param roll defines the rotation around Z axis
  7355. * @param result defines the target quaternion
  7356. */
  7357. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  7358. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  7359. var halfRoll = roll * 0.5;
  7360. var halfPitch = pitch * 0.5;
  7361. var halfYaw = yaw * 0.5;
  7362. var sinRoll = Math.sin(halfRoll);
  7363. var cosRoll = Math.cos(halfRoll);
  7364. var sinPitch = Math.sin(halfPitch);
  7365. var cosPitch = Math.cos(halfPitch);
  7366. var sinYaw = Math.sin(halfYaw);
  7367. var cosYaw = Math.cos(halfYaw);
  7368. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  7369. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  7370. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  7371. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  7372. };
  7373. /**
  7374. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  7375. * @param alpha defines the rotation around first axis
  7376. * @param beta defines the rotation around second axis
  7377. * @param gamma defines the rotation around third axis
  7378. * @returns the new quaternion
  7379. */
  7380. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  7381. var result = new Quaternion();
  7382. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  7383. return result;
  7384. };
  7385. /**
  7386. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  7387. * @param alpha defines the rotation around first axis
  7388. * @param beta defines the rotation around second axis
  7389. * @param gamma defines the rotation around third axis
  7390. * @param result defines the target quaternion
  7391. */
  7392. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  7393. // Produces a quaternion from Euler angles in the z-x-z orientation
  7394. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  7395. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  7396. var halfBeta = beta * 0.5;
  7397. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  7398. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  7399. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  7400. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  7401. };
  7402. /**
  7403. * 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)
  7404. * @param axis1 defines the first axis
  7405. * @param axis2 defines the second axis
  7406. * @param axis3 defines the third axis
  7407. * @returns the new quaternion
  7408. */
  7409. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  7410. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  7411. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  7412. return quat;
  7413. };
  7414. /**
  7415. * 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
  7416. * @param axis1 defines the first axis
  7417. * @param axis2 defines the second axis
  7418. * @param axis3 defines the third axis
  7419. * @param ref defines the target quaternion
  7420. */
  7421. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  7422. var rotMat = MathTmp.Matrix[0];
  7423. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  7424. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  7425. };
  7426. /**
  7427. * Interpolates between two quaternions
  7428. * @param left defines first quaternion
  7429. * @param right defines second quaternion
  7430. * @param amount defines the gradient to use
  7431. * @returns the new interpolated quaternion
  7432. */
  7433. Quaternion.Slerp = function (left, right, amount) {
  7434. var result = Quaternion.Identity();
  7435. Quaternion.SlerpToRef(left, right, amount, result);
  7436. return result;
  7437. };
  7438. /**
  7439. * Interpolates between two quaternions and stores it into a target quaternion
  7440. * @param left defines first quaternion
  7441. * @param right defines second quaternion
  7442. * @param amount defines the gradient to use
  7443. * @param result defines the target quaternion
  7444. */
  7445. Quaternion.SlerpToRef = function (left, right, amount, result) {
  7446. var num2;
  7447. var num3;
  7448. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  7449. var flag = false;
  7450. if (num4 < 0) {
  7451. flag = true;
  7452. num4 = -num4;
  7453. }
  7454. if (num4 > 0.999999) {
  7455. num3 = 1 - amount;
  7456. num2 = flag ? -amount : amount;
  7457. }
  7458. else {
  7459. var num5 = Math.acos(num4);
  7460. var num6 = (1.0 / Math.sin(num5));
  7461. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  7462. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  7463. }
  7464. result.x = (num3 * left.x) + (num2 * right.x);
  7465. result.y = (num3 * left.y) + (num2 * right.y);
  7466. result.z = (num3 * left.z) + (num2 * right.z);
  7467. result.w = (num3 * left.w) + (num2 * right.w);
  7468. };
  7469. /**
  7470. * Interpolate between two quaternions using Hermite interpolation
  7471. * @param value1 defines first quaternion
  7472. * @param tangent1 defines the incoming tangent
  7473. * @param value2 defines second quaternion
  7474. * @param tangent2 defines the outgoing tangent
  7475. * @param amount defines the target quaternion
  7476. * @returns the new interpolated quaternion
  7477. */
  7478. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7479. var squared = amount * amount;
  7480. var cubed = amount * squared;
  7481. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7482. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7483. var part3 = (cubed - (2.0 * squared)) + amount;
  7484. var part4 = cubed - squared;
  7485. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  7486. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  7487. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  7488. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  7489. return new Quaternion(x, y, z, w);
  7490. };
  7491. return Quaternion;
  7492. }());
  7493. BABYLON.Quaternion = Quaternion;
  7494. /**
  7495. * Class used to store matrix data (4x4)
  7496. */
  7497. var Matrix = /** @class */ (function () {
  7498. /**
  7499. * Creates an empty matrix (filled with zeros)
  7500. */
  7501. function Matrix() {
  7502. this._isIdentity = false;
  7503. this._isIdentityDirty = true;
  7504. this._isIdentity3x2 = true;
  7505. this._isIdentity3x2Dirty = true;
  7506. this._m = new Float32Array(16);
  7507. this._updateIdentityStatus(false);
  7508. }
  7509. Object.defineProperty(Matrix.prototype, "m", {
  7510. /**
  7511. * Gets the internal data of the matrix
  7512. */
  7513. get: function () { return this._m; },
  7514. enumerable: true,
  7515. configurable: true
  7516. });
  7517. /** @hidden */
  7518. Matrix.prototype._markAsUpdated = function () {
  7519. this.updateFlag = Matrix._updateFlagSeed++;
  7520. this._isIdentity = false;
  7521. this._isIdentity3x2 = false;
  7522. this._isIdentityDirty = true;
  7523. this._isIdentity3x2Dirty = true;
  7524. };
  7525. /** @hidden */
  7526. Matrix.prototype._updateIdentityStatus = function (isIdentity, isIdentityDirty, isIdentity3x2, isIdentity3x2Dirty) {
  7527. if (isIdentityDirty === void 0) { isIdentityDirty = false; }
  7528. if (isIdentity3x2 === void 0) { isIdentity3x2 = false; }
  7529. if (isIdentity3x2Dirty === void 0) { isIdentity3x2Dirty = true; }
  7530. this.updateFlag = Matrix._updateFlagSeed++;
  7531. this._isIdentity = isIdentity;
  7532. this._isIdentity3x2 = isIdentity || isIdentity3x2;
  7533. this._isIdentityDirty = this._isIdentity ? false : isIdentityDirty;
  7534. this._isIdentity3x2Dirty = this._isIdentity3x2 ? false : isIdentity3x2Dirty;
  7535. };
  7536. // Properties
  7537. /**
  7538. * Check if the current matrix is identity
  7539. * @returns true is the matrix is the identity matrix
  7540. */
  7541. Matrix.prototype.isIdentity = function () {
  7542. if (this._isIdentityDirty) {
  7543. this._isIdentityDirty = false;
  7544. var m = this._m;
  7545. this._isIdentity = (m[0] === 1.0 && m[1] === 0.0 && m[2] === 0.0 && m[3] === 0.0 &&
  7546. m[4] === 0.0 && m[5] === 1.0 && m[6] === 0.0 && m[7] === 0.0 &&
  7547. m[8] === 0.0 && m[9] === 0.0 && m[10] === 1.0 && m[11] === 0.0 &&
  7548. m[12] === 0.0 && m[13] === 0.0 && m[14] === 0.0 && m[15] === 1.0);
  7549. }
  7550. return this._isIdentity;
  7551. };
  7552. /**
  7553. * Check if the current matrix is identity as a texture matrix (3x2 store in 4x4)
  7554. * @returns true is the matrix is the identity matrix
  7555. */
  7556. Matrix.prototype.isIdentityAs3x2 = function () {
  7557. if (this._isIdentity3x2Dirty) {
  7558. this._isIdentity3x2Dirty = false;
  7559. if (this._m[0] !== 1.0 || this._m[5] !== 1.0 || this._m[15] !== 1.0) {
  7560. this._isIdentity3x2 = false;
  7561. }
  7562. else if (this._m[1] !== 0.0 || this._m[2] !== 0.0 || this._m[3] !== 0.0 ||
  7563. this._m[4] !== 0.0 || this._m[6] !== 0.0 || this._m[7] !== 0.0 ||
  7564. this._m[8] !== 0.0 || this._m[9] !== 0.0 || this._m[10] !== 0.0 || this._m[11] !== 0.0 ||
  7565. this._m[12] !== 0.0 || this._m[13] !== 0.0 || this._m[14] !== 0.0) {
  7566. this._isIdentity3x2 = false;
  7567. }
  7568. else {
  7569. this._isIdentity3x2 = true;
  7570. }
  7571. }
  7572. return this._isIdentity3x2;
  7573. };
  7574. /**
  7575. * Gets the determinant of the matrix
  7576. * @returns the matrix determinant
  7577. */
  7578. Matrix.prototype.determinant = function () {
  7579. if (this._isIdentity === true) {
  7580. return 1;
  7581. }
  7582. var m = this._m;
  7583. var m00 = m[0], m01 = m[1], m02 = m[2], m03 = m[3];
  7584. var m10 = m[4], m11 = m[5], m12 = m[6], m13 = m[7];
  7585. var m20 = m[8], m21 = m[9], m22 = m[10], m23 = m[11];
  7586. var m30 = m[12], m31 = m[13], m32 = m[14], m33 = m[15];
  7587. // https://en.wikipedia.org/wiki/Laplace_expansion
  7588. // to compute the deterrminant of a 4x4 Matrix we compute the cofactors of any row or column,
  7589. // then we multiply each Cofactor by its corresponding matrix value and sum them all to get the determinant
  7590. // Cofactor(i, j) = sign(i,j) * det(Minor(i, j))
  7591. // where
  7592. // - sign(i,j) = (i+j) % 2 === 0 ? 1 : -1
  7593. // - Minor(i, j) is the 3x3 matrix we get by removing row i and column j from current Matrix
  7594. //
  7595. // Here we do that for the 1st row.
  7596. var det_22_33 = m22 * m33 - m32 * m23;
  7597. var det_21_33 = m21 * m33 - m31 * m23;
  7598. var det_21_32 = m21 * m32 - m31 * m22;
  7599. var det_20_33 = m20 * m33 - m30 * m23;
  7600. var det_20_32 = m20 * m32 - m22 * m30;
  7601. var det_20_31 = m20 * m31 - m30 * m21;
  7602. var cofact_00 = +(m11 * det_22_33 - m12 * det_21_33 + m13 * det_21_32);
  7603. var cofact_01 = -(m10 * det_22_33 - m12 * det_20_33 + m13 * det_20_32);
  7604. var cofact_02 = +(m10 * det_21_33 - m11 * det_20_33 + m13 * det_20_31);
  7605. var cofact_03 = -(m10 * det_21_32 - m11 * det_20_32 + m12 * det_20_31);
  7606. return m00 * cofact_00 + m01 * cofact_01 + m02 * cofact_02 + m03 * cofact_03;
  7607. };
  7608. // Methods
  7609. /**
  7610. * Returns the matrix as a Float32Array
  7611. * @returns the matrix underlying array
  7612. */
  7613. Matrix.prototype.toArray = function () {
  7614. return this._m;
  7615. };
  7616. /**
  7617. * Returns the matrix as a Float32Array
  7618. * @returns the matrix underlying array.
  7619. */
  7620. Matrix.prototype.asArray = function () {
  7621. return this._m;
  7622. };
  7623. /**
  7624. * Inverts the current matrix in place
  7625. * @returns the current inverted matrix
  7626. */
  7627. Matrix.prototype.invert = function () {
  7628. this.invertToRef(this);
  7629. return this;
  7630. };
  7631. /**
  7632. * Sets all the matrix elements to zero
  7633. * @returns the current matrix
  7634. */
  7635. Matrix.prototype.reset = function () {
  7636. Matrix.FromValuesToRef(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, this);
  7637. this._updateIdentityStatus(false);
  7638. return this;
  7639. };
  7640. /**
  7641. * Adds the current matrix with a second one
  7642. * @param other defines the matrix to add
  7643. * @returns a new matrix as the addition of the current matrix and the given one
  7644. */
  7645. Matrix.prototype.add = function (other) {
  7646. var result = new Matrix();
  7647. this.addToRef(other, result);
  7648. return result;
  7649. };
  7650. /**
  7651. * Sets the given matrix "result" to the addition of the current matrix and the given one
  7652. * @param other defines the matrix to add
  7653. * @param result defines the target matrix
  7654. * @returns the current matrix
  7655. */
  7656. Matrix.prototype.addToRef = function (other, result) {
  7657. for (var index = 0; index < 16; index++) {
  7658. result._m[index] = this._m[index] + other._m[index];
  7659. }
  7660. result._markAsUpdated();
  7661. return this;
  7662. };
  7663. /**
  7664. * Adds in place the given matrix to the current matrix
  7665. * @param other defines the second operand
  7666. * @returns the current updated matrix
  7667. */
  7668. Matrix.prototype.addToSelf = function (other) {
  7669. for (var index = 0; index < 16; index++) {
  7670. this._m[index] += other._m[index];
  7671. }
  7672. this._markAsUpdated();
  7673. return this;
  7674. };
  7675. /**
  7676. * Sets the given matrix to the current inverted Matrix
  7677. * @param other defines the target matrix
  7678. * @returns the unmodified current matrix
  7679. */
  7680. Matrix.prototype.invertToRef = function (other) {
  7681. if (this._isIdentity === true) {
  7682. Matrix.IdentityToRef(other);
  7683. return this;
  7684. }
  7685. // the inverse of a Matrix is the transpose of cofactor matrix divided by the determinant
  7686. var m = this._m;
  7687. var m00 = m[0], m01 = m[1], m02 = m[2], m03 = m[3];
  7688. var m10 = m[4], m11 = m[5], m12 = m[6], m13 = m[7];
  7689. var m20 = m[8], m21 = m[9], m22 = m[10], m23 = m[11];
  7690. var m30 = m[12], m31 = m[13], m32 = m[14], m33 = m[15];
  7691. var det_22_33 = m22 * m33 - m32 * m23;
  7692. var det_21_33 = m21 * m33 - m31 * m23;
  7693. var det_21_32 = m21 * m32 - m31 * m22;
  7694. var det_20_33 = m20 * m33 - m30 * m23;
  7695. var det_20_32 = m20 * m32 - m22 * m30;
  7696. var det_20_31 = m20 * m31 - m30 * m21;
  7697. var cofact_00 = +(m11 * det_22_33 - m12 * det_21_33 + m13 * det_21_32);
  7698. var cofact_01 = -(m10 * det_22_33 - m12 * det_20_33 + m13 * det_20_32);
  7699. var cofact_02 = +(m10 * det_21_33 - m11 * det_20_33 + m13 * det_20_31);
  7700. var cofact_03 = -(m10 * det_21_32 - m11 * det_20_32 + m12 * det_20_31);
  7701. var det = m00 * cofact_00 + m01 * cofact_01 + m02 * cofact_02 + m03 * cofact_03;
  7702. if (det === 0) {
  7703. // not invertible
  7704. other.copyFrom(this);
  7705. return this;
  7706. }
  7707. var detInv = 1 / det;
  7708. var det_12_33 = m12 * m33 - m32 * m13;
  7709. var det_11_33 = m11 * m33 - m31 * m13;
  7710. var det_11_32 = m11 * m32 - m31 * m12;
  7711. var det_10_33 = m10 * m33 - m30 * m13;
  7712. var det_10_32 = m10 * m32 - m30 * m12;
  7713. var det_10_31 = m10 * m31 - m30 * m11;
  7714. var det_12_23 = m12 * m23 - m22 * m13;
  7715. var det_11_23 = m11 * m23 - m21 * m13;
  7716. var det_11_22 = m11 * m22 - m21 * m12;
  7717. var det_10_23 = m10 * m23 - m20 * m13;
  7718. var det_10_22 = m10 * m22 - m20 * m12;
  7719. var det_10_21 = m10 * m21 - m20 * m11;
  7720. var cofact_10 = -(m01 * det_22_33 - m02 * det_21_33 + m03 * det_21_32);
  7721. var cofact_11 = +(m00 * det_22_33 - m02 * det_20_33 + m03 * det_20_32);
  7722. var cofact_12 = -(m00 * det_21_33 - m01 * det_20_33 + m03 * det_20_31);
  7723. var cofact_13 = +(m00 * det_21_32 - m01 * det_20_32 + m02 * det_20_31);
  7724. var cofact_20 = +(m01 * det_12_33 - m02 * det_11_33 + m03 * det_11_32);
  7725. var cofact_21 = -(m00 * det_12_33 - m02 * det_10_33 + m03 * det_10_32);
  7726. var cofact_22 = +(m00 * det_11_33 - m01 * det_10_33 + m03 * det_10_31);
  7727. var cofact_23 = -(m00 * det_11_32 - m01 * det_10_32 + m02 * det_10_31);
  7728. var cofact_30 = -(m01 * det_12_23 - m02 * det_11_23 + m03 * det_11_22);
  7729. var cofact_31 = +(m00 * det_12_23 - m02 * det_10_23 + m03 * det_10_22);
  7730. var cofact_32 = -(m00 * det_11_23 - m01 * det_10_23 + m03 * det_10_21);
  7731. var cofact_33 = +(m00 * det_11_22 - m01 * det_10_22 + m02 * det_10_21);
  7732. Matrix.FromValuesToRef(cofact_00 * detInv, cofact_10 * detInv, cofact_20 * detInv, cofact_30 * detInv, cofact_01 * detInv, cofact_11 * detInv, cofact_21 * detInv, cofact_31 * detInv, cofact_02 * detInv, cofact_12 * detInv, cofact_22 * detInv, cofact_32 * detInv, cofact_03 * detInv, cofact_13 * detInv, cofact_23 * detInv, cofact_33 * detInv, other);
  7733. return this;
  7734. };
  7735. /**
  7736. * add a value at the specified position in the current Matrix
  7737. * @param index the index of the value within the matrix. between 0 and 15.
  7738. * @param value the value to be added
  7739. * @returns the current updated matrix
  7740. */
  7741. Matrix.prototype.addAtIndex = function (index, value) {
  7742. this._m[index] += value;
  7743. this._markAsUpdated();
  7744. return this;
  7745. };
  7746. /**
  7747. * mutiply the specified position in the current Matrix by a value
  7748. * @param index the index of the value within the matrix. between 0 and 15.
  7749. * @param value the value to be added
  7750. * @returns the current updated matrix
  7751. */
  7752. Matrix.prototype.multiplyAtIndex = function (index, value) {
  7753. this._m[index] *= value;
  7754. this._markAsUpdated();
  7755. return this;
  7756. };
  7757. /**
  7758. * Inserts the translation vector (using 3 floats) in the current matrix
  7759. * @param x defines the 1st component of the translation
  7760. * @param y defines the 2nd component of the translation
  7761. * @param z defines the 3rd component of the translation
  7762. * @returns the current updated matrix
  7763. */
  7764. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  7765. this._m[12] = x;
  7766. this._m[13] = y;
  7767. this._m[14] = z;
  7768. this._markAsUpdated();
  7769. return this;
  7770. };
  7771. /**
  7772. * Inserts the translation vector in the current matrix
  7773. * @param vector3 defines the translation to insert
  7774. * @returns the current updated matrix
  7775. */
  7776. Matrix.prototype.setTranslation = function (vector3) {
  7777. return this.setTranslationFromFloats(vector3.x, vector3.y, vector3.z);
  7778. };
  7779. /**
  7780. * Gets the translation value of the current matrix
  7781. * @returns a new Vector3 as the extracted translation from the matrix
  7782. */
  7783. Matrix.prototype.getTranslation = function () {
  7784. return new Vector3(this._m[12], this._m[13], this._m[14]);
  7785. };
  7786. /**
  7787. * Fill a Vector3 with the extracted translation from the matrix
  7788. * @param result defines the Vector3 where to store the translation
  7789. * @returns the current matrix
  7790. */
  7791. Matrix.prototype.getTranslationToRef = function (result) {
  7792. result.x = this._m[12];
  7793. result.y = this._m[13];
  7794. result.z = this._m[14];
  7795. return this;
  7796. };
  7797. /**
  7798. * Remove rotation and scaling part from the matrix
  7799. * @returns the updated matrix
  7800. */
  7801. Matrix.prototype.removeRotationAndScaling = function () {
  7802. var m = this.m;
  7803. 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, m[12], m[13], m[14], m[15], this);
  7804. this._updateIdentityStatus(m[12] === 0 && m[13] === 0 && m[14] === 0 && m[15] === 1);
  7805. return this;
  7806. };
  7807. /**
  7808. * Multiply two matrices
  7809. * @param other defines the second operand
  7810. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  7811. */
  7812. Matrix.prototype.multiply = function (other) {
  7813. var result = new Matrix();
  7814. this.multiplyToRef(other, result);
  7815. return result;
  7816. };
  7817. /**
  7818. * Copy the current matrix from the given one
  7819. * @param other defines the source matrix
  7820. * @returns the current updated matrix
  7821. */
  7822. Matrix.prototype.copyFrom = function (other) {
  7823. other.copyToArray(this._m);
  7824. var o = other;
  7825. this._updateIdentityStatus(o._isIdentity, o._isIdentityDirty, o._isIdentity3x2, o._isIdentity3x2Dirty);
  7826. return this;
  7827. };
  7828. /**
  7829. * Populates the given array from the starting index with the current matrix values
  7830. * @param array defines the target array
  7831. * @param offset defines the offset in the target array where to start storing values
  7832. * @returns the current matrix
  7833. */
  7834. Matrix.prototype.copyToArray = function (array, offset) {
  7835. if (offset === void 0) { offset = 0; }
  7836. for (var index = 0; index < 16; index++) {
  7837. array[offset + index] = this._m[index];
  7838. }
  7839. return this;
  7840. };
  7841. /**
  7842. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  7843. * @param other defines the second operand
  7844. * @param result defines the matrix where to store the multiplication
  7845. * @returns the current matrix
  7846. */
  7847. Matrix.prototype.multiplyToRef = function (other, result) {
  7848. if (this._isIdentity) {
  7849. result.copyFrom(other);
  7850. return this;
  7851. }
  7852. if (other._isIdentity) {
  7853. result.copyFrom(this);
  7854. return this;
  7855. }
  7856. this.multiplyToArray(other, result._m, 0);
  7857. result._markAsUpdated();
  7858. return this;
  7859. };
  7860. /**
  7861. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  7862. * @param other defines the second operand
  7863. * @param result defines the array where to store the multiplication
  7864. * @param offset defines the offset in the target array where to start storing values
  7865. * @returns the current matrix
  7866. */
  7867. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  7868. var m = this._m;
  7869. var otherM = other.m;
  7870. var tm0 = m[0], tm1 = m[1], tm2 = m[2], tm3 = m[3];
  7871. var tm4 = m[4], tm5 = m[5], tm6 = m[6], tm7 = m[7];
  7872. var tm8 = m[8], tm9 = m[9], tm10 = m[10], tm11 = m[11];
  7873. var tm12 = m[12], tm13 = m[13], tm14 = m[14], tm15 = m[15];
  7874. var om0 = otherM[0], om1 = otherM[1], om2 = otherM[2], om3 = otherM[3];
  7875. var om4 = otherM[4], om5 = otherM[5], om6 = otherM[6], om7 = otherM[7];
  7876. var om8 = otherM[8], om9 = otherM[9], om10 = otherM[10], om11 = otherM[11];
  7877. var om12 = otherM[12], om13 = otherM[13], om14 = otherM[14], om15 = otherM[15];
  7878. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  7879. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  7880. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  7881. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  7882. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  7883. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  7884. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  7885. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  7886. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  7887. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  7888. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  7889. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  7890. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  7891. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  7892. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  7893. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  7894. return this;
  7895. };
  7896. /**
  7897. * Check equality between this matrix and a second one
  7898. * @param value defines the second matrix to compare
  7899. * @returns true is the current matrix and the given one values are strictly equal
  7900. */
  7901. Matrix.prototype.equals = function (value) {
  7902. var other = value;
  7903. if (!other) {
  7904. return false;
  7905. }
  7906. if (this._isIdentity || other._isIdentity) {
  7907. if (!this._isIdentityDirty && !other._isIdentityDirty) {
  7908. return this._isIdentity && other._isIdentity;
  7909. }
  7910. }
  7911. var m = this.m;
  7912. var om = other.m;
  7913. return (m[0] === om[0] && m[1] === om[1] && m[2] === om[2] && m[3] === om[3] &&
  7914. m[4] === om[4] && m[5] === om[5] && m[6] === om[6] && m[7] === om[7] &&
  7915. m[8] === om[8] && m[9] === om[9] && m[10] === om[10] && m[11] === om[11] &&
  7916. m[12] === om[12] && m[13] === om[13] && m[14] === om[14] && m[15] === om[15]);
  7917. };
  7918. /**
  7919. * Clone the current matrix
  7920. * @returns a new matrix from the current matrix
  7921. */
  7922. Matrix.prototype.clone = function () {
  7923. var matrix = new Matrix();
  7924. matrix.copyFrom(this);
  7925. return matrix;
  7926. };
  7927. /**
  7928. * Returns the name of the current matrix class
  7929. * @returns the string "Matrix"
  7930. */
  7931. Matrix.prototype.getClassName = function () {
  7932. return "Matrix";
  7933. };
  7934. /**
  7935. * Gets the hash code of the current matrix
  7936. * @returns the hash code
  7937. */
  7938. Matrix.prototype.getHashCode = function () {
  7939. var hash = this._m[0] || 0;
  7940. for (var i = 1; i < 16; i++) {
  7941. hash = (hash * 397) ^ (this._m[i] || 0);
  7942. }
  7943. return hash;
  7944. };
  7945. /**
  7946. * Decomposes the current Matrix into a translation, rotation and scaling components
  7947. * @param scale defines the scale vector3 given as a reference to update
  7948. * @param rotation defines the rotation quaternion given as a reference to update
  7949. * @param translation defines the translation vector3 given as a reference to update
  7950. * @returns true if operation was successful
  7951. */
  7952. Matrix.prototype.decompose = function (scale, rotation, translation) {
  7953. if (this._isIdentity) {
  7954. if (translation) {
  7955. translation.setAll(0);
  7956. }
  7957. if (scale) {
  7958. scale.setAll(1);
  7959. }
  7960. if (rotation) {
  7961. rotation.copyFromFloats(0, 0, 0, 1);
  7962. }
  7963. return true;
  7964. }
  7965. var m = this._m;
  7966. if (translation) {
  7967. translation.copyFromFloats(m[12], m[13], m[14]);
  7968. }
  7969. scale = scale || MathTmp.Vector3[0];
  7970. scale.x = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  7971. scale.y = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  7972. scale.z = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  7973. if (this.determinant() <= 0) {
  7974. scale.y *= -1;
  7975. }
  7976. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  7977. if (rotation) {
  7978. rotation.copyFromFloats(0.0, 0.0, 0.0, 1.0);
  7979. }
  7980. return false;
  7981. }
  7982. if (rotation) {
  7983. var sx = 1 / scale.x, sy = 1 / scale.y, sz = 1 / scale.z;
  7984. Matrix.FromValuesToRef(m[0] * sx, m[1] * sx, m[2] * sx, 0.0, m[4] * sy, m[5] * sy, m[6] * sy, 0.0, m[8] * sz, m[9] * sz, m[10] * sz, 0.0, 0.0, 0.0, 0.0, 1.0, MathTmp.Matrix[0]);
  7985. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  7986. }
  7987. return true;
  7988. };
  7989. /**
  7990. * Gets specific row of the matrix
  7991. * @param index defines the number of the row to get
  7992. * @returns the index-th row of the current matrix as a new Vector4
  7993. */
  7994. Matrix.prototype.getRow = function (index) {
  7995. if (index < 0 || index > 3) {
  7996. return null;
  7997. }
  7998. var i = index * 4;
  7999. return new Vector4(this._m[i + 0], this._m[i + 1], this._m[i + 2], this._m[i + 3]);
  8000. };
  8001. /**
  8002. * Sets the index-th row of the current matrix to the vector4 values
  8003. * @param index defines the number of the row to set
  8004. * @param row defines the target vector4
  8005. * @returns the updated current matrix
  8006. */
  8007. Matrix.prototype.setRow = function (index, row) {
  8008. return this.setRowFromFloats(index, row.x, row.y, row.z, row.w);
  8009. };
  8010. /**
  8011. * Compute the transpose of the matrix
  8012. * @returns the new transposed matrix
  8013. */
  8014. Matrix.prototype.transpose = function () {
  8015. return Matrix.Transpose(this);
  8016. };
  8017. /**
  8018. * Compute the transpose of the matrix and store it in a given matrix
  8019. * @param result defines the target matrix
  8020. * @returns the current matrix
  8021. */
  8022. Matrix.prototype.transposeToRef = function (result) {
  8023. Matrix.TransposeToRef(this, result);
  8024. return this;
  8025. };
  8026. /**
  8027. * Sets the index-th row of the current matrix with the given 4 x float values
  8028. * @param index defines the row index
  8029. * @param x defines the x component to set
  8030. * @param y defines the y component to set
  8031. * @param z defines the z component to set
  8032. * @param w defines the w component to set
  8033. * @returns the updated current matrix
  8034. */
  8035. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  8036. if (index < 0 || index > 3) {
  8037. return this;
  8038. }
  8039. var i = index * 4;
  8040. this._m[i + 0] = x;
  8041. this._m[i + 1] = y;
  8042. this._m[i + 2] = z;
  8043. this._m[i + 3] = w;
  8044. this._markAsUpdated();
  8045. return this;
  8046. };
  8047. /**
  8048. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  8049. * @param scale defines the scale factor
  8050. * @returns a new matrix
  8051. */
  8052. Matrix.prototype.scale = function (scale) {
  8053. var result = new Matrix();
  8054. this.scaleToRef(scale, result);
  8055. return result;
  8056. };
  8057. /**
  8058. * Scale the current matrix values by a factor to a given result matrix
  8059. * @param scale defines the scale factor
  8060. * @param result defines the matrix to store the result
  8061. * @returns the current matrix
  8062. */
  8063. Matrix.prototype.scaleToRef = function (scale, result) {
  8064. for (var index = 0; index < 16; index++) {
  8065. result._m[index] = this._m[index] * scale;
  8066. }
  8067. result._markAsUpdated();
  8068. return this;
  8069. };
  8070. /**
  8071. * Scale the current matrix values by a factor and add the result to a given matrix
  8072. * @param scale defines the scale factor
  8073. * @param result defines the Matrix to store the result
  8074. * @returns the current matrix
  8075. */
  8076. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  8077. for (var index = 0; index < 16; index++) {
  8078. result._m[index] += this._m[index] * scale;
  8079. }
  8080. result._markAsUpdated();
  8081. return this;
  8082. };
  8083. /**
  8084. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  8085. * @param ref matrix to store the result
  8086. */
  8087. Matrix.prototype.toNormalMatrix = function (ref) {
  8088. var tmp = MathTmp.Matrix[0];
  8089. this.invertToRef(tmp);
  8090. tmp.transposeToRef(ref);
  8091. var m = ref._m;
  8092. Matrix.FromValuesToRef(m[0], m[1], m[2], 0.0, m[4], m[5], m[6], 0.0, m[8], m[9], m[10], 0.0, 0.0, 0.0, 0.0, 1.0, ref);
  8093. };
  8094. /**
  8095. * Gets only rotation part of the current matrix
  8096. * @returns a new matrix sets to the extracted rotation matrix from the current one
  8097. */
  8098. Matrix.prototype.getRotationMatrix = function () {
  8099. var result = new Matrix();
  8100. this.getRotationMatrixToRef(result);
  8101. return result;
  8102. };
  8103. /**
  8104. * Extracts the rotation matrix from the current one and sets it as the given "result"
  8105. * @param result defines the target matrix to store data to
  8106. * @returns the current matrix
  8107. */
  8108. Matrix.prototype.getRotationMatrixToRef = function (result) {
  8109. var scale = MathTmp.Vector3[0];
  8110. if (!this.decompose(scale)) {
  8111. Matrix.IdentityToRef(result);
  8112. return this;
  8113. }
  8114. var m = this._m;
  8115. var sx = 1 / scale.x, sy = 1 / scale.y, sz = 1 / scale.z;
  8116. Matrix.FromValuesToRef(m[0] * sx, m[1] * sx, m[2] * sx, 0.0, m[4] * sy, m[5] * sy, m[6] * sy, 0.0, m[8] * sz, m[9] * sz, m[10] * sz, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  8117. return this;
  8118. };
  8119. /**
  8120. * Toggles model matrix from being right handed to left handed in place and vice versa
  8121. */
  8122. Matrix.prototype.toggleModelMatrixHandInPlace = function () {
  8123. var m = this._m;
  8124. m[2] *= -1;
  8125. m[6] *= -1;
  8126. m[8] *= -1;
  8127. m[9] *= -1;
  8128. m[14] *= -1;
  8129. this._markAsUpdated();
  8130. };
  8131. /**
  8132. * Toggles projection matrix from being right handed to left handed in place and vice versa
  8133. */
  8134. Matrix.prototype.toggleProjectionMatrixHandInPlace = function () {
  8135. var m = this._m;
  8136. m[8] *= -1;
  8137. m[9] *= -1;
  8138. m[10] *= -1;
  8139. m[11] *= -1;
  8140. this._markAsUpdated();
  8141. };
  8142. // Statics
  8143. /**
  8144. * Creates a matrix from an array
  8145. * @param array defines the source array
  8146. * @param offset defines an offset in the source array
  8147. * @returns a new Matrix set from the starting index of the given array
  8148. */
  8149. Matrix.FromArray = function (array, offset) {
  8150. if (offset === void 0) { offset = 0; }
  8151. var result = new Matrix();
  8152. Matrix.FromArrayToRef(array, offset, result);
  8153. return result;
  8154. };
  8155. /**
  8156. * Copy the content of an array into a given matrix
  8157. * @param array defines the source array
  8158. * @param offset defines an offset in the source array
  8159. * @param result defines the target matrix
  8160. */
  8161. Matrix.FromArrayToRef = function (array, offset, result) {
  8162. for (var index = 0; index < 16; index++) {
  8163. result._m[index] = array[index + offset];
  8164. }
  8165. result._markAsUpdated();
  8166. };
  8167. /**
  8168. * Stores an array into a matrix after having multiplied each component by a given factor
  8169. * @param array defines the source array
  8170. * @param offset defines the offset in the source array
  8171. * @param scale defines the scaling factor
  8172. * @param result defines the target matrix
  8173. */
  8174. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  8175. for (var index = 0; index < 16; index++) {
  8176. result._m[index] = array[index + offset] * scale;
  8177. }
  8178. result._markAsUpdated();
  8179. };
  8180. Object.defineProperty(Matrix, "IdentityReadOnly", {
  8181. /**
  8182. * Gets an identity matrix that must not be updated
  8183. */
  8184. get: function () {
  8185. return Matrix._identityReadOnly;
  8186. },
  8187. enumerable: true,
  8188. configurable: true
  8189. });
  8190. /**
  8191. * Stores a list of values (16) inside a given matrix
  8192. * @param initialM11 defines 1st value of 1st row
  8193. * @param initialM12 defines 2nd value of 1st row
  8194. * @param initialM13 defines 3rd value of 1st row
  8195. * @param initialM14 defines 4th value of 1st row
  8196. * @param initialM21 defines 1st value of 2nd row
  8197. * @param initialM22 defines 2nd value of 2nd row
  8198. * @param initialM23 defines 3rd value of 2nd row
  8199. * @param initialM24 defines 4th value of 2nd row
  8200. * @param initialM31 defines 1st value of 3rd row
  8201. * @param initialM32 defines 2nd value of 3rd row
  8202. * @param initialM33 defines 3rd value of 3rd row
  8203. * @param initialM34 defines 4th value of 3rd row
  8204. * @param initialM41 defines 1st value of 4th row
  8205. * @param initialM42 defines 2nd value of 4th row
  8206. * @param initialM43 defines 3rd value of 4th row
  8207. * @param initialM44 defines 4th value of 4th row
  8208. * @param result defines the target matrix
  8209. */
  8210. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  8211. var m = result._m;
  8212. m[0] = initialM11;
  8213. m[1] = initialM12;
  8214. m[2] = initialM13;
  8215. m[3] = initialM14;
  8216. m[4] = initialM21;
  8217. m[5] = initialM22;
  8218. m[6] = initialM23;
  8219. m[7] = initialM24;
  8220. m[8] = initialM31;
  8221. m[9] = initialM32;
  8222. m[10] = initialM33;
  8223. m[11] = initialM34;
  8224. m[12] = initialM41;
  8225. m[13] = initialM42;
  8226. m[14] = initialM43;
  8227. m[15] = initialM44;
  8228. result._markAsUpdated();
  8229. };
  8230. /**
  8231. * Creates new matrix from a list of values (16)
  8232. * @param initialM11 defines 1st value of 1st row
  8233. * @param initialM12 defines 2nd value of 1st row
  8234. * @param initialM13 defines 3rd value of 1st row
  8235. * @param initialM14 defines 4th value of 1st row
  8236. * @param initialM21 defines 1st value of 2nd row
  8237. * @param initialM22 defines 2nd value of 2nd row
  8238. * @param initialM23 defines 3rd value of 2nd row
  8239. * @param initialM24 defines 4th value of 2nd row
  8240. * @param initialM31 defines 1st value of 3rd row
  8241. * @param initialM32 defines 2nd value of 3rd row
  8242. * @param initialM33 defines 3rd value of 3rd row
  8243. * @param initialM34 defines 4th value of 3rd row
  8244. * @param initialM41 defines 1st value of 4th row
  8245. * @param initialM42 defines 2nd value of 4th row
  8246. * @param initialM43 defines 3rd value of 4th row
  8247. * @param initialM44 defines 4th value of 4th row
  8248. * @returns the new matrix
  8249. */
  8250. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  8251. var result = new Matrix();
  8252. var m = result._m;
  8253. m[0] = initialM11;
  8254. m[1] = initialM12;
  8255. m[2] = initialM13;
  8256. m[3] = initialM14;
  8257. m[4] = initialM21;
  8258. m[5] = initialM22;
  8259. m[6] = initialM23;
  8260. m[7] = initialM24;
  8261. m[8] = initialM31;
  8262. m[9] = initialM32;
  8263. m[10] = initialM33;
  8264. m[11] = initialM34;
  8265. m[12] = initialM41;
  8266. m[13] = initialM42;
  8267. m[14] = initialM43;
  8268. m[15] = initialM44;
  8269. result._markAsUpdated();
  8270. return result;
  8271. };
  8272. /**
  8273. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  8274. * @param scale defines the scale vector3
  8275. * @param rotation defines the rotation quaternion
  8276. * @param translation defines the translation vector3
  8277. * @returns a new matrix
  8278. */
  8279. Matrix.Compose = function (scale, rotation, translation) {
  8280. var result = new Matrix();
  8281. Matrix.ComposeToRef(scale, rotation, translation, result);
  8282. return result;
  8283. };
  8284. /**
  8285. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  8286. * @param scale defines the scale vector3
  8287. * @param rotation defines the rotation quaternion
  8288. * @param translation defines the translation vector3
  8289. * @param result defines the target matrix
  8290. */
  8291. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  8292. Matrix.ScalingToRef(scale.x, scale.y, scale.z, MathTmp.Matrix[1]);
  8293. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  8294. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  8295. result.setTranslation(translation);
  8296. };
  8297. /**
  8298. * Creates a new identity matrix
  8299. * @returns a new identity matrix
  8300. */
  8301. Matrix.Identity = function () {
  8302. var identity = 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);
  8303. identity._updateIdentityStatus(true);
  8304. return identity;
  8305. };
  8306. /**
  8307. * Creates a new identity matrix and stores the result in a given matrix
  8308. * @param result defines the target matrix
  8309. */
  8310. Matrix.IdentityToRef = function (result) {
  8311. 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);
  8312. result._updateIdentityStatus(true);
  8313. };
  8314. /**
  8315. * Creates a new zero matrix
  8316. * @returns a new zero matrix
  8317. */
  8318. Matrix.Zero = function () {
  8319. var zero = 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);
  8320. zero._updateIdentityStatus(false);
  8321. return zero;
  8322. };
  8323. /**
  8324. * Creates a new rotation matrix for "angle" radians around the X axis
  8325. * @param angle defines the angle (in radians) to use
  8326. * @return the new matrix
  8327. */
  8328. Matrix.RotationX = function (angle) {
  8329. var result = new Matrix();
  8330. Matrix.RotationXToRef(angle, result);
  8331. return result;
  8332. };
  8333. /**
  8334. * Creates a new matrix as the invert of a given matrix
  8335. * @param source defines the source matrix
  8336. * @returns the new matrix
  8337. */
  8338. Matrix.Invert = function (source) {
  8339. var result = new Matrix();
  8340. source.invertToRef(result);
  8341. return result;
  8342. };
  8343. /**
  8344. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  8345. * @param angle defines the angle (in radians) to use
  8346. * @param result defines the target matrix
  8347. */
  8348. Matrix.RotationXToRef = function (angle, result) {
  8349. var s = Math.sin(angle);
  8350. var c = Math.cos(angle);
  8351. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  8352. result._updateIdentityStatus(c === 1 && s === 0);
  8353. };
  8354. /**
  8355. * Creates a new rotation matrix for "angle" radians around the Y axis
  8356. * @param angle defines the angle (in radians) to use
  8357. * @return the new matrix
  8358. */
  8359. Matrix.RotationY = function (angle) {
  8360. var result = new Matrix();
  8361. Matrix.RotationYToRef(angle, result);
  8362. return result;
  8363. };
  8364. /**
  8365. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  8366. * @param angle defines the angle (in radians) to use
  8367. * @param result defines the target matrix
  8368. */
  8369. Matrix.RotationYToRef = function (angle, result) {
  8370. var s = Math.sin(angle);
  8371. var c = Math.cos(angle);
  8372. Matrix.FromValuesToRef(c, 0.0, -s, 0.0, 0.0, 1.0, 0.0, 0.0, s, 0.0, c, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  8373. result._updateIdentityStatus(c === 1 && s === 0);
  8374. };
  8375. /**
  8376. * Creates a new rotation matrix for "angle" radians around the Z axis
  8377. * @param angle defines the angle (in radians) to use
  8378. * @return the new matrix
  8379. */
  8380. Matrix.RotationZ = function (angle) {
  8381. var result = new Matrix();
  8382. Matrix.RotationZToRef(angle, result);
  8383. return result;
  8384. };
  8385. /**
  8386. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  8387. * @param angle defines the angle (in radians) to use
  8388. * @param result defines the target matrix
  8389. */
  8390. Matrix.RotationZToRef = function (angle, result) {
  8391. var s = Math.sin(angle);
  8392. var c = Math.cos(angle);
  8393. Matrix.FromValuesToRef(c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  8394. result._updateIdentityStatus(c === 1 && s === 0);
  8395. };
  8396. /**
  8397. * Creates a new rotation matrix for "angle" radians around the given axis
  8398. * @param axis defines the axis to use
  8399. * @param angle defines the angle (in radians) to use
  8400. * @return the new matrix
  8401. */
  8402. Matrix.RotationAxis = function (axis, angle) {
  8403. var result = new Matrix();
  8404. Matrix.RotationAxisToRef(axis, angle, result);
  8405. return result;
  8406. };
  8407. /**
  8408. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  8409. * @param axis defines the axis to use
  8410. * @param angle defines the angle (in radians) to use
  8411. * @param result defines the target matrix
  8412. */
  8413. Matrix.RotationAxisToRef = function (axis, angle, result) {
  8414. var s = Math.sin(-angle);
  8415. var c = Math.cos(-angle);
  8416. var c1 = 1 - c;
  8417. axis.normalize();
  8418. var m = result._m;
  8419. m[0] = (axis.x * axis.x) * c1 + c;
  8420. m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  8421. m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  8422. m[3] = 0.0;
  8423. m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  8424. m[5] = (axis.y * axis.y) * c1 + c;
  8425. m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  8426. m[7] = 0.0;
  8427. m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  8428. m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  8429. m[10] = (axis.z * axis.z) * c1 + c;
  8430. m[11] = 0.0;
  8431. m[12] = 0.0;
  8432. m[13] = 0.0;
  8433. m[14] = 0.0;
  8434. m[15] = 1.0;
  8435. result._markAsUpdated();
  8436. };
  8437. /**
  8438. * Creates a rotation matrix
  8439. * @param yaw defines the yaw angle in radians (Y axis)
  8440. * @param pitch defines the pitch angle in radians (X axis)
  8441. * @param roll defines the roll angle in radians (X axis)
  8442. * @returns the new rotation matrix
  8443. */
  8444. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  8445. var result = new Matrix();
  8446. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  8447. return result;
  8448. };
  8449. /**
  8450. * Creates a rotation matrix and stores it in a given matrix
  8451. * @param yaw defines the yaw angle in radians (Y axis)
  8452. * @param pitch defines the pitch angle in radians (X axis)
  8453. * @param roll defines the roll angle in radians (X axis)
  8454. * @param result defines the target matrix
  8455. */
  8456. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  8457. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, MathTmp.Quaternion[0]);
  8458. MathTmp.Quaternion[0].toRotationMatrix(result);
  8459. };
  8460. /**
  8461. * Creates a scaling matrix
  8462. * @param x defines the scale factor on X axis
  8463. * @param y defines the scale factor on Y axis
  8464. * @param z defines the scale factor on Z axis
  8465. * @returns the new matrix
  8466. */
  8467. Matrix.Scaling = function (x, y, z) {
  8468. var result = new Matrix();
  8469. Matrix.ScalingToRef(x, y, z, result);
  8470. return result;
  8471. };
  8472. /**
  8473. * Creates a scaling matrix and stores it in a given matrix
  8474. * @param x defines the scale factor on X axis
  8475. * @param y defines the scale factor on Y axis
  8476. * @param z defines the scale factor on Z axis
  8477. * @param result defines the target matrix
  8478. */
  8479. Matrix.ScalingToRef = function (x, y, z, result) {
  8480. Matrix.FromValuesToRef(x, 0.0, 0.0, 0.0, 0.0, y, 0.0, 0.0, 0.0, 0.0, z, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  8481. result._updateIdentityStatus(x === 1 && y === 1 && z === 1);
  8482. };
  8483. /**
  8484. * Creates a translation matrix
  8485. * @param x defines the translation on X axis
  8486. * @param y defines the translation on Y axis
  8487. * @param z defines the translationon Z axis
  8488. * @returns the new matrix
  8489. */
  8490. Matrix.Translation = function (x, y, z) {
  8491. var result = new Matrix();
  8492. Matrix.TranslationToRef(x, y, z, result);
  8493. return result;
  8494. };
  8495. /**
  8496. * Creates a translation matrix and stores it in a given matrix
  8497. * @param x defines the translation on X axis
  8498. * @param y defines the translation on Y axis
  8499. * @param z defines the translationon Z axis
  8500. * @param result defines the target matrix
  8501. */
  8502. Matrix.TranslationToRef = function (x, y, z, result) {
  8503. 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);
  8504. result._updateIdentityStatus(x === 0 && y === 0 && z === 0);
  8505. };
  8506. /**
  8507. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  8508. * @param startValue defines the start value
  8509. * @param endValue defines the end value
  8510. * @param gradient defines the gradient factor
  8511. * @returns the new matrix
  8512. */
  8513. Matrix.Lerp = function (startValue, endValue, gradient) {
  8514. var result = new Matrix();
  8515. Matrix.LerpToRef(startValue, endValue, gradient, result);
  8516. return result;
  8517. };
  8518. /**
  8519. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  8520. * @param startValue defines the start value
  8521. * @param endValue defines the end value
  8522. * @param gradient defines the gradient factor
  8523. * @param result defines the Matrix object where to store data
  8524. */
  8525. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  8526. for (var index = 0; index < 16; index++) {
  8527. result._m[index] = startValue._m[index] * (1.0 - gradient) + endValue._m[index] * gradient;
  8528. }
  8529. result._markAsUpdated();
  8530. };
  8531. /**
  8532. * Builds a new matrix whose values are computed by:
  8533. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  8534. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  8535. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  8536. * @param startValue defines the first matrix
  8537. * @param endValue defines the second matrix
  8538. * @param gradient defines the gradient between the two matrices
  8539. * @returns the new matrix
  8540. */
  8541. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  8542. var result = new Matrix();
  8543. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  8544. return result;
  8545. };
  8546. /**
  8547. * Update a matrix to values which are computed by:
  8548. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  8549. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  8550. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  8551. * @param startValue defines the first matrix
  8552. * @param endValue defines the second matrix
  8553. * @param gradient defines the gradient between the two matrices
  8554. * @param result defines the target matrix
  8555. */
  8556. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  8557. var startScale = MathTmp.Vector3[0];
  8558. var startRotation = MathTmp.Quaternion[0];
  8559. var startTranslation = MathTmp.Vector3[1];
  8560. startValue.decompose(startScale, startRotation, startTranslation);
  8561. var endScale = MathTmp.Vector3[2];
  8562. var endRotation = MathTmp.Quaternion[1];
  8563. var endTranslation = MathTmp.Vector3[3];
  8564. endValue.decompose(endScale, endRotation, endTranslation);
  8565. var resultScale = MathTmp.Vector3[4];
  8566. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  8567. var resultRotation = MathTmp.Quaternion[2];
  8568. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  8569. var resultTranslation = MathTmp.Vector3[5];
  8570. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  8571. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  8572. };
  8573. /**
  8574. * 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"
  8575. * This function works in left handed mode
  8576. * @param eye defines the final position of the entity
  8577. * @param target defines where the entity should look at
  8578. * @param up defines the up vector for the entity
  8579. * @returns the new matrix
  8580. */
  8581. Matrix.LookAtLH = function (eye, target, up) {
  8582. var result = new Matrix();
  8583. Matrix.LookAtLHToRef(eye, target, up, result);
  8584. return result;
  8585. };
  8586. /**
  8587. * 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".
  8588. * This function works in left handed mode
  8589. * @param eye defines the final position of the entity
  8590. * @param target defines where the entity should look at
  8591. * @param up defines the up vector for the entity
  8592. * @param result defines the target matrix
  8593. */
  8594. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  8595. var xAxis = MathTmp.Vector3[0];
  8596. var yAxis = MathTmp.Vector3[1];
  8597. var zAxis = MathTmp.Vector3[2];
  8598. // Z axis
  8599. target.subtractToRef(eye, zAxis);
  8600. zAxis.normalize();
  8601. // X axis
  8602. Vector3.CrossToRef(up, zAxis, xAxis);
  8603. var xSquareLength = xAxis.lengthSquared();
  8604. if (xSquareLength === 0) {
  8605. xAxis.x = 1.0;
  8606. }
  8607. else {
  8608. xAxis.normalizeFromLength(Math.sqrt(xSquareLength));
  8609. }
  8610. // Y axis
  8611. Vector3.CrossToRef(zAxis, xAxis, yAxis);
  8612. yAxis.normalize();
  8613. // Eye angles
  8614. var ex = -Vector3.Dot(xAxis, eye);
  8615. var ey = -Vector3.Dot(yAxis, eye);
  8616. var ez = -Vector3.Dot(zAxis, eye);
  8617. Matrix.FromValuesToRef(xAxis.x, yAxis.x, zAxis.x, 0.0, xAxis.y, yAxis.y, zAxis.y, 0.0, xAxis.z, yAxis.z, zAxis.z, 0.0, ex, ey, ez, 1.0, result);
  8618. };
  8619. /**
  8620. * 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"
  8621. * This function works in right handed mode
  8622. * @param eye defines the final position of the entity
  8623. * @param target defines where the entity should look at
  8624. * @param up defines the up vector for the entity
  8625. * @returns the new matrix
  8626. */
  8627. Matrix.LookAtRH = function (eye, target, up) {
  8628. var result = new Matrix();
  8629. Matrix.LookAtRHToRef(eye, target, up, result);
  8630. return result;
  8631. };
  8632. /**
  8633. * 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".
  8634. * This function works in right handed mode
  8635. * @param eye defines the final position of the entity
  8636. * @param target defines where the entity should look at
  8637. * @param up defines the up vector for the entity
  8638. * @param result defines the target matrix
  8639. */
  8640. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  8641. var xAxis = MathTmp.Vector3[0];
  8642. var yAxis = MathTmp.Vector3[1];
  8643. var zAxis = MathTmp.Vector3[2];
  8644. // Z axis
  8645. eye.subtractToRef(target, zAxis);
  8646. zAxis.normalize();
  8647. // X axis
  8648. Vector3.CrossToRef(up, zAxis, xAxis);
  8649. var xSquareLength = xAxis.lengthSquared();
  8650. if (xSquareLength === 0) {
  8651. xAxis.x = 1.0;
  8652. }
  8653. else {
  8654. xAxis.normalizeFromLength(Math.sqrt(xSquareLength));
  8655. }
  8656. // Y axis
  8657. Vector3.CrossToRef(zAxis, xAxis, yAxis);
  8658. yAxis.normalize();
  8659. // Eye angles
  8660. var ex = -Vector3.Dot(xAxis, eye);
  8661. var ey = -Vector3.Dot(yAxis, eye);
  8662. var ez = -Vector3.Dot(zAxis, eye);
  8663. Matrix.FromValuesToRef(xAxis.x, yAxis.x, zAxis.x, 0.0, xAxis.y, yAxis.y, zAxis.y, 0.0, xAxis.z, yAxis.z, zAxis.z, 0.0, ex, ey, ez, 1.0, result);
  8664. };
  8665. /**
  8666. * Create a left-handed orthographic projection matrix
  8667. * @param width defines the viewport width
  8668. * @param height defines the viewport height
  8669. * @param znear defines the near clip plane
  8670. * @param zfar defines the far clip plane
  8671. * @returns a new matrix as a left-handed orthographic projection matrix
  8672. */
  8673. Matrix.OrthoLH = function (width, height, znear, zfar) {
  8674. var matrix = new Matrix();
  8675. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  8676. return matrix;
  8677. };
  8678. /**
  8679. * Store a left-handed orthographic projection to a given matrix
  8680. * @param width defines the viewport width
  8681. * @param height defines the viewport height
  8682. * @param znear defines the near clip plane
  8683. * @param zfar defines the far clip plane
  8684. * @param result defines the target matrix
  8685. */
  8686. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  8687. var n = znear;
  8688. var f = zfar;
  8689. var a = 2.0 / width;
  8690. var b = 2.0 / height;
  8691. var c = 2.0 / (f - n);
  8692. var d = -(f + n) / (f - n);
  8693. 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);
  8694. result._updateIdentityStatus(a === 1 && b === 1 && c === 1 && d === 0);
  8695. };
  8696. /**
  8697. * Create a left-handed orthographic projection matrix
  8698. * @param left defines the viewport left coordinate
  8699. * @param right defines the viewport right coordinate
  8700. * @param bottom defines the viewport bottom coordinate
  8701. * @param top defines the viewport top coordinate
  8702. * @param znear defines the near clip plane
  8703. * @param zfar defines the far clip plane
  8704. * @returns a new matrix as a left-handed orthographic projection matrix
  8705. */
  8706. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  8707. var matrix = new Matrix();
  8708. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  8709. return matrix;
  8710. };
  8711. /**
  8712. * Stores a left-handed orthographic projection into a given matrix
  8713. * @param left defines the viewport left coordinate
  8714. * @param right defines the viewport right coordinate
  8715. * @param bottom defines the viewport bottom coordinate
  8716. * @param top defines the viewport top coordinate
  8717. * @param znear defines the near clip plane
  8718. * @param zfar defines the far clip plane
  8719. * @param result defines the target matrix
  8720. */
  8721. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  8722. var n = znear;
  8723. var f = zfar;
  8724. var a = 2.0 / (right - left);
  8725. var b = 2.0 / (top - bottom);
  8726. var c = 2.0 / (f - n);
  8727. var d = -(f + n) / (f - n);
  8728. var i0 = (left + right) / (left - right);
  8729. var i1 = (top + bottom) / (bottom - top);
  8730. 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);
  8731. result._markAsUpdated();
  8732. };
  8733. /**
  8734. * Creates a right-handed orthographic projection matrix
  8735. * @param left defines the viewport left coordinate
  8736. * @param right defines the viewport right coordinate
  8737. * @param bottom defines the viewport bottom coordinate
  8738. * @param top defines the viewport top coordinate
  8739. * @param znear defines the near clip plane
  8740. * @param zfar defines the far clip plane
  8741. * @returns a new matrix as a right-handed orthographic projection matrix
  8742. */
  8743. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  8744. var matrix = new Matrix();
  8745. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  8746. return matrix;
  8747. };
  8748. /**
  8749. * Stores a right-handed orthographic projection into a given matrix
  8750. * @param left defines the viewport left coordinate
  8751. * @param right defines the viewport right coordinate
  8752. * @param bottom defines the viewport bottom coordinate
  8753. * @param top defines the viewport top coordinate
  8754. * @param znear defines the near clip plane
  8755. * @param zfar defines the far clip plane
  8756. * @param result defines the target matrix
  8757. */
  8758. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  8759. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  8760. result._m[10] *= -1; // No need to call _markAsUpdated as previous function already called it and let _isIdentityDirty to true
  8761. };
  8762. /**
  8763. * Creates a left-handed perspective projection matrix
  8764. * @param width defines the viewport width
  8765. * @param height defines the viewport height
  8766. * @param znear defines the near clip plane
  8767. * @param zfar defines the far clip plane
  8768. * @returns a new matrix as a left-handed perspective projection matrix
  8769. */
  8770. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  8771. var matrix = new Matrix();
  8772. var n = znear;
  8773. var f = zfar;
  8774. var a = 2.0 * n / width;
  8775. var b = 2.0 * n / height;
  8776. var c = (f + n) / (f - n);
  8777. var d = -2.0 * f * n / (f - n);
  8778. 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);
  8779. matrix._updateIdentityStatus(false);
  8780. return matrix;
  8781. };
  8782. /**
  8783. * Creates a left-handed perspective projection matrix
  8784. * @param fov defines the horizontal field of view
  8785. * @param aspect defines the aspect ratio
  8786. * @param znear defines the near clip plane
  8787. * @param zfar defines the far clip plane
  8788. * @returns a new matrix as a left-handed perspective projection matrix
  8789. */
  8790. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  8791. var matrix = new Matrix();
  8792. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  8793. return matrix;
  8794. };
  8795. /**
  8796. * Stores a left-handed perspective projection into a given matrix
  8797. * @param fov defines the horizontal field of view
  8798. * @param aspect defines the aspect ratio
  8799. * @param znear defines the near clip plane
  8800. * @param zfar defines the far clip plane
  8801. * @param result defines the target matrix
  8802. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  8803. */
  8804. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  8805. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  8806. var n = znear;
  8807. var f = zfar;
  8808. var t = 1.0 / (Math.tan(fov * 0.5));
  8809. var a = isVerticalFovFixed ? (t / aspect) : t;
  8810. var b = isVerticalFovFixed ? t : (t * aspect);
  8811. var c = (f + n) / (f - n);
  8812. var d = -2.0 * f * n / (f - n);
  8813. 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);
  8814. result._updateIdentityStatus(false);
  8815. };
  8816. /**
  8817. * Creates a right-handed perspective projection matrix
  8818. * @param fov defines the horizontal field of view
  8819. * @param aspect defines the aspect ratio
  8820. * @param znear defines the near clip plane
  8821. * @param zfar defines the far clip plane
  8822. * @returns a new matrix as a right-handed perspective projection matrix
  8823. */
  8824. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  8825. var matrix = new Matrix();
  8826. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  8827. return matrix;
  8828. };
  8829. /**
  8830. * Stores a right-handed perspective projection into a given matrix
  8831. * @param fov defines the horizontal field of view
  8832. * @param aspect defines the aspect ratio
  8833. * @param znear defines the near clip plane
  8834. * @param zfar defines the far clip plane
  8835. * @param result defines the target matrix
  8836. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  8837. */
  8838. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  8839. //alternatively this could be expressed as:
  8840. // m = PerspectiveFovLHToRef
  8841. // m[10] *= -1.0;
  8842. // m[11] *= -1.0;
  8843. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  8844. var n = znear;
  8845. var f = zfar;
  8846. var t = 1.0 / (Math.tan(fov * 0.5));
  8847. var a = isVerticalFovFixed ? (t / aspect) : t;
  8848. var b = isVerticalFovFixed ? t : (t * aspect);
  8849. var c = -(f + n) / (f - n);
  8850. var d = -2 * f * n / (f - n);
  8851. 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);
  8852. result._updateIdentityStatus(false);
  8853. };
  8854. /**
  8855. * Stores a perspective projection for WebVR info a given matrix
  8856. * @param fov defines the field of view
  8857. * @param znear defines the near clip plane
  8858. * @param zfar defines the far clip plane
  8859. * @param result defines the target matrix
  8860. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  8861. */
  8862. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  8863. if (rightHanded === void 0) { rightHanded = false; }
  8864. var rightHandedFactor = rightHanded ? -1 : 1;
  8865. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  8866. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  8867. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  8868. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  8869. var xScale = 2.0 / (leftTan + rightTan);
  8870. var yScale = 2.0 / (upTan + downTan);
  8871. var m = result._m;
  8872. m[0] = xScale;
  8873. m[1] = m[2] = m[3] = m[4] = 0.0;
  8874. m[5] = yScale;
  8875. m[6] = m[7] = 0.0;
  8876. m[8] = ((leftTan - rightTan) * xScale * 0.5);
  8877. m[9] = -((upTan - downTan) * yScale * 0.5);
  8878. m[10] = -zfar / (znear - zfar);
  8879. m[11] = 1.0 * rightHandedFactor;
  8880. m[12] = m[13] = m[15] = 0.0;
  8881. m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  8882. result._markAsUpdated();
  8883. };
  8884. /**
  8885. * Computes a complete transformation matrix
  8886. * @param viewport defines the viewport to use
  8887. * @param world defines the world matrix
  8888. * @param view defines the view matrix
  8889. * @param projection defines the projection matrix
  8890. * @param zmin defines the near clip plane
  8891. * @param zmax defines the far clip plane
  8892. * @returns the transformation matrix
  8893. */
  8894. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  8895. var cw = viewport.width;
  8896. var ch = viewport.height;
  8897. var cx = viewport.x;
  8898. var cy = viewport.y;
  8899. 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.0);
  8900. var matrix = MathTmp.Matrix[0];
  8901. world.multiplyToRef(view, matrix);
  8902. matrix.multiplyToRef(projection, matrix);
  8903. return matrix.multiply(viewportMatrix);
  8904. };
  8905. /**
  8906. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  8907. * @param matrix defines the matrix to use
  8908. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  8909. */
  8910. Matrix.GetAsMatrix2x2 = function (matrix) {
  8911. return new Float32Array([
  8912. matrix._m[0], matrix._m[1],
  8913. matrix._m[4], matrix._m[5]
  8914. ]);
  8915. };
  8916. /**
  8917. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  8918. * @param matrix defines the matrix to use
  8919. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  8920. */
  8921. Matrix.GetAsMatrix3x3 = function (matrix) {
  8922. return new Float32Array([
  8923. matrix._m[0], matrix._m[1], matrix._m[2],
  8924. matrix._m[4], matrix._m[5], matrix._m[6],
  8925. matrix._m[8], matrix._m[9], matrix._m[10]
  8926. ]);
  8927. };
  8928. /**
  8929. * Compute the transpose of a given matrix
  8930. * @param matrix defines the matrix to transpose
  8931. * @returns the new matrix
  8932. */
  8933. Matrix.Transpose = function (matrix) {
  8934. var result = new Matrix();
  8935. Matrix.TransposeToRef(matrix, result);
  8936. return result;
  8937. };
  8938. /**
  8939. * Compute the transpose of a matrix and store it in a target matrix
  8940. * @param matrix defines the matrix to transpose
  8941. * @param result defines the target matrix
  8942. */
  8943. Matrix.TransposeToRef = function (matrix, result) {
  8944. var rm = result._m;
  8945. var mm = matrix._m;
  8946. rm[0] = mm[0];
  8947. rm[1] = mm[4];
  8948. rm[2] = mm[8];
  8949. rm[3] = mm[12];
  8950. rm[4] = mm[1];
  8951. rm[5] = mm[5];
  8952. rm[6] = mm[9];
  8953. rm[7] = mm[13];
  8954. rm[8] = mm[2];
  8955. rm[9] = mm[6];
  8956. rm[10] = mm[10];
  8957. rm[11] = mm[14];
  8958. rm[12] = mm[3];
  8959. rm[13] = mm[7];
  8960. rm[14] = mm[11];
  8961. rm[15] = mm[15];
  8962. // identity-ness does not change when transposing
  8963. result._updateIdentityStatus(matrix._isIdentity, matrix._isIdentityDirty);
  8964. };
  8965. /**
  8966. * Computes a reflection matrix from a plane
  8967. * @param plane defines the reflection plane
  8968. * @returns a new matrix
  8969. */
  8970. Matrix.Reflection = function (plane) {
  8971. var matrix = new Matrix();
  8972. Matrix.ReflectionToRef(plane, matrix);
  8973. return matrix;
  8974. };
  8975. /**
  8976. * Computes a reflection matrix from a plane
  8977. * @param plane defines the reflection plane
  8978. * @param result defines the target matrix
  8979. */
  8980. Matrix.ReflectionToRef = function (plane, result) {
  8981. plane.normalize();
  8982. var x = plane.normal.x;
  8983. var y = plane.normal.y;
  8984. var z = plane.normal.z;
  8985. var temp = -2 * x;
  8986. var temp2 = -2 * y;
  8987. var temp3 = -2 * z;
  8988. Matrix.FromValuesToRef(temp * x + 1, temp2 * x, temp3 * x, 0.0, temp * y, temp2 * y + 1, temp3 * y, 0.0, temp * z, temp2 * z, temp3 * z + 1, 0.0, temp * plane.d, temp2 * plane.d, temp3 * plane.d, 1.0, result);
  8989. };
  8990. /**
  8991. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  8992. * @param xaxis defines the value of the 1st axis
  8993. * @param yaxis defines the value of the 2nd axis
  8994. * @param zaxis defines the value of the 3rd axis
  8995. * @param result defines the target matrix
  8996. */
  8997. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  8998. Matrix.FromValuesToRef(xaxis.x, xaxis.y, xaxis.z, 0.0, yaxis.x, yaxis.y, yaxis.z, 0.0, zaxis.x, zaxis.y, zaxis.z, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  8999. };
  9000. /**
  9001. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  9002. * @param quat defines the quaternion to use
  9003. * @param result defines the target matrix
  9004. */
  9005. Matrix.FromQuaternionToRef = function (quat, result) {
  9006. var xx = quat.x * quat.x;
  9007. var yy = quat.y * quat.y;
  9008. var zz = quat.z * quat.z;
  9009. var xy = quat.x * quat.y;
  9010. var zw = quat.z * quat.w;
  9011. var zx = quat.z * quat.x;
  9012. var yw = quat.y * quat.w;
  9013. var yz = quat.y * quat.z;
  9014. var xw = quat.x * quat.w;
  9015. result._m[0] = 1.0 - (2.0 * (yy + zz));
  9016. result._m[1] = 2.0 * (xy + zw);
  9017. result._m[2] = 2.0 * (zx - yw);
  9018. result._m[3] = 0.0;
  9019. result._m[4] = 2.0 * (xy - zw);
  9020. result._m[5] = 1.0 - (2.0 * (zz + xx));
  9021. result._m[6] = 2.0 * (yz + xw);
  9022. result._m[7] = 0.0;
  9023. result._m[8] = 2.0 * (zx + yw);
  9024. result._m[9] = 2.0 * (yz - xw);
  9025. result._m[10] = 1.0 - (2.0 * (yy + xx));
  9026. result._m[11] = 0.0;
  9027. result._m[12] = 0.0;
  9028. result._m[13] = 0.0;
  9029. result._m[14] = 0.0;
  9030. result._m[15] = 1.0;
  9031. result._markAsUpdated();
  9032. };
  9033. Matrix._updateFlagSeed = 0;
  9034. Matrix._identityReadOnly = Matrix.Identity();
  9035. return Matrix;
  9036. }());
  9037. BABYLON.Matrix = Matrix;
  9038. /**
  9039. * Represens a plane by the equation ax + by + cz + d = 0
  9040. */
  9041. var Plane = /** @class */ (function () {
  9042. /**
  9043. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  9044. * @param a a component of the plane
  9045. * @param b b component of the plane
  9046. * @param c c component of the plane
  9047. * @param d d component of the plane
  9048. */
  9049. function Plane(a, b, c, d) {
  9050. this.normal = new Vector3(a, b, c);
  9051. this.d = d;
  9052. }
  9053. /**
  9054. * @returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  9055. */
  9056. Plane.prototype.asArray = function () {
  9057. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  9058. };
  9059. // Methods
  9060. /**
  9061. * @returns a new plane copied from the current Plane.
  9062. */
  9063. Plane.prototype.clone = function () {
  9064. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  9065. };
  9066. /**
  9067. * @returns the string "Plane".
  9068. */
  9069. Plane.prototype.getClassName = function () {
  9070. return "Plane";
  9071. };
  9072. /**
  9073. * @returns the Plane hash code.
  9074. */
  9075. Plane.prototype.getHashCode = function () {
  9076. var hash = this.normal.getHashCode();
  9077. hash = (hash * 397) ^ (this.d || 0);
  9078. return hash;
  9079. };
  9080. /**
  9081. * Normalize the current Plane in place.
  9082. * @returns the updated Plane.
  9083. */
  9084. Plane.prototype.normalize = function () {
  9085. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  9086. var magnitude = 0.0;
  9087. if (norm !== 0) {
  9088. magnitude = 1.0 / norm;
  9089. }
  9090. this.normal.x *= magnitude;
  9091. this.normal.y *= magnitude;
  9092. this.normal.z *= magnitude;
  9093. this.d *= magnitude;
  9094. return this;
  9095. };
  9096. /**
  9097. * Applies a transformation the plane and returns the result
  9098. * @param transformation the transformation matrix to be applied to the plane
  9099. * @returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  9100. */
  9101. Plane.prototype.transform = function (transformation) {
  9102. var transposedMatrix = MathTmp.Matrix[0];
  9103. Matrix.TransposeToRef(transformation, transposedMatrix);
  9104. var m = transposedMatrix.m;
  9105. var x = this.normal.x;
  9106. var y = this.normal.y;
  9107. var z = this.normal.z;
  9108. var d = this.d;
  9109. var normalX = x * m[0] + y * m[1] + z * m[2] + d * m[3];
  9110. var normalY = x * m[4] + y * m[5] + z * m[6] + d * m[7];
  9111. var normalZ = x * m[8] + y * m[9] + z * m[10] + d * m[11];
  9112. var finalD = x * m[12] + y * m[13] + z * m[14] + d * m[15];
  9113. return new Plane(normalX, normalY, normalZ, finalD);
  9114. };
  9115. /**
  9116. * Calcualtte the dot product between the point and the plane normal
  9117. * @param point point to calculate the dot product with
  9118. * @returns the dot product (float) of the point coordinates and the plane normal.
  9119. */
  9120. Plane.prototype.dotCoordinate = function (point) {
  9121. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  9122. };
  9123. /**
  9124. * Updates the current Plane from the plane defined by the three given points.
  9125. * @param point1 one of the points used to contruct the plane
  9126. * @param point2 one of the points used to contruct the plane
  9127. * @param point3 one of the points used to contruct the plane
  9128. * @returns the updated Plane.
  9129. */
  9130. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  9131. var x1 = point2.x - point1.x;
  9132. var y1 = point2.y - point1.y;
  9133. var z1 = point2.z - point1.z;
  9134. var x2 = point3.x - point1.x;
  9135. var y2 = point3.y - point1.y;
  9136. var z2 = point3.z - point1.z;
  9137. var yz = (y1 * z2) - (z1 * y2);
  9138. var xz = (z1 * x2) - (x1 * z2);
  9139. var xy = (x1 * y2) - (y1 * x2);
  9140. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  9141. var invPyth;
  9142. if (pyth !== 0) {
  9143. invPyth = 1.0 / pyth;
  9144. }
  9145. else {
  9146. invPyth = 0.0;
  9147. }
  9148. this.normal.x = yz * invPyth;
  9149. this.normal.y = xz * invPyth;
  9150. this.normal.z = xy * invPyth;
  9151. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  9152. return this;
  9153. };
  9154. /**
  9155. * Checks if the plane is facing a given direction
  9156. * @param direction the direction to check if the plane is facing
  9157. * @param epsilon value the dot product is compared against (returns true if dot <= epsilon)
  9158. * @returns True is the vector "direction" is the same side than the plane normal.
  9159. */
  9160. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  9161. var dot = Vector3.Dot(this.normal, direction);
  9162. return (dot <= epsilon);
  9163. };
  9164. /**
  9165. * Calculates the distance to a point
  9166. * @param point point to calculate distance to
  9167. * @returns the signed distance (float) from the given point to the Plane.
  9168. */
  9169. Plane.prototype.signedDistanceTo = function (point) {
  9170. return Vector3.Dot(point, this.normal) + this.d;
  9171. };
  9172. // Statics
  9173. /**
  9174. * Creates a plane from an array
  9175. * @param array the array to create a plane from
  9176. * @returns a new Plane from the given array.
  9177. */
  9178. Plane.FromArray = function (array) {
  9179. return new Plane(array[0], array[1], array[2], array[3]);
  9180. };
  9181. /**
  9182. * Creates a plane from three points
  9183. * @param point1 point used to create the plane
  9184. * @param point2 point used to create the plane
  9185. * @param point3 point used to create the plane
  9186. * @returns a new Plane defined by the three given points.
  9187. */
  9188. Plane.FromPoints = function (point1, point2, point3) {
  9189. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  9190. result.copyFromPoints(point1, point2, point3);
  9191. return result;
  9192. };
  9193. /**
  9194. * Creates a plane from an origin point and a normal
  9195. * @param origin origin of the plane to be constructed
  9196. * @param normal normal of the plane to be constructed
  9197. * @returns a new Plane the normal vector to this plane at the given origin point.
  9198. * Note : the vector "normal" is updated because normalized.
  9199. */
  9200. Plane.FromPositionAndNormal = function (origin, normal) {
  9201. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  9202. normal.normalize();
  9203. result.normal = normal;
  9204. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  9205. return result;
  9206. };
  9207. /**
  9208. * Calculates the distance from a plane and a point
  9209. * @param origin origin of the plane to be constructed
  9210. * @param normal normal of the plane to be constructed
  9211. * @param point point to calculate distance to
  9212. * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  9213. */
  9214. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  9215. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  9216. return Vector3.Dot(point, normal) + d;
  9217. };
  9218. return Plane;
  9219. }());
  9220. BABYLON.Plane = Plane;
  9221. /**
  9222. * Class used to represent a viewport on screen
  9223. */
  9224. var Viewport = /** @class */ (function () {
  9225. /**
  9226. * Creates a Viewport object located at (x, y) and sized (width, height)
  9227. * @param x defines viewport left coordinate
  9228. * @param y defines viewport top coordinate
  9229. * @param width defines the viewport width
  9230. * @param height defines the viewport height
  9231. */
  9232. function Viewport(
  9233. /** viewport left coordinate */
  9234. x,
  9235. /** viewport top coordinate */
  9236. y,
  9237. /**viewport width */
  9238. width,
  9239. /** viewport height */
  9240. height) {
  9241. this.x = x;
  9242. this.y = y;
  9243. this.width = width;
  9244. this.height = height;
  9245. }
  9246. /**
  9247. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  9248. * @param renderWidthOrEngine defines either an engine or the rendering width
  9249. * @param renderHeight defines the rendering height
  9250. * @returns a new Viewport
  9251. */
  9252. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  9253. if (renderWidthOrEngine.getRenderWidth) {
  9254. var engine = renderWidthOrEngine;
  9255. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  9256. }
  9257. var renderWidth = renderWidthOrEngine;
  9258. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  9259. };
  9260. /**
  9261. * Returns a new Viewport copied from the current one
  9262. * @returns a new Viewport
  9263. */
  9264. Viewport.prototype.clone = function () {
  9265. return new Viewport(this.x, this.y, this.width, this.height);
  9266. };
  9267. return Viewport;
  9268. }());
  9269. BABYLON.Viewport = Viewport;
  9270. /**
  9271. * Reprasents a camera frustum
  9272. */
  9273. var Frustum = /** @class */ (function () {
  9274. function Frustum() {
  9275. }
  9276. /**
  9277. * Gets the planes representing the frustum
  9278. * @param transform matrix to be applied to the returned planes
  9279. * @returns a new array of 6 Frustum planes computed by the given transformation matrix.
  9280. */
  9281. Frustum.GetPlanes = function (transform) {
  9282. var frustumPlanes = [];
  9283. for (var index = 0; index < 6; index++) {
  9284. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  9285. }
  9286. Frustum.GetPlanesToRef(transform, frustumPlanes);
  9287. return frustumPlanes;
  9288. };
  9289. /**
  9290. * Gets the near frustum plane transformed by the transform matrix
  9291. * @param transform transformation matrix to be applied to the resulting frustum plane
  9292. * @param frustumPlane the resuling frustum plane
  9293. */
  9294. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  9295. var m = transform.m;
  9296. frustumPlane.normal.x = m[3] + m[2];
  9297. frustumPlane.normal.y = m[7] + m[6];
  9298. frustumPlane.normal.z = m[11] + m[10];
  9299. frustumPlane.d = m[15] + m[14];
  9300. frustumPlane.normalize();
  9301. };
  9302. /**
  9303. * Gets the far frustum plane transformed by the transform matrix
  9304. * @param transform transformation matrix to be applied to the resulting frustum plane
  9305. * @param frustumPlane the resuling frustum plane
  9306. */
  9307. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  9308. var m = transform.m;
  9309. frustumPlane.normal.x = m[3] - m[2];
  9310. frustumPlane.normal.y = m[7] - m[6];
  9311. frustumPlane.normal.z = m[11] - m[10];
  9312. frustumPlane.d = m[15] - m[14];
  9313. frustumPlane.normalize();
  9314. };
  9315. /**
  9316. * Gets the left frustum plane transformed by the transform matrix
  9317. * @param transform transformation matrix to be applied to the resulting frustum plane
  9318. * @param frustumPlane the resuling frustum plane
  9319. */
  9320. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  9321. var m = transform.m;
  9322. frustumPlane.normal.x = m[3] + m[0];
  9323. frustumPlane.normal.y = m[7] + m[4];
  9324. frustumPlane.normal.z = m[11] + m[8];
  9325. frustumPlane.d = m[15] + m[12];
  9326. frustumPlane.normalize();
  9327. };
  9328. /**
  9329. * Gets the right frustum plane transformed by the transform matrix
  9330. * @param transform transformation matrix to be applied to the resulting frustum plane
  9331. * @param frustumPlane the resuling frustum plane
  9332. */
  9333. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  9334. var m = transform.m;
  9335. frustumPlane.normal.x = m[3] - m[0];
  9336. frustumPlane.normal.y = m[7] - m[4];
  9337. frustumPlane.normal.z = m[11] - m[8];
  9338. frustumPlane.d = m[15] - m[12];
  9339. frustumPlane.normalize();
  9340. };
  9341. /**
  9342. * Gets the top frustum plane transformed by the transform matrix
  9343. * @param transform transformation matrix to be applied to the resulting frustum plane
  9344. * @param frustumPlane the resuling frustum plane
  9345. */
  9346. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  9347. var m = transform.m;
  9348. frustumPlane.normal.x = m[3] - m[1];
  9349. frustumPlane.normal.y = m[7] - m[5];
  9350. frustumPlane.normal.z = m[11] - m[9];
  9351. frustumPlane.d = m[15] - m[13];
  9352. frustumPlane.normalize();
  9353. };
  9354. /**
  9355. * Gets the bottom frustum plane transformed by the transform matrix
  9356. * @param transform transformation matrix to be applied to the resulting frustum plane
  9357. * @param frustumPlane the resuling frustum plane
  9358. */
  9359. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  9360. var m = transform.m;
  9361. frustumPlane.normal.x = m[3] + m[1];
  9362. frustumPlane.normal.y = m[7] + m[5];
  9363. frustumPlane.normal.z = m[11] + m[9];
  9364. frustumPlane.d = m[15] + m[13];
  9365. frustumPlane.normalize();
  9366. };
  9367. /**
  9368. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  9369. * @param transform transformation matrix to be applied to the resulting frustum planes
  9370. * @param frustumPlanes the resuling frustum planes
  9371. */
  9372. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  9373. // Near
  9374. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  9375. // Far
  9376. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  9377. // Left
  9378. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  9379. // Right
  9380. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  9381. // Top
  9382. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  9383. // Bottom
  9384. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  9385. };
  9386. return Frustum;
  9387. }());
  9388. BABYLON.Frustum = Frustum;
  9389. /** Defines supported spaces */
  9390. var Space;
  9391. (function (Space) {
  9392. /** Local (object) space */
  9393. Space[Space["LOCAL"] = 0] = "LOCAL";
  9394. /** World space */
  9395. Space[Space["WORLD"] = 1] = "WORLD";
  9396. /** Bone space */
  9397. Space[Space["BONE"] = 2] = "BONE";
  9398. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  9399. /** Defines the 3 main axes */
  9400. var Axis = /** @class */ (function () {
  9401. function Axis() {
  9402. }
  9403. /** X axis */
  9404. Axis.X = new Vector3(1.0, 0.0, 0.0);
  9405. /** Y axis */
  9406. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  9407. /** Z axis */
  9408. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  9409. return Axis;
  9410. }());
  9411. BABYLON.Axis = Axis;
  9412. /** Class used to represent a Bezier curve */
  9413. var BezierCurve = /** @class */ (function () {
  9414. function BezierCurve() {
  9415. }
  9416. /**
  9417. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  9418. * @param t defines the time
  9419. * @param x1 defines the left coordinate on X axis
  9420. * @param y1 defines the left coordinate on Y axis
  9421. * @param x2 defines the right coordinate on X axis
  9422. * @param y2 defines the right coordinate on Y axis
  9423. * @returns the interpolated value
  9424. */
  9425. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  9426. // Extract X (which is equal to time here)
  9427. var f0 = 1 - 3 * x2 + 3 * x1;
  9428. var f1 = 3 * x2 - 6 * x1;
  9429. var f2 = 3 * x1;
  9430. var refinedT = t;
  9431. for (var i = 0; i < 5; i++) {
  9432. var refinedT2 = refinedT * refinedT;
  9433. var refinedT3 = refinedT2 * refinedT;
  9434. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  9435. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  9436. refinedT -= (x - t) * slope;
  9437. refinedT = Math.min(1, Math.max(0, refinedT));
  9438. }
  9439. // Resolve cubic bezier for the given x
  9440. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  9441. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  9442. Math.pow(refinedT, 3);
  9443. };
  9444. return BezierCurve;
  9445. }());
  9446. BABYLON.BezierCurve = BezierCurve;
  9447. /**
  9448. * Defines potential orientation for back face culling
  9449. */
  9450. var Orientation;
  9451. (function (Orientation) {
  9452. /**
  9453. * Clockwise
  9454. */
  9455. Orientation[Orientation["CW"] = 0] = "CW";
  9456. /** Counter clockwise */
  9457. Orientation[Orientation["CCW"] = 1] = "CCW";
  9458. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  9459. /**
  9460. * Defines angle representation
  9461. */
  9462. var Angle = /** @class */ (function () {
  9463. /**
  9464. * Creates an Angle object of "radians" radians (float).
  9465. */
  9466. function Angle(radians) {
  9467. this._radians = radians;
  9468. if (this._radians < 0.0) {
  9469. this._radians += (2.0 * Math.PI);
  9470. }
  9471. }
  9472. /**
  9473. * Get value in degrees
  9474. * @returns the Angle value in degrees (float)
  9475. */
  9476. Angle.prototype.degrees = function () {
  9477. return this._radians * 180.0 / Math.PI;
  9478. };
  9479. /**
  9480. * Get value in radians
  9481. * @returns the Angle value in radians (float)
  9482. */
  9483. Angle.prototype.radians = function () {
  9484. return this._radians;
  9485. };
  9486. /**
  9487. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  9488. * @param a defines first vector
  9489. * @param b defines second vector
  9490. * @returns a new Angle
  9491. */
  9492. Angle.BetweenTwoPoints = function (a, b) {
  9493. var delta = b.subtract(a);
  9494. var theta = Math.atan2(delta.y, delta.x);
  9495. return new Angle(theta);
  9496. };
  9497. /**
  9498. * Gets a new Angle object from the given float in radians
  9499. * @param radians defines the angle value in radians
  9500. * @returns a new Angle
  9501. */
  9502. Angle.FromRadians = function (radians) {
  9503. return new Angle(radians);
  9504. };
  9505. /**
  9506. * Gets a new Angle object from the given float in degrees
  9507. * @param degrees defines the angle value in degrees
  9508. * @returns a new Angle
  9509. */
  9510. Angle.FromDegrees = function (degrees) {
  9511. return new Angle(degrees * Math.PI / 180.0);
  9512. };
  9513. return Angle;
  9514. }());
  9515. BABYLON.Angle = Angle;
  9516. /**
  9517. * This represents an arc in a 2d space.
  9518. */
  9519. var Arc2 = /** @class */ (function () {
  9520. /**
  9521. * Creates an Arc object from the three given points : start, middle and end.
  9522. * @param startPoint Defines the start point of the arc
  9523. * @param midPoint Defines the midlle point of the arc
  9524. * @param endPoint Defines the end point of the arc
  9525. */
  9526. function Arc2(
  9527. /** Defines the start point of the arc */
  9528. startPoint,
  9529. /** Defines the mid point of the arc */
  9530. midPoint,
  9531. /** Defines the end point of the arc */
  9532. endPoint) {
  9533. this.startPoint = startPoint;
  9534. this.midPoint = midPoint;
  9535. this.endPoint = endPoint;
  9536. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  9537. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  9538. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  9539. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  9540. 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);
  9541. this.radius = this.centerPoint.subtract(this.startPoint).length();
  9542. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  9543. var a1 = this.startAngle.degrees();
  9544. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  9545. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  9546. // angles correction
  9547. if (a2 - a1 > +180.0) {
  9548. a2 -= 360.0;
  9549. }
  9550. if (a2 - a1 < -180.0) {
  9551. a2 += 360.0;
  9552. }
  9553. if (a3 - a2 > +180.0) {
  9554. a3 -= 360.0;
  9555. }
  9556. if (a3 - a2 < -180.0) {
  9557. a3 += 360.0;
  9558. }
  9559. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  9560. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  9561. }
  9562. return Arc2;
  9563. }());
  9564. BABYLON.Arc2 = Arc2;
  9565. /**
  9566. * Represents a 2D path made up of multiple 2D points
  9567. */
  9568. var Path2 = /** @class */ (function () {
  9569. /**
  9570. * Creates a Path2 object from the starting 2D coordinates x and y.
  9571. * @param x the starting points x value
  9572. * @param y the starting points y value
  9573. */
  9574. function Path2(x, y) {
  9575. this._points = new Array();
  9576. this._length = 0.0;
  9577. /**
  9578. * If the path start and end point are the same
  9579. */
  9580. this.closed = false;
  9581. this._points.push(new Vector2(x, y));
  9582. }
  9583. /**
  9584. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  9585. * @param x the added points x value
  9586. * @param y the added points y value
  9587. * @returns the updated Path2.
  9588. */
  9589. Path2.prototype.addLineTo = function (x, y) {
  9590. if (this.closed) {
  9591. return this;
  9592. }
  9593. var newPoint = new Vector2(x, y);
  9594. var previousPoint = this._points[this._points.length - 1];
  9595. this._points.push(newPoint);
  9596. this._length += newPoint.subtract(previousPoint).length();
  9597. return this;
  9598. };
  9599. /**
  9600. * 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.
  9601. * @param midX middle point x value
  9602. * @param midY middle point y value
  9603. * @param endX end point x value
  9604. * @param endY end point y value
  9605. * @param numberOfSegments (default: 36)
  9606. * @returns the updated Path2.
  9607. */
  9608. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  9609. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  9610. if (this.closed) {
  9611. return this;
  9612. }
  9613. var startPoint = this._points[this._points.length - 1];
  9614. var midPoint = new Vector2(midX, midY);
  9615. var endPoint = new Vector2(endX, endY);
  9616. var arc = new Arc2(startPoint, midPoint, endPoint);
  9617. var increment = arc.angle.radians() / numberOfSegments;
  9618. if (arc.orientation === Orientation.CW) {
  9619. increment *= -1;
  9620. }
  9621. var currentAngle = arc.startAngle.radians() + increment;
  9622. for (var i = 0; i < numberOfSegments; i++) {
  9623. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  9624. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  9625. this.addLineTo(x, y);
  9626. currentAngle += increment;
  9627. }
  9628. return this;
  9629. };
  9630. /**
  9631. * Closes the Path2.
  9632. * @returns the Path2.
  9633. */
  9634. Path2.prototype.close = function () {
  9635. this.closed = true;
  9636. return this;
  9637. };
  9638. /**
  9639. * Gets the sum of the distance between each sequential point in the path
  9640. * @returns the Path2 total length (float).
  9641. */
  9642. Path2.prototype.length = function () {
  9643. var result = this._length;
  9644. if (!this.closed) {
  9645. var lastPoint = this._points[this._points.length - 1];
  9646. var firstPoint = this._points[0];
  9647. result += (firstPoint.subtract(lastPoint).length());
  9648. }
  9649. return result;
  9650. };
  9651. /**
  9652. * Gets the points which construct the path
  9653. * @returns the Path2 internal array of points.
  9654. */
  9655. Path2.prototype.getPoints = function () {
  9656. return this._points;
  9657. };
  9658. /**
  9659. * Retreives the point at the distance aways from the starting point
  9660. * @param normalizedLengthPosition the length along the path to retreive the point from
  9661. * @returns a new Vector2 located at a percentage of the Path2 total length on this path.
  9662. */
  9663. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  9664. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  9665. return Vector2.Zero();
  9666. }
  9667. var lengthPosition = normalizedLengthPosition * this.length();
  9668. var previousOffset = 0;
  9669. for (var i = 0; i < this._points.length; i++) {
  9670. var j = (i + 1) % this._points.length;
  9671. var a = this._points[i];
  9672. var b = this._points[j];
  9673. var bToA = b.subtract(a);
  9674. var nextOffset = (bToA.length() + previousOffset);
  9675. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  9676. var dir = bToA.normalize();
  9677. var localOffset = lengthPosition - previousOffset;
  9678. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  9679. }
  9680. previousOffset = nextOffset;
  9681. }
  9682. return Vector2.Zero();
  9683. };
  9684. /**
  9685. * Creates a new path starting from an x and y position
  9686. * @param x starting x value
  9687. * @param y starting y value
  9688. * @returns a new Path2 starting at the coordinates (x, y).
  9689. */
  9690. Path2.StartingAt = function (x, y) {
  9691. return new Path2(x, y);
  9692. };
  9693. return Path2;
  9694. }());
  9695. BABYLON.Path2 = Path2;
  9696. /**
  9697. * Represents a 3D path made up of multiple 3D points
  9698. */
  9699. var Path3D = /** @class */ (function () {
  9700. /**
  9701. * new Path3D(path, normal, raw)
  9702. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  9703. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  9704. * @param path an array of Vector3, the curve axis of the Path3D
  9705. * @param normal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  9706. * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  9707. */
  9708. function Path3D(
  9709. /**
  9710. * an array of Vector3, the curve axis of the Path3D
  9711. */
  9712. path, firstNormal, raw) {
  9713. if (firstNormal === void 0) { firstNormal = null; }
  9714. this.path = path;
  9715. this._curve = new Array();
  9716. this._distances = new Array();
  9717. this._tangents = new Array();
  9718. this._normals = new Array();
  9719. this._binormals = new Array();
  9720. for (var p = 0; p < path.length; p++) {
  9721. this._curve[p] = path[p].clone(); // hard copy
  9722. }
  9723. this._raw = raw || false;
  9724. this._compute(firstNormal);
  9725. }
  9726. /**
  9727. * Returns the Path3D array of successive Vector3 designing its curve.
  9728. * @returns the Path3D array of successive Vector3 designing its curve.
  9729. */
  9730. Path3D.prototype.getCurve = function () {
  9731. return this._curve;
  9732. };
  9733. /**
  9734. * Returns an array populated with tangent vectors on each Path3D curve point.
  9735. * @returns an array populated with tangent vectors on each Path3D curve point.
  9736. */
  9737. Path3D.prototype.getTangents = function () {
  9738. return this._tangents;
  9739. };
  9740. /**
  9741. * Returns an array populated with normal vectors on each Path3D curve point.
  9742. * @returns an array populated with normal vectors on each Path3D curve point.
  9743. */
  9744. Path3D.prototype.getNormals = function () {
  9745. return this._normals;
  9746. };
  9747. /**
  9748. * Returns an array populated with binormal vectors on each Path3D curve point.
  9749. * @returns an array populated with binormal vectors on each Path3D curve point.
  9750. */
  9751. Path3D.prototype.getBinormals = function () {
  9752. return this._binormals;
  9753. };
  9754. /**
  9755. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  9756. * @returns an array populated with distances (float) of the i-th point from the first curve point.
  9757. */
  9758. Path3D.prototype.getDistances = function () {
  9759. return this._distances;
  9760. };
  9761. /**
  9762. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  9763. * @param path path which all values are copied into the curves points
  9764. * @param firstNormal which should be projected onto the curve
  9765. * @returns the same object updated.
  9766. */
  9767. Path3D.prototype.update = function (path, firstNormal) {
  9768. if (firstNormal === void 0) { firstNormal = null; }
  9769. for (var p = 0; p < path.length; p++) {
  9770. this._curve[p].x = path[p].x;
  9771. this._curve[p].y = path[p].y;
  9772. this._curve[p].z = path[p].z;
  9773. }
  9774. this._compute(firstNormal);
  9775. return this;
  9776. };
  9777. // private function compute() : computes tangents, normals and binormals
  9778. Path3D.prototype._compute = function (firstNormal) {
  9779. var l = this._curve.length;
  9780. // first and last tangents
  9781. this._tangents[0] = this._getFirstNonNullVector(0);
  9782. if (!this._raw) {
  9783. this._tangents[0].normalize();
  9784. }
  9785. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  9786. if (!this._raw) {
  9787. this._tangents[l - 1].normalize();
  9788. }
  9789. // normals and binormals at first point : arbitrary vector with _normalVector()
  9790. var tg0 = this._tangents[0];
  9791. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  9792. this._normals[0] = pp0;
  9793. if (!this._raw) {
  9794. this._normals[0].normalize();
  9795. }
  9796. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  9797. if (!this._raw) {
  9798. this._binormals[0].normalize();
  9799. }
  9800. this._distances[0] = 0.0;
  9801. // normals and binormals : next points
  9802. var prev; // previous vector (segment)
  9803. var cur; // current vector (segment)
  9804. var curTang; // current tangent
  9805. // previous normal
  9806. var prevBinor; // previous binormal
  9807. for (var i = 1; i < l; i++) {
  9808. // tangents
  9809. prev = this._getLastNonNullVector(i);
  9810. if (i < l - 1) {
  9811. cur = this._getFirstNonNullVector(i);
  9812. this._tangents[i] = prev.add(cur);
  9813. this._tangents[i].normalize();
  9814. }
  9815. this._distances[i] = this._distances[i - 1] + prev.length();
  9816. // normals and binormals
  9817. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  9818. curTang = this._tangents[i];
  9819. prevBinor = this._binormals[i - 1];
  9820. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  9821. if (!this._raw) {
  9822. this._normals[i].normalize();
  9823. }
  9824. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  9825. if (!this._raw) {
  9826. this._binormals[i].normalize();
  9827. }
  9828. }
  9829. };
  9830. // private function getFirstNonNullVector(index)
  9831. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  9832. Path3D.prototype._getFirstNonNullVector = function (index) {
  9833. var i = 1;
  9834. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  9835. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  9836. i++;
  9837. nNVector = this._curve[index + i].subtract(this._curve[index]);
  9838. }
  9839. return nNVector;
  9840. };
  9841. // private function getLastNonNullVector(index)
  9842. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  9843. Path3D.prototype._getLastNonNullVector = function (index) {
  9844. var i = 1;
  9845. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  9846. while (nLVector.length() === 0 && index > i + 1) {
  9847. i++;
  9848. nLVector = this._curve[index].subtract(this._curve[index - i]);
  9849. }
  9850. return nLVector;
  9851. };
  9852. // private function normalVector(v0, vt, va) :
  9853. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  9854. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  9855. Path3D.prototype._normalVector = function (v0, vt, va) {
  9856. var normal0;
  9857. var tgl = vt.length();
  9858. if (tgl === 0.0) {
  9859. tgl = 1.0;
  9860. }
  9861. if (va === undefined || va === null) {
  9862. var point;
  9863. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  9864. point = new Vector3(0.0, -1.0, 0.0);
  9865. }
  9866. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  9867. point = new Vector3(1.0, 0.0, 0.0);
  9868. }
  9869. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  9870. point = new Vector3(0.0, 0.0, 1.0);
  9871. }
  9872. else {
  9873. point = Vector3.Zero();
  9874. }
  9875. normal0 = Vector3.Cross(vt, point);
  9876. }
  9877. else {
  9878. normal0 = Vector3.Cross(vt, va);
  9879. Vector3.CrossToRef(normal0, vt, normal0);
  9880. }
  9881. normal0.normalize();
  9882. return normal0;
  9883. };
  9884. return Path3D;
  9885. }());
  9886. BABYLON.Path3D = Path3D;
  9887. /**
  9888. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  9889. * A Curve3 is designed from a series of successive Vector3.
  9890. * @see https://doc.babylonjs.com/how_to/how_to_use_curve3
  9891. */
  9892. var Curve3 = /** @class */ (function () {
  9893. /**
  9894. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  9895. * A Curve3 is designed from a series of successive Vector3.
  9896. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  9897. * @param points points which make up the curve
  9898. */
  9899. function Curve3(points) {
  9900. this._length = 0.0;
  9901. this._points = points;
  9902. this._length = this._computeLength(points);
  9903. }
  9904. /**
  9905. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  9906. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  9907. * @param v1 (Vector3) the control point
  9908. * @param v2 (Vector3) the end point of the Quadratic Bezier
  9909. * @param nbPoints (integer) the wanted number of points in the curve
  9910. * @returns the created Curve3
  9911. */
  9912. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  9913. nbPoints = nbPoints > 2 ? nbPoints : 3;
  9914. var bez = new Array();
  9915. var equation = function (t, val0, val1, val2) {
  9916. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  9917. return res;
  9918. };
  9919. for (var i = 0; i <= nbPoints; i++) {
  9920. 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)));
  9921. }
  9922. return new Curve3(bez);
  9923. };
  9924. /**
  9925. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  9926. * @param v0 (Vector3) the origin point of the Cubic Bezier
  9927. * @param v1 (Vector3) the first control point
  9928. * @param v2 (Vector3) the second control point
  9929. * @param v3 (Vector3) the end point of the Cubic Bezier
  9930. * @param nbPoints (integer) the wanted number of points in the curve
  9931. * @returns the created Curve3
  9932. */
  9933. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  9934. nbPoints = nbPoints > 3 ? nbPoints : 4;
  9935. var bez = new Array();
  9936. var equation = function (t, val0, val1, val2, val3) {
  9937. 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;
  9938. return res;
  9939. };
  9940. for (var i = 0; i <= nbPoints; i++) {
  9941. 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)));
  9942. }
  9943. return new Curve3(bez);
  9944. };
  9945. /**
  9946. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  9947. * @param p1 (Vector3) the origin point of the Hermite Spline
  9948. * @param t1 (Vector3) the tangent vector at the origin point
  9949. * @param p2 (Vector3) the end point of the Hermite Spline
  9950. * @param t2 (Vector3) the tangent vector at the end point
  9951. * @param nbPoints (integer) the wanted number of points in the curve
  9952. * @returns the created Curve3
  9953. */
  9954. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  9955. var hermite = new Array();
  9956. var step = 1.0 / nbPoints;
  9957. for (var i = 0; i <= nbPoints; i++) {
  9958. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  9959. }
  9960. return new Curve3(hermite);
  9961. };
  9962. /**
  9963. * Returns a Curve3 object along a CatmullRom Spline curve :
  9964. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  9965. * @param nbPoints (integer) the wanted number of points between each curve control points
  9966. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  9967. * @returns the created Curve3
  9968. */
  9969. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  9970. var catmullRom = new Array();
  9971. var step = 1.0 / nbPoints;
  9972. var amount = 0.0;
  9973. if (closed) {
  9974. var pointsCount = points.length;
  9975. for (var i = 0; i < pointsCount; i++) {
  9976. amount = 0;
  9977. for (var c = 0; c < nbPoints; c++) {
  9978. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  9979. amount += step;
  9980. }
  9981. }
  9982. catmullRom.push(catmullRom[0]);
  9983. }
  9984. else {
  9985. var totalPoints = new Array();
  9986. totalPoints.push(points[0].clone());
  9987. Array.prototype.push.apply(totalPoints, points);
  9988. totalPoints.push(points[points.length - 1].clone());
  9989. for (var i = 0; i < totalPoints.length - 3; i++) {
  9990. amount = 0;
  9991. for (var c = 0; c < nbPoints; c++) {
  9992. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  9993. amount += step;
  9994. }
  9995. }
  9996. i--;
  9997. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  9998. }
  9999. return new Curve3(catmullRom);
  10000. };
  10001. /**
  10002. * @returns the Curve3 stored array of successive Vector3
  10003. */
  10004. Curve3.prototype.getPoints = function () {
  10005. return this._points;
  10006. };
  10007. /**
  10008. * @returns the computed length (float) of the curve.
  10009. */
  10010. Curve3.prototype.length = function () {
  10011. return this._length;
  10012. };
  10013. /**
  10014. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  10015. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  10016. * curveA and curveB keep unchanged.
  10017. * @param curve the curve to continue from this curve
  10018. * @returns the newly constructed curve
  10019. */
  10020. Curve3.prototype.continue = function (curve) {
  10021. var lastPoint = this._points[this._points.length - 1];
  10022. var continuedPoints = this._points.slice();
  10023. var curvePoints = curve.getPoints();
  10024. for (var i = 1; i < curvePoints.length; i++) {
  10025. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  10026. }
  10027. var continuedCurve = new Curve3(continuedPoints);
  10028. return continuedCurve;
  10029. };
  10030. Curve3.prototype._computeLength = function (path) {
  10031. var l = 0;
  10032. for (var i = 1; i < path.length; i++) {
  10033. l += (path[i].subtract(path[i - 1])).length();
  10034. }
  10035. return l;
  10036. };
  10037. return Curve3;
  10038. }());
  10039. BABYLON.Curve3 = Curve3;
  10040. // Vertex formats
  10041. /**
  10042. * Contains position and normal vectors for a vertex
  10043. */
  10044. var PositionNormalVertex = /** @class */ (function () {
  10045. /**
  10046. * Creates a PositionNormalVertex
  10047. * @param position the position of the vertex (defaut: 0,0,0)
  10048. * @param normal the normal of the vertex (defaut: 0,1,0)
  10049. */
  10050. function PositionNormalVertex(
  10051. /** the position of the vertex (defaut: 0,0,0) */
  10052. position,
  10053. /** the normal of the vertex (defaut: 0,1,0) */
  10054. normal) {
  10055. if (position === void 0) { position = Vector3.Zero(); }
  10056. if (normal === void 0) { normal = Vector3.Up(); }
  10057. this.position = position;
  10058. this.normal = normal;
  10059. }
  10060. /**
  10061. * Clones the PositionNormalVertex
  10062. * @returns the cloned PositionNormalVertex
  10063. */
  10064. PositionNormalVertex.prototype.clone = function () {
  10065. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  10066. };
  10067. return PositionNormalVertex;
  10068. }());
  10069. BABYLON.PositionNormalVertex = PositionNormalVertex;
  10070. /**
  10071. * Contains position, normal and uv vectors for a vertex
  10072. */
  10073. var PositionNormalTextureVertex = /** @class */ (function () {
  10074. /**
  10075. * Creates a PositionNormalTextureVertex
  10076. * @param position the position of the vertex (defaut: 0,0,0)
  10077. * @param normal the normal of the vertex (defaut: 0,1,0)
  10078. * @param uv the uv of the vertex (default: 0,0)
  10079. */
  10080. function PositionNormalTextureVertex(
  10081. /** the position of the vertex (defaut: 0,0,0) */
  10082. position,
  10083. /** the normal of the vertex (defaut: 0,1,0) */
  10084. normal,
  10085. /** the uv of the vertex (default: 0,0) */
  10086. uv) {
  10087. if (position === void 0) { position = Vector3.Zero(); }
  10088. if (normal === void 0) { normal = Vector3.Up(); }
  10089. if (uv === void 0) { uv = Vector2.Zero(); }
  10090. this.position = position;
  10091. this.normal = normal;
  10092. this.uv = uv;
  10093. }
  10094. /**
  10095. * Clones the PositionNormalTextureVertex
  10096. * @returns the cloned PositionNormalTextureVertex
  10097. */
  10098. PositionNormalTextureVertex.prototype.clone = function () {
  10099. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  10100. };
  10101. return PositionNormalTextureVertex;
  10102. }());
  10103. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  10104. // Temporary pre-allocated objects for engine internal use
  10105. // usage in any internal function :
  10106. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  10107. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  10108. /**
  10109. * @hidden
  10110. */
  10111. var Tmp = /** @class */ (function () {
  10112. function Tmp() {
  10113. }
  10114. Tmp.Color3 = BABYLON.Tools.BuildArray(3, Color3.Black);
  10115. Tmp.Color4 = BABYLON.Tools.BuildArray(3, function () { return new Color4(0, 0, 0, 0); });
  10116. Tmp.Vector2 = BABYLON.Tools.BuildArray(3, Vector2.Zero); // 3 temp Vector2 at once should be enough
  10117. Tmp.Vector3 = BABYLON.Tools.BuildArray(13, Vector3.Zero); // 13 temp Vector3 at once should be enough
  10118. Tmp.Vector4 = BABYLON.Tools.BuildArray(3, Vector4.Zero); // 3 temp Vector4 at once should be enough
  10119. Tmp.Quaternion = BABYLON.Tools.BuildArray(2, Quaternion.Zero); // 2 temp Quaternion at once should be enough
  10120. Tmp.Matrix = BABYLON.Tools.BuildArray(8, Matrix.Identity); // 8 temp Matrices at once should be enough
  10121. return Tmp;
  10122. }());
  10123. BABYLON.Tmp = Tmp;
  10124. /**
  10125. * @hidden
  10126. * Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  10127. */
  10128. var MathTmp = /** @class */ (function () {
  10129. function MathTmp() {
  10130. }
  10131. MathTmp.Vector3 = BABYLON.Tools.BuildArray(6, Vector3.Zero);
  10132. MathTmp.Matrix = BABYLON.Tools.BuildArray(2, Matrix.Identity);
  10133. MathTmp.Quaternion = BABYLON.Tools.BuildArray(3, Quaternion.Zero);
  10134. return MathTmp;
  10135. }());
  10136. })(BABYLON || (BABYLON = {}));
  10137. //# sourceMappingURL=math.js.map
  10138. var BABYLON;
  10139. (function (BABYLON) {
  10140. /**
  10141. * Scalar computation library
  10142. */
  10143. var Scalar = /** @class */ (function () {
  10144. function Scalar() {
  10145. }
  10146. /**
  10147. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  10148. * @param a number
  10149. * @param b number
  10150. * @param epsilon (default = 1.401298E-45)
  10151. * @returns true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  10152. */
  10153. Scalar.WithinEpsilon = function (a, b, epsilon) {
  10154. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  10155. var num = a - b;
  10156. return -epsilon <= num && num <= epsilon;
  10157. };
  10158. /**
  10159. * Returns a string : the upper case translation of the number i to hexadecimal.
  10160. * @param i number
  10161. * @returns the upper case translation of the number i to hexadecimal.
  10162. */
  10163. Scalar.ToHex = function (i) {
  10164. var str = i.toString(16);
  10165. if (i <= 15) {
  10166. return ("0" + str).toUpperCase();
  10167. }
  10168. return str.toUpperCase();
  10169. };
  10170. /**
  10171. * Returns -1 if value is negative and +1 is value is positive.
  10172. * @param value the value
  10173. * @returns the value itself if it's equal to zero.
  10174. */
  10175. Scalar.Sign = function (value) {
  10176. value = +value; // convert to a number
  10177. if (value === 0 || isNaN(value)) {
  10178. return value;
  10179. }
  10180. return value > 0 ? 1 : -1;
  10181. };
  10182. /**
  10183. * Returns the value itself if it's between min and max.
  10184. * Returns min if the value is lower than min.
  10185. * Returns max if the value is greater than max.
  10186. * @param value the value to clmap
  10187. * @param min the min value to clamp to (default: 0)
  10188. * @param max the max value to clamp to (default: 1)
  10189. * @returns the clamped value
  10190. */
  10191. Scalar.Clamp = function (value, min, max) {
  10192. if (min === void 0) { min = 0; }
  10193. if (max === void 0) { max = 1; }
  10194. return Math.min(max, Math.max(min, value));
  10195. };
  10196. /**
  10197. * the log2 of value.
  10198. * @param value the value to compute log2 of
  10199. * @returns the log2 of value.
  10200. */
  10201. Scalar.Log2 = function (value) {
  10202. return Math.log(value) * Math.LOG2E;
  10203. };
  10204. /**
  10205. * Loops the value, so that it is never larger than length and never smaller than 0.
  10206. *
  10207. * This is similar to the modulo operator but it works with floating point numbers.
  10208. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  10209. * With t = 5 and length = 2.5, the result would be 0.0.
  10210. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  10211. * @param value the value
  10212. * @param length the length
  10213. * @returns the looped value
  10214. */
  10215. Scalar.Repeat = function (value, length) {
  10216. return value - Math.floor(value / length) * length;
  10217. };
  10218. /**
  10219. * Normalize the value between 0.0 and 1.0 using min and max values
  10220. * @param value value to normalize
  10221. * @param min max to normalize between
  10222. * @param max min to normalize between
  10223. * @returns the normalized value
  10224. */
  10225. Scalar.Normalize = function (value, min, max) {
  10226. return (value - min) / (max - min);
  10227. };
  10228. /**
  10229. * Denormalize the value from 0.0 and 1.0 using min and max values
  10230. * @param normalized value to denormalize
  10231. * @param min max to denormalize between
  10232. * @param max min to denormalize between
  10233. * @returns the denormalized value
  10234. */
  10235. Scalar.Denormalize = function (normalized, min, max) {
  10236. return (normalized * (max - min) + min);
  10237. };
  10238. /**
  10239. * Calculates the shortest difference between two given angles given in degrees.
  10240. * @param current current angle in degrees
  10241. * @param target target angle in degrees
  10242. * @returns the delta
  10243. */
  10244. Scalar.DeltaAngle = function (current, target) {
  10245. var num = Scalar.Repeat(target - current, 360.0);
  10246. if (num > 180.0) {
  10247. num -= 360.0;
  10248. }
  10249. return num;
  10250. };
  10251. /**
  10252. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  10253. * @param tx value
  10254. * @param length length
  10255. * @returns The returned value will move back and forth between 0 and length
  10256. */
  10257. Scalar.PingPong = function (tx, length) {
  10258. var t = Scalar.Repeat(tx, length * 2.0);
  10259. return length - Math.abs(t - length);
  10260. };
  10261. /**
  10262. * Interpolates between min and max with smoothing at the limits.
  10263. *
  10264. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  10265. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  10266. * @param from from
  10267. * @param to to
  10268. * @param tx value
  10269. * @returns the smooth stepped value
  10270. */
  10271. Scalar.SmoothStep = function (from, to, tx) {
  10272. var t = Scalar.Clamp(tx);
  10273. t = -2.0 * t * t * t + 3.0 * t * t;
  10274. return to * t + from * (1.0 - t);
  10275. };
  10276. /**
  10277. * Moves a value current towards target.
  10278. *
  10279. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  10280. * Negative values of maxDelta pushes the value away from target.
  10281. * @param current current value
  10282. * @param target target value
  10283. * @param maxDelta max distance to move
  10284. * @returns resulting value
  10285. */
  10286. Scalar.MoveTowards = function (current, target, maxDelta) {
  10287. var result = 0;
  10288. if (Math.abs(target - current) <= maxDelta) {
  10289. result = target;
  10290. }
  10291. else {
  10292. result = current + Scalar.Sign(target - current) * maxDelta;
  10293. }
  10294. return result;
  10295. };
  10296. /**
  10297. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  10298. *
  10299. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  10300. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  10301. * @param current current value
  10302. * @param target target value
  10303. * @param maxDelta max distance to move
  10304. * @returns resulting angle
  10305. */
  10306. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  10307. var num = Scalar.DeltaAngle(current, target);
  10308. var result = 0;
  10309. if (-maxDelta < num && num < maxDelta) {
  10310. result = target;
  10311. }
  10312. else {
  10313. target = current + num;
  10314. result = Scalar.MoveTowards(current, target, maxDelta);
  10315. }
  10316. return result;
  10317. };
  10318. /**
  10319. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  10320. * @param start start value
  10321. * @param end target value
  10322. * @param amount amount to lerp between
  10323. * @returns the lerped value
  10324. */
  10325. Scalar.Lerp = function (start, end, amount) {
  10326. return start + ((end - start) * amount);
  10327. };
  10328. /**
  10329. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  10330. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  10331. * @param start start value
  10332. * @param end target value
  10333. * @param amount amount to lerp between
  10334. * @returns the lerped value
  10335. */
  10336. Scalar.LerpAngle = function (start, end, amount) {
  10337. var num = Scalar.Repeat(end - start, 360.0);
  10338. if (num > 180.0) {
  10339. num -= 360.0;
  10340. }
  10341. return start + num * Scalar.Clamp(amount);
  10342. };
  10343. /**
  10344. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  10345. * @param a start value
  10346. * @param b target value
  10347. * @param value value between a and b
  10348. * @returns the inverseLerp value
  10349. */
  10350. Scalar.InverseLerp = function (a, b, value) {
  10351. var result = 0;
  10352. if (a != b) {
  10353. result = Scalar.Clamp((value - a) / (b - a));
  10354. }
  10355. else {
  10356. result = 0.0;
  10357. }
  10358. return result;
  10359. };
  10360. /**
  10361. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  10362. * @see http://mathworld.wolfram.com/HermitePolynomial.html
  10363. * @param value1 spline value
  10364. * @param tangent1 spline value
  10365. * @param value2 spline value
  10366. * @param tangent2 spline value
  10367. * @param amount input value
  10368. * @returns hermite result
  10369. */
  10370. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  10371. var squared = amount * amount;
  10372. var cubed = amount * squared;
  10373. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  10374. var part2 = (-2.0 * cubed) + (3.0 * squared);
  10375. var part3 = (cubed - (2.0 * squared)) + amount;
  10376. var part4 = cubed - squared;
  10377. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  10378. };
  10379. /**
  10380. * Returns a random float number between and min and max values
  10381. * @param min min value of random
  10382. * @param max max value of random
  10383. * @returns random value
  10384. */
  10385. Scalar.RandomRange = function (min, max) {
  10386. if (min === max) {
  10387. return min;
  10388. }
  10389. return ((Math.random() * (max - min)) + min);
  10390. };
  10391. /**
  10392. * This function returns percentage of a number in a given range.
  10393. *
  10394. * RangeToPercent(40,20,60) will return 0.5 (50%)
  10395. * RangeToPercent(34,0,100) will return 0.34 (34%)
  10396. * @param number to convert to percentage
  10397. * @param min min range
  10398. * @param max max range
  10399. * @returns the percentage
  10400. */
  10401. Scalar.RangeToPercent = function (number, min, max) {
  10402. return ((number - min) / (max - min));
  10403. };
  10404. /**
  10405. * This function returns number that corresponds to the percentage in a given range.
  10406. *
  10407. * PercentToRange(0.34,0,100) will return 34.
  10408. * @param percent to convert to number
  10409. * @param min min range
  10410. * @param max max range
  10411. * @returns the number
  10412. */
  10413. Scalar.PercentToRange = function (percent, min, max) {
  10414. return ((max - min) * percent + min);
  10415. };
  10416. /**
  10417. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  10418. * @param angle The angle to normalize in radian.
  10419. * @return The converted angle.
  10420. */
  10421. Scalar.NormalizeRadians = function (angle) {
  10422. // More precise but slower version kept for reference.
  10423. // angle = angle % Tools.TwoPi;
  10424. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  10425. //if (angle > Math.PI) {
  10426. // angle -= Tools.TwoPi;
  10427. //}
  10428. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  10429. return angle;
  10430. };
  10431. /**
  10432. * Two pi constants convenient for computation.
  10433. */
  10434. Scalar.TwoPi = Math.PI * 2;
  10435. return Scalar;
  10436. }());
  10437. BABYLON.Scalar = Scalar;
  10438. })(BABYLON || (BABYLON = {}));
  10439. //# sourceMappingURL=math.scalar.js.map
  10440. //# sourceMappingURL=mixins.js.map
  10441. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  10442. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  10443. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  10444. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  10445. //# sourceMappingURL=webgl2.js.map
  10446. var BABYLON;
  10447. (function (BABYLON) {
  10448. var __decoratorInitialStore = {};
  10449. var __mergedStore = {};
  10450. var _copySource = function (creationFunction, source, instanciate) {
  10451. var destination = creationFunction();
  10452. // Tags
  10453. if (BABYLON.Tags) {
  10454. BABYLON.Tags.AddTagsTo(destination, source.tags);
  10455. }
  10456. var classStore = getMergedStore(destination);
  10457. // Properties
  10458. for (var property in classStore) {
  10459. var propertyDescriptor = classStore[property];
  10460. var sourceProperty = source[property];
  10461. var propertyType = propertyDescriptor.type;
  10462. if (sourceProperty !== undefined && sourceProperty !== null) {
  10463. switch (propertyType) {
  10464. case 0: // Value
  10465. case 6: // Mesh reference
  10466. case 11: // Camera reference
  10467. destination[property] = sourceProperty;
  10468. break;
  10469. case 1: // Texture
  10470. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  10471. break;
  10472. case 2: // Color3
  10473. case 3: // FresnelParameters
  10474. case 4: // Vector2
  10475. case 5: // Vector3
  10476. case 7: // Color Curves
  10477. case 10: // Quaternion
  10478. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  10479. break;
  10480. }
  10481. }
  10482. }
  10483. return destination;
  10484. };
  10485. function getDirectStore(target) {
  10486. var classKey = target.getClassName();
  10487. if (!__decoratorInitialStore[classKey]) {
  10488. __decoratorInitialStore[classKey] = {};
  10489. }
  10490. return __decoratorInitialStore[classKey];
  10491. }
  10492. /**
  10493. * Return the list of properties flagged as serializable
  10494. * @param target: host object
  10495. */
  10496. function getMergedStore(target) {
  10497. var classKey = target.getClassName();
  10498. if (__mergedStore[classKey]) {
  10499. return __mergedStore[classKey];
  10500. }
  10501. __mergedStore[classKey] = {};
  10502. var store = __mergedStore[classKey];
  10503. var currentTarget = target;
  10504. var currentKey = classKey;
  10505. while (currentKey) {
  10506. var initialStore = __decoratorInitialStore[currentKey];
  10507. for (var property in initialStore) {
  10508. store[property] = initialStore[property];
  10509. }
  10510. var parent_1 = void 0;
  10511. var done = false;
  10512. do {
  10513. parent_1 = Object.getPrototypeOf(currentTarget);
  10514. if (!parent_1.getClassName) {
  10515. done = true;
  10516. break;
  10517. }
  10518. if (parent_1.getClassName() !== currentKey) {
  10519. break;
  10520. }
  10521. currentTarget = parent_1;
  10522. } while (parent_1);
  10523. if (done) {
  10524. break;
  10525. }
  10526. currentKey = parent_1.getClassName();
  10527. currentTarget = parent_1;
  10528. }
  10529. return store;
  10530. }
  10531. function generateSerializableMember(type, sourceName) {
  10532. return function (target, propertyKey) {
  10533. var classStore = getDirectStore(target);
  10534. if (!classStore[propertyKey]) {
  10535. classStore[propertyKey] = { type: type, sourceName: sourceName };
  10536. }
  10537. };
  10538. }
  10539. function generateExpandMember(setCallback, targetKey) {
  10540. if (targetKey === void 0) { targetKey = null; }
  10541. return function (target, propertyKey) {
  10542. var key = targetKey || ("_" + propertyKey);
  10543. Object.defineProperty(target, propertyKey, {
  10544. get: function () {
  10545. return this[key];
  10546. },
  10547. set: function (value) {
  10548. if (this[key] === value) {
  10549. return;
  10550. }
  10551. this[key] = value;
  10552. target[setCallback].apply(this);
  10553. },
  10554. enumerable: true,
  10555. configurable: true
  10556. });
  10557. };
  10558. }
  10559. function expandToProperty(callback, targetKey) {
  10560. if (targetKey === void 0) { targetKey = null; }
  10561. return generateExpandMember(callback, targetKey);
  10562. }
  10563. BABYLON.expandToProperty = expandToProperty;
  10564. function serialize(sourceName) {
  10565. return generateSerializableMember(0, sourceName); // value member
  10566. }
  10567. BABYLON.serialize = serialize;
  10568. function serializeAsTexture(sourceName) {
  10569. return generateSerializableMember(1, sourceName); // texture member
  10570. }
  10571. BABYLON.serializeAsTexture = serializeAsTexture;
  10572. function serializeAsColor3(sourceName) {
  10573. return generateSerializableMember(2, sourceName); // color3 member
  10574. }
  10575. BABYLON.serializeAsColor3 = serializeAsColor3;
  10576. function serializeAsFresnelParameters(sourceName) {
  10577. return generateSerializableMember(3, sourceName); // fresnel parameters member
  10578. }
  10579. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  10580. function serializeAsVector2(sourceName) {
  10581. return generateSerializableMember(4, sourceName); // vector2 member
  10582. }
  10583. BABYLON.serializeAsVector2 = serializeAsVector2;
  10584. function serializeAsVector3(sourceName) {
  10585. return generateSerializableMember(5, sourceName); // vector3 member
  10586. }
  10587. BABYLON.serializeAsVector3 = serializeAsVector3;
  10588. function serializeAsMeshReference(sourceName) {
  10589. return generateSerializableMember(6, sourceName); // mesh reference member
  10590. }
  10591. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  10592. function serializeAsColorCurves(sourceName) {
  10593. return generateSerializableMember(7, sourceName); // color curves
  10594. }
  10595. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  10596. function serializeAsColor4(sourceName) {
  10597. return generateSerializableMember(8, sourceName); // color 4
  10598. }
  10599. BABYLON.serializeAsColor4 = serializeAsColor4;
  10600. function serializeAsImageProcessingConfiguration(sourceName) {
  10601. return generateSerializableMember(9, sourceName); // image processing
  10602. }
  10603. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  10604. function serializeAsQuaternion(sourceName) {
  10605. return generateSerializableMember(10, sourceName); // quaternion member
  10606. }
  10607. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  10608. /**
  10609. * Decorator used to define property that can be serialized as reference to a camera
  10610. * @param sourceName defines the name of the property to decorate
  10611. */
  10612. function serializeAsCameraReference(sourceName) {
  10613. return generateSerializableMember(11, sourceName); // camera reference member
  10614. }
  10615. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  10616. /**
  10617. * Class used to help serialization objects
  10618. */
  10619. var SerializationHelper = /** @class */ (function () {
  10620. function SerializationHelper() {
  10621. }
  10622. /**
  10623. * Static function used to serialized a specific entity
  10624. * @param entity defines the entity to serialize
  10625. * @param serializationObject defines the optional target obecjt where serialization data will be stored
  10626. * @returns a JSON compatible object representing the serialization of the entity
  10627. */
  10628. SerializationHelper.Serialize = function (entity, serializationObject) {
  10629. if (!serializationObject) {
  10630. serializationObject = {};
  10631. }
  10632. // Tags
  10633. if (BABYLON.Tags) {
  10634. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  10635. }
  10636. var serializedProperties = getMergedStore(entity);
  10637. // Properties
  10638. for (var property in serializedProperties) {
  10639. var propertyDescriptor = serializedProperties[property];
  10640. var targetPropertyName = propertyDescriptor.sourceName || property;
  10641. var propertyType = propertyDescriptor.type;
  10642. var sourceProperty = entity[property];
  10643. if (sourceProperty !== undefined && sourceProperty !== null) {
  10644. switch (propertyType) {
  10645. case 0: // Value
  10646. serializationObject[targetPropertyName] = sourceProperty;
  10647. break;
  10648. case 1: // Texture
  10649. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10650. break;
  10651. case 2: // Color3
  10652. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10653. break;
  10654. case 3: // FresnelParameters
  10655. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10656. break;
  10657. case 4: // Vector2
  10658. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10659. break;
  10660. case 5: // Vector3
  10661. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10662. break;
  10663. case 6: // Mesh reference
  10664. serializationObject[targetPropertyName] = sourceProperty.id;
  10665. break;
  10666. case 7: // Color Curves
  10667. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10668. break;
  10669. case 8: // Color 4
  10670. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10671. break;
  10672. case 9: // Image Processing
  10673. serializationObject[targetPropertyName] = sourceProperty.serialize();
  10674. break;
  10675. case 10: // Quaternion
  10676. serializationObject[targetPropertyName] = sourceProperty.asArray();
  10677. break;
  10678. case 11: // Camera reference
  10679. serializationObject[targetPropertyName] = sourceProperty.id;
  10680. break;
  10681. }
  10682. }
  10683. }
  10684. return serializationObject;
  10685. };
  10686. /**
  10687. * Creates a new entity from a serialization data object
  10688. * @param creationFunction defines a function used to instanciated the new entity
  10689. * @param source defines the source serialization data
  10690. * @param scene defines the hosting scene
  10691. * @param rootUrl defines the root url for resources
  10692. * @returns a new entity
  10693. */
  10694. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  10695. if (rootUrl === void 0) { rootUrl = null; }
  10696. var destination = creationFunction();
  10697. if (!rootUrl) {
  10698. rootUrl = "";
  10699. }
  10700. // Tags
  10701. if (BABYLON.Tags) {
  10702. BABYLON.Tags.AddTagsTo(destination, source.tags);
  10703. }
  10704. var classStore = getMergedStore(destination);
  10705. // Properties
  10706. for (var property in classStore) {
  10707. var propertyDescriptor = classStore[property];
  10708. var sourceProperty = source[propertyDescriptor.sourceName || property];
  10709. var propertyType = propertyDescriptor.type;
  10710. if (sourceProperty !== undefined && sourceProperty !== null) {
  10711. var dest = destination;
  10712. switch (propertyType) {
  10713. case 0: // Value
  10714. dest[property] = sourceProperty;
  10715. break;
  10716. case 1: // Texture
  10717. if (scene) {
  10718. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  10719. }
  10720. break;
  10721. case 2: // Color3
  10722. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  10723. break;
  10724. case 3: // FresnelParameters
  10725. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  10726. break;
  10727. case 4: // Vector2
  10728. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  10729. break;
  10730. case 5: // Vector3
  10731. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  10732. break;
  10733. case 6: // Mesh reference
  10734. if (scene) {
  10735. dest[property] = scene.getLastMeshByID(sourceProperty);
  10736. }
  10737. break;
  10738. case 7: // Color Curves
  10739. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  10740. break;
  10741. case 8: // Color 4
  10742. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  10743. break;
  10744. case 9: // Image Processing
  10745. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  10746. break;
  10747. case 10: // Quaternion
  10748. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  10749. break;
  10750. case 11: // Camera reference
  10751. if (scene) {
  10752. dest[property] = scene.getCameraByID(sourceProperty);
  10753. }
  10754. break;
  10755. }
  10756. }
  10757. }
  10758. return destination;
  10759. };
  10760. /**
  10761. * Clones an object
  10762. * @param creationFunction defines the function used to instanciate the new object
  10763. * @param source defines the source object
  10764. * @returns the cloned object
  10765. */
  10766. SerializationHelper.Clone = function (creationFunction, source) {
  10767. return _copySource(creationFunction, source, false);
  10768. };
  10769. /**
  10770. * Instanciates a new object based on a source one (some data will be shared between both object)
  10771. * @param creationFunction defines the function used to instanciate the new object
  10772. * @param source defines the source object
  10773. * @returns the new object
  10774. */
  10775. SerializationHelper.Instanciate = function (creationFunction, source) {
  10776. return _copySource(creationFunction, source, true);
  10777. };
  10778. return SerializationHelper;
  10779. }());
  10780. BABYLON.SerializationHelper = SerializationHelper;
  10781. })(BABYLON || (BABYLON = {}));
  10782. //# sourceMappingURL=decorators.js.map
  10783. var BABYLON;
  10784. (function (BABYLON) {
  10785. /**
  10786. * Wrapper class for promise with external resolve and reject.
  10787. */
  10788. var Deferred = /** @class */ (function () {
  10789. /**
  10790. * Constructor for this deferred object.
  10791. */
  10792. function Deferred() {
  10793. var _this = this;
  10794. this.promise = new Promise(function (resolve, reject) {
  10795. _this._resolve = resolve;
  10796. _this._reject = reject;
  10797. });
  10798. }
  10799. Object.defineProperty(Deferred.prototype, "resolve", {
  10800. /**
  10801. * The resolve method of the promise associated with this deferred object.
  10802. */
  10803. get: function () {
  10804. return this._resolve;
  10805. },
  10806. enumerable: true,
  10807. configurable: true
  10808. });
  10809. Object.defineProperty(Deferred.prototype, "reject", {
  10810. /**
  10811. * The reject method of the promise associated with this deferred object.
  10812. */
  10813. get: function () {
  10814. return this._reject;
  10815. },
  10816. enumerable: true,
  10817. configurable: true
  10818. });
  10819. return Deferred;
  10820. }());
  10821. BABYLON.Deferred = Deferred;
  10822. })(BABYLON || (BABYLON = {}));
  10823. //# sourceMappingURL=deferred.js.map
  10824. var BABYLON;
  10825. (function (BABYLON) {
  10826. /**
  10827. * A class serves as a medium between the observable and its observers
  10828. */
  10829. var EventState = /** @class */ (function () {
  10830. /**
  10831. * Create a new EventState
  10832. * @param mask defines the mask associated with this state
  10833. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  10834. * @param target defines the original target of the state
  10835. * @param currentTarget defines the current target of the state
  10836. */
  10837. function EventState(mask, skipNextObservers, target, currentTarget) {
  10838. if (skipNextObservers === void 0) { skipNextObservers = false; }
  10839. this.initalize(mask, skipNextObservers, target, currentTarget);
  10840. }
  10841. /**
  10842. * Initialize the current event state
  10843. * @param mask defines the mask associated with this state
  10844. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  10845. * @param target defines the original target of the state
  10846. * @param currentTarget defines the current target of the state
  10847. * @returns the current event state
  10848. */
  10849. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  10850. if (skipNextObservers === void 0) { skipNextObservers = false; }
  10851. this.mask = mask;
  10852. this.skipNextObservers = skipNextObservers;
  10853. this.target = target;
  10854. this.currentTarget = currentTarget;
  10855. return this;
  10856. };
  10857. return EventState;
  10858. }());
  10859. BABYLON.EventState = EventState;
  10860. /**
  10861. * Represent an Observer registered to a given Observable object.
  10862. */
  10863. var Observer = /** @class */ (function () {
  10864. /**
  10865. * Creates a new observer
  10866. * @param callback defines the callback to call when the observer is notified
  10867. * @param mask defines the mask of the observer (used to filter notifications)
  10868. * @param scope defines the current scope used to restore the JS context
  10869. */
  10870. function Observer(
  10871. /**
  10872. * Defines the callback to call when the observer is notified
  10873. */
  10874. callback,
  10875. /**
  10876. * Defines the mask of the observer (used to filter notifications)
  10877. */
  10878. mask,
  10879. /**
  10880. * Defines the current scope used to restore the JS context
  10881. */
  10882. scope) {
  10883. if (scope === void 0) { scope = null; }
  10884. this.callback = callback;
  10885. this.mask = mask;
  10886. this.scope = scope;
  10887. /** @hidden */
  10888. this._willBeUnregistered = false;
  10889. /**
  10890. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  10891. */
  10892. this.unregisterOnNextCall = false;
  10893. }
  10894. return Observer;
  10895. }());
  10896. BABYLON.Observer = Observer;
  10897. /**
  10898. * Represent a list of observers registered to multiple Observables object.
  10899. */
  10900. var MultiObserver = /** @class */ (function () {
  10901. function MultiObserver() {
  10902. }
  10903. /**
  10904. * Release associated resources
  10905. */
  10906. MultiObserver.prototype.dispose = function () {
  10907. if (this._observers && this._observables) {
  10908. for (var index = 0; index < this._observers.length; index++) {
  10909. this._observables[index].remove(this._observers[index]);
  10910. }
  10911. }
  10912. this._observers = null;
  10913. this._observables = null;
  10914. };
  10915. /**
  10916. * Raise a callback when one of the observable will notify
  10917. * @param observables defines a list of observables to watch
  10918. * @param callback defines the callback to call on notification
  10919. * @param mask defines the mask used to filter notifications
  10920. * @param scope defines the current scope used to restore the JS context
  10921. * @returns the new MultiObserver
  10922. */
  10923. MultiObserver.Watch = function (observables, callback, mask, scope) {
  10924. if (mask === void 0) { mask = -1; }
  10925. if (scope === void 0) { scope = null; }
  10926. var result = new MultiObserver();
  10927. result._observers = new Array();
  10928. result._observables = observables;
  10929. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  10930. var observable = observables_1[_i];
  10931. var observer = observable.add(callback, mask, false, scope);
  10932. if (observer) {
  10933. result._observers.push(observer);
  10934. }
  10935. }
  10936. return result;
  10937. };
  10938. return MultiObserver;
  10939. }());
  10940. BABYLON.MultiObserver = MultiObserver;
  10941. /**
  10942. * The Observable class is a simple implementation of the Observable pattern.
  10943. *
  10944. * 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.
  10945. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  10946. * 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).
  10947. * 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.
  10948. */
  10949. var Observable = /** @class */ (function () {
  10950. /**
  10951. * Creates a new observable
  10952. * @param onObserverAdded defines a callback to call when a new observer is added
  10953. */
  10954. function Observable(onObserverAdded) {
  10955. this._observers = new Array();
  10956. this._eventState = new EventState(0);
  10957. if (onObserverAdded) {
  10958. this._onObserverAdded = onObserverAdded;
  10959. }
  10960. }
  10961. /**
  10962. * Create a new Observer with the specified callback
  10963. * @param callback the callback that will be executed for that Observer
  10964. * @param mask the mask used to filter observers
  10965. * @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.
  10966. * @param scope optional scope for the callback to be called from
  10967. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  10968. * @returns the new observer created for the callback
  10969. */
  10970. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  10971. if (mask === void 0) { mask = -1; }
  10972. if (insertFirst === void 0) { insertFirst = false; }
  10973. if (scope === void 0) { scope = null; }
  10974. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  10975. if (!callback) {
  10976. return null;
  10977. }
  10978. var observer = new Observer(callback, mask, scope);
  10979. observer.unregisterOnNextCall = unregisterOnFirstCall;
  10980. if (insertFirst) {
  10981. this._observers.unshift(observer);
  10982. }
  10983. else {
  10984. this._observers.push(observer);
  10985. }
  10986. if (this._onObserverAdded) {
  10987. this._onObserverAdded(observer);
  10988. }
  10989. return observer;
  10990. };
  10991. /**
  10992. * Create a new Observer with the specified callback and unregisters after the next notification
  10993. * @param callback the callback that will be executed for that Observer
  10994. * @returns the new observer created for the callback
  10995. */
  10996. Observable.prototype.addOnce = function (callback) {
  10997. return this.add(callback, undefined, undefined, undefined, true);
  10998. };
  10999. /**
  11000. * Remove an Observer from the Observable object
  11001. * @param observer the instance of the Observer to remove
  11002. * @returns false if it doesn't belong to this Observable
  11003. */
  11004. Observable.prototype.remove = function (observer) {
  11005. if (!observer) {
  11006. return false;
  11007. }
  11008. var index = this._observers.indexOf(observer);
  11009. if (index !== -1) {
  11010. this._deferUnregister(observer);
  11011. return true;
  11012. }
  11013. return false;
  11014. };
  11015. /**
  11016. * Remove a callback from the Observable object
  11017. * @param callback the callback to remove
  11018. * @param scope optional scope. If used only the callbacks with this scope will be removed
  11019. * @returns false if it doesn't belong to this Observable
  11020. */
  11021. Observable.prototype.removeCallback = function (callback, scope) {
  11022. for (var index = 0; index < this._observers.length; index++) {
  11023. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  11024. this._deferUnregister(this._observers[index]);
  11025. return true;
  11026. }
  11027. }
  11028. return false;
  11029. };
  11030. Observable.prototype._deferUnregister = function (observer) {
  11031. var _this = this;
  11032. observer.unregisterOnNextCall = false;
  11033. observer._willBeUnregistered = true;
  11034. BABYLON.Tools.SetImmediate(function () {
  11035. _this._remove(observer);
  11036. });
  11037. };
  11038. // This should only be called when not iterating over _observers to avoid callback skipping.
  11039. // Removes an observer from the _observer Array.
  11040. Observable.prototype._remove = function (observer) {
  11041. if (!observer) {
  11042. return false;
  11043. }
  11044. var index = this._observers.indexOf(observer);
  11045. if (index !== -1) {
  11046. this._observers.splice(index, 1);
  11047. return true;
  11048. }
  11049. return false;
  11050. };
  11051. /**
  11052. * Notify all Observers by calling their respective callback with the given data
  11053. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  11054. * @param eventData defines the data to send to all observers
  11055. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  11056. * @param target defines the original target of the state
  11057. * @param currentTarget defines the current target of the state
  11058. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  11059. */
  11060. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  11061. if (mask === void 0) { mask = -1; }
  11062. if (!this._observers.length) {
  11063. return true;
  11064. }
  11065. var state = this._eventState;
  11066. state.mask = mask;
  11067. state.target = target;
  11068. state.currentTarget = currentTarget;
  11069. state.skipNextObservers = false;
  11070. state.lastReturnValue = eventData;
  11071. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  11072. var obs = _a[_i];
  11073. if (obs._willBeUnregistered) {
  11074. continue;
  11075. }
  11076. if (obs.mask & mask) {
  11077. if (obs.scope) {
  11078. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  11079. }
  11080. else {
  11081. state.lastReturnValue = obs.callback(eventData, state);
  11082. }
  11083. if (obs.unregisterOnNextCall) {
  11084. this._deferUnregister(obs);
  11085. }
  11086. }
  11087. if (state.skipNextObservers) {
  11088. return false;
  11089. }
  11090. }
  11091. return true;
  11092. };
  11093. /**
  11094. * Calling this will execute each callback, expecting it to be a promise or return a value.
  11095. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  11096. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  11097. * and it is crucial that all callbacks will be executed.
  11098. * The order of the callbacks is kept, callbacks are not executed parallel.
  11099. *
  11100. * @param eventData The data to be sent to each callback
  11101. * @param mask is used to filter observers defaults to -1
  11102. * @param target defines the callback target (see EventState)
  11103. * @param currentTarget defines he current object in the bubbling phase
  11104. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  11105. */
  11106. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  11107. var _this = this;
  11108. if (mask === void 0) { mask = -1; }
  11109. // create an empty promise
  11110. var p = Promise.resolve(eventData);
  11111. // no observers? return this promise.
  11112. if (!this._observers.length) {
  11113. return p;
  11114. }
  11115. var state = this._eventState;
  11116. state.mask = mask;
  11117. state.target = target;
  11118. state.currentTarget = currentTarget;
  11119. state.skipNextObservers = false;
  11120. // execute one callback after another (not using Promise.all, the order is important)
  11121. this._observers.forEach(function (obs) {
  11122. if (state.skipNextObservers) {
  11123. return;
  11124. }
  11125. if (obs._willBeUnregistered) {
  11126. return;
  11127. }
  11128. if (obs.mask & mask) {
  11129. if (obs.scope) {
  11130. p = p.then(function (lastReturnedValue) {
  11131. state.lastReturnValue = lastReturnedValue;
  11132. return obs.callback.apply(obs.scope, [eventData, state]);
  11133. });
  11134. }
  11135. else {
  11136. p = p.then(function (lastReturnedValue) {
  11137. state.lastReturnValue = lastReturnedValue;
  11138. return obs.callback(eventData, state);
  11139. });
  11140. }
  11141. if (obs.unregisterOnNextCall) {
  11142. _this._deferUnregister(obs);
  11143. }
  11144. }
  11145. });
  11146. // return the eventData
  11147. return p.then(function () { return eventData; });
  11148. };
  11149. /**
  11150. * Notify a specific observer
  11151. * @param observer defines the observer to notify
  11152. * @param eventData defines the data to be sent to each callback
  11153. * @param mask is used to filter observers defaults to -1
  11154. */
  11155. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  11156. if (mask === void 0) { mask = -1; }
  11157. var state = this._eventState;
  11158. state.mask = mask;
  11159. state.skipNextObservers = false;
  11160. observer.callback(eventData, state);
  11161. };
  11162. /**
  11163. * Gets a boolean indicating if the observable has at least one observer
  11164. * @returns true is the Observable has at least one Observer registered
  11165. */
  11166. Observable.prototype.hasObservers = function () {
  11167. return this._observers.length > 0;
  11168. };
  11169. /**
  11170. * Clear the list of observers
  11171. */
  11172. Observable.prototype.clear = function () {
  11173. this._observers = new Array();
  11174. this._onObserverAdded = null;
  11175. };
  11176. /**
  11177. * Clone the current observable
  11178. * @returns a new observable
  11179. */
  11180. Observable.prototype.clone = function () {
  11181. var result = new Observable();
  11182. result._observers = this._observers.slice(0);
  11183. return result;
  11184. };
  11185. /**
  11186. * Does this observable handles observer registered with a given mask
  11187. * @param mask defines the mask to be tested
  11188. * @return whether or not one observer registered with the given mask is handeled
  11189. **/
  11190. Observable.prototype.hasSpecificMask = function (mask) {
  11191. if (mask === void 0) { mask = -1; }
  11192. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  11193. var obs = _a[_i];
  11194. if (obs.mask & mask || obs.mask === mask) {
  11195. return true;
  11196. }
  11197. }
  11198. return false;
  11199. };
  11200. return Observable;
  11201. }());
  11202. BABYLON.Observable = Observable;
  11203. })(BABYLON || (BABYLON = {}));
  11204. //# sourceMappingURL=observable.js.map
  11205. var BABYLON;
  11206. (function (BABYLON) {
  11207. /**
  11208. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  11209. */
  11210. var SmartArray = /** @class */ (function () {
  11211. /**
  11212. * Instantiates a Smart Array.
  11213. * @param capacity defines the default capacity of the array.
  11214. */
  11215. function SmartArray(capacity) {
  11216. /**
  11217. * The active length of the array.
  11218. */
  11219. this.length = 0;
  11220. this.data = new Array(capacity);
  11221. this._id = SmartArray._GlobalId++;
  11222. }
  11223. /**
  11224. * Pushes a value at the end of the active data.
  11225. * @param value defines the object to push in the array.
  11226. */
  11227. SmartArray.prototype.push = function (value) {
  11228. this.data[this.length++] = value;
  11229. if (this.length > this.data.length) {
  11230. this.data.length *= 2;
  11231. }
  11232. };
  11233. /**
  11234. * Iterates over the active data and apply the lambda to them.
  11235. * @param func defines the action to apply on each value.
  11236. */
  11237. SmartArray.prototype.forEach = function (func) {
  11238. for (var index = 0; index < this.length; index++) {
  11239. func(this.data[index]);
  11240. }
  11241. };
  11242. /**
  11243. * Sorts the full sets of data.
  11244. * @param compareFn defines the comparison function to apply.
  11245. */
  11246. SmartArray.prototype.sort = function (compareFn) {
  11247. this.data.sort(compareFn);
  11248. };
  11249. /**
  11250. * Resets the active data to an empty array.
  11251. */
  11252. SmartArray.prototype.reset = function () {
  11253. this.length = 0;
  11254. };
  11255. /**
  11256. * Releases all the data from the array as well as the array.
  11257. */
  11258. SmartArray.prototype.dispose = function () {
  11259. this.reset();
  11260. if (this.data) {
  11261. this.data.length = 0;
  11262. this.data = [];
  11263. }
  11264. };
  11265. /**
  11266. * Concats the active data with a given array.
  11267. * @param array defines the data to concatenate with.
  11268. */
  11269. SmartArray.prototype.concat = function (array) {
  11270. if (array.length === 0) {
  11271. return;
  11272. }
  11273. if (this.length + array.length > this.data.length) {
  11274. this.data.length = (this.length + array.length) * 2;
  11275. }
  11276. for (var index = 0; index < array.length; index++) {
  11277. this.data[this.length++] = (array.data || array)[index];
  11278. }
  11279. };
  11280. /**
  11281. * Returns the position of a value in the active data.
  11282. * @param value defines the value to find the index for
  11283. * @returns the index if found in the active data otherwise -1
  11284. */
  11285. SmartArray.prototype.indexOf = function (value) {
  11286. var position = this.data.indexOf(value);
  11287. if (position >= this.length) {
  11288. return -1;
  11289. }
  11290. return position;
  11291. };
  11292. /**
  11293. * Returns whether an element is part of the active data.
  11294. * @param value defines the value to look for
  11295. * @returns true if found in the active data otherwise false
  11296. */
  11297. SmartArray.prototype.contains = function (value) {
  11298. return this.indexOf(value) !== -1;
  11299. };
  11300. // Statics
  11301. SmartArray._GlobalId = 0;
  11302. return SmartArray;
  11303. }());
  11304. BABYLON.SmartArray = SmartArray;
  11305. /**
  11306. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  11307. * The data in this array can only be present once
  11308. */
  11309. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  11310. __extends(SmartArrayNoDuplicate, _super);
  11311. function SmartArrayNoDuplicate() {
  11312. var _this = _super !== null && _super.apply(this, arguments) || this;
  11313. _this._duplicateId = 0;
  11314. return _this;
  11315. }
  11316. /**
  11317. * Pushes a value at the end of the active data.
  11318. * THIS DOES NOT PREVENT DUPPLICATE DATA
  11319. * @param value defines the object to push in the array.
  11320. */
  11321. SmartArrayNoDuplicate.prototype.push = function (value) {
  11322. _super.prototype.push.call(this, value);
  11323. if (!value.__smartArrayFlags) {
  11324. value.__smartArrayFlags = {};
  11325. }
  11326. value.__smartArrayFlags[this._id] = this._duplicateId;
  11327. };
  11328. /**
  11329. * Pushes a value at the end of the active data.
  11330. * If the data is already present, it won t be added again
  11331. * @param value defines the object to push in the array.
  11332. * @returns true if added false if it was already present
  11333. */
  11334. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  11335. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  11336. return false;
  11337. }
  11338. this.push(value);
  11339. return true;
  11340. };
  11341. /**
  11342. * Resets the active data to an empty array.
  11343. */
  11344. SmartArrayNoDuplicate.prototype.reset = function () {
  11345. _super.prototype.reset.call(this);
  11346. this._duplicateId++;
  11347. };
  11348. /**
  11349. * Concats the active data with a given array.
  11350. * This ensures no dupplicate will be present in the result.
  11351. * @param array defines the data to concatenate with.
  11352. */
  11353. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  11354. if (array.length === 0) {
  11355. return;
  11356. }
  11357. if (this.length + array.length > this.data.length) {
  11358. this.data.length = (this.length + array.length) * 2;
  11359. }
  11360. for (var index = 0; index < array.length; index++) {
  11361. var item = (array.data || array)[index];
  11362. this.pushNoDuplicate(item);
  11363. }
  11364. };
  11365. return SmartArrayNoDuplicate;
  11366. }(SmartArray));
  11367. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  11368. })(BABYLON || (BABYLON = {}));
  11369. //# sourceMappingURL=smartArray.js.map
  11370. var BABYLON;
  11371. (function (BABYLON) {
  11372. var PromiseStates;
  11373. (function (PromiseStates) {
  11374. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  11375. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  11376. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  11377. })(PromiseStates || (PromiseStates = {}));
  11378. var FulFillmentAgregator = /** @class */ (function () {
  11379. function FulFillmentAgregator() {
  11380. this.count = 0;
  11381. this.target = 0;
  11382. this.results = [];
  11383. }
  11384. return FulFillmentAgregator;
  11385. }());
  11386. var InternalPromise = /** @class */ (function () {
  11387. function InternalPromise(resolver) {
  11388. var _this = this;
  11389. this._state = PromiseStates.Pending;
  11390. this._children = new Array();
  11391. this._rejectWasConsumed = false;
  11392. if (!resolver) {
  11393. return;
  11394. }
  11395. try {
  11396. resolver(function (value) {
  11397. _this._resolve(value);
  11398. }, function (reason) {
  11399. _this._reject(reason);
  11400. });
  11401. }
  11402. catch (e) {
  11403. this._reject(e);
  11404. }
  11405. }
  11406. Object.defineProperty(InternalPromise.prototype, "_result", {
  11407. get: function () {
  11408. return this._resultValue;
  11409. },
  11410. set: function (value) {
  11411. this._resultValue = value;
  11412. if (this._parent && this._parent._result === undefined) {
  11413. this._parent._result = value;
  11414. }
  11415. },
  11416. enumerable: true,
  11417. configurable: true
  11418. });
  11419. InternalPromise.prototype.catch = function (onRejected) {
  11420. return this.then(undefined, onRejected);
  11421. };
  11422. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  11423. var _this = this;
  11424. var newPromise = new InternalPromise();
  11425. newPromise._onFulfilled = onFulfilled;
  11426. newPromise._onRejected = onRejected;
  11427. // Composition
  11428. this._children.push(newPromise);
  11429. newPromise._parent = this;
  11430. if (this._state !== PromiseStates.Pending) {
  11431. BABYLON.Tools.SetImmediate(function () {
  11432. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  11433. var returnedValue = newPromise._resolve(_this._result);
  11434. if (returnedValue !== undefined && returnedValue !== null) {
  11435. if (returnedValue._state !== undefined) {
  11436. var returnedPromise = returnedValue;
  11437. newPromise._children.push(returnedPromise);
  11438. returnedPromise._parent = newPromise;
  11439. newPromise = returnedPromise;
  11440. }
  11441. else {
  11442. newPromise._result = returnedValue;
  11443. }
  11444. }
  11445. }
  11446. else {
  11447. newPromise._reject(_this._reason);
  11448. }
  11449. });
  11450. }
  11451. return newPromise;
  11452. };
  11453. InternalPromise.prototype._moveChildren = function (children) {
  11454. var _this = this;
  11455. var _a;
  11456. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  11457. this._children.forEach(function (child) {
  11458. child._parent = _this;
  11459. });
  11460. if (this._state === PromiseStates.Fulfilled) {
  11461. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  11462. var child = _b[_i];
  11463. child._resolve(this._result);
  11464. }
  11465. }
  11466. else if (this._state === PromiseStates.Rejected) {
  11467. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  11468. var child = _d[_c];
  11469. child._reject(this._reason);
  11470. }
  11471. }
  11472. };
  11473. InternalPromise.prototype._resolve = function (value) {
  11474. try {
  11475. this._state = PromiseStates.Fulfilled;
  11476. var returnedValue = null;
  11477. if (this._onFulfilled) {
  11478. returnedValue = this._onFulfilled(value);
  11479. }
  11480. if (returnedValue !== undefined && returnedValue !== null) {
  11481. if (returnedValue._state !== undefined) {
  11482. // Transmit children
  11483. var returnedPromise = returnedValue;
  11484. returnedPromise._parent = this;
  11485. returnedPromise._moveChildren(this._children);
  11486. value = returnedPromise._result;
  11487. }
  11488. else {
  11489. value = returnedValue;
  11490. }
  11491. }
  11492. this._result = value;
  11493. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11494. var child = _a[_i];
  11495. child._resolve(value);
  11496. }
  11497. this._children.length = 0;
  11498. delete this._onFulfilled;
  11499. delete this._onRejected;
  11500. }
  11501. catch (e) {
  11502. this._reject(e, true);
  11503. }
  11504. };
  11505. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  11506. if (onLocalThrow === void 0) { onLocalThrow = false; }
  11507. this._state = PromiseStates.Rejected;
  11508. this._reason = reason;
  11509. if (this._onRejected && !onLocalThrow) {
  11510. try {
  11511. this._onRejected(reason);
  11512. this._rejectWasConsumed = true;
  11513. }
  11514. catch (e) {
  11515. reason = e;
  11516. }
  11517. }
  11518. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11519. var child = _a[_i];
  11520. if (this._rejectWasConsumed) {
  11521. child._resolve(null);
  11522. }
  11523. else {
  11524. child._reject(reason);
  11525. }
  11526. }
  11527. this._children.length = 0;
  11528. delete this._onFulfilled;
  11529. delete this._onRejected;
  11530. };
  11531. InternalPromise.resolve = function (value) {
  11532. var newPromise = new InternalPromise();
  11533. newPromise._resolve(value);
  11534. return newPromise;
  11535. };
  11536. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  11537. promise.then(function (value) {
  11538. agregator.results[index] = value;
  11539. agregator.count++;
  11540. if (agregator.count === agregator.target) {
  11541. agregator.rootPromise._resolve(agregator.results);
  11542. }
  11543. return null;
  11544. }, function (reason) {
  11545. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  11546. agregator.rootPromise._reject(reason);
  11547. }
  11548. });
  11549. };
  11550. InternalPromise.all = function (promises) {
  11551. var newPromise = new InternalPromise();
  11552. var agregator = new FulFillmentAgregator();
  11553. agregator.target = promises.length;
  11554. agregator.rootPromise = newPromise;
  11555. if (promises.length) {
  11556. for (var index = 0; index < promises.length; index++) {
  11557. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  11558. }
  11559. }
  11560. else {
  11561. newPromise._resolve([]);
  11562. }
  11563. return newPromise;
  11564. };
  11565. InternalPromise.race = function (promises) {
  11566. var newPromise = new InternalPromise();
  11567. if (promises.length) {
  11568. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  11569. var promise = promises_1[_i];
  11570. promise.then(function (value) {
  11571. if (newPromise) {
  11572. newPromise._resolve(value);
  11573. newPromise = null;
  11574. }
  11575. return null;
  11576. }, function (reason) {
  11577. if (newPromise) {
  11578. newPromise._reject(reason);
  11579. newPromise = null;
  11580. }
  11581. });
  11582. }
  11583. }
  11584. return newPromise;
  11585. };
  11586. return InternalPromise;
  11587. }());
  11588. /**
  11589. * Helper class that provides a small promise polyfill
  11590. */
  11591. var PromisePolyfill = /** @class */ (function () {
  11592. function PromisePolyfill() {
  11593. }
  11594. /**
  11595. * Static function used to check if the polyfill is required
  11596. * If this is the case then the function will inject the polyfill to window.Promise
  11597. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  11598. */
  11599. PromisePolyfill.Apply = function (force) {
  11600. if (force === void 0) { force = false; }
  11601. if (force || typeof Promise === 'undefined') {
  11602. var root = window;
  11603. root.Promise = InternalPromise;
  11604. }
  11605. };
  11606. return PromisePolyfill;
  11607. }());
  11608. BABYLON.PromisePolyfill = PromisePolyfill;
  11609. })(BABYLON || (BABYLON = {}));
  11610. //# sourceMappingURL=promise.js.map
  11611. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  11612. var BABYLON;
  11613. (function (BABYLON) {
  11614. /**
  11615. * Helper class to push actions to a pool of workers.
  11616. */
  11617. var WorkerPool = /** @class */ (function () {
  11618. /**
  11619. * Constructor
  11620. * @param workers Array of workers to use for actions
  11621. */
  11622. function WorkerPool(workers) {
  11623. this._pendingActions = new Array();
  11624. this._workerInfos = workers.map(function (worker) { return ({
  11625. worker: worker,
  11626. active: false
  11627. }); });
  11628. }
  11629. /**
  11630. * Terminates all workers and clears any pending actions.
  11631. */
  11632. WorkerPool.prototype.dispose = function () {
  11633. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11634. var workerInfo = _a[_i];
  11635. workerInfo.worker.terminate();
  11636. }
  11637. delete this._workerInfos;
  11638. delete this._pendingActions;
  11639. };
  11640. /**
  11641. * Pushes an action to the worker pool. If all the workers are active, the action will be
  11642. * pended until a worker has completed its action.
  11643. * @param action The action to perform. Call onComplete when the action is complete.
  11644. */
  11645. WorkerPool.prototype.push = function (action) {
  11646. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11647. var workerInfo = _a[_i];
  11648. if (!workerInfo.active) {
  11649. this._execute(workerInfo, action);
  11650. return;
  11651. }
  11652. }
  11653. this._pendingActions.push(action);
  11654. };
  11655. WorkerPool.prototype._execute = function (workerInfo, action) {
  11656. var _this = this;
  11657. workerInfo.active = true;
  11658. action(workerInfo.worker, function () {
  11659. workerInfo.active = false;
  11660. var nextAction = _this._pendingActions.shift();
  11661. if (nextAction) {
  11662. _this._execute(workerInfo, nextAction);
  11663. }
  11664. });
  11665. };
  11666. return WorkerPool;
  11667. }());
  11668. BABYLON.WorkerPool = WorkerPool;
  11669. })(BABYLON || (BABYLON = {}));
  11670. //# sourceMappingURL=workerPool.js.map
  11671. var BABYLON;
  11672. (function (BABYLON) {
  11673. /**
  11674. * @hidden
  11675. **/
  11676. var _AlphaState = /** @class */ (function () {
  11677. /**
  11678. * Initializes the state.
  11679. */
  11680. function _AlphaState() {
  11681. this._isAlphaBlendDirty = false;
  11682. this._isBlendFunctionParametersDirty = false;
  11683. this._isBlendEquationParametersDirty = false;
  11684. this._isBlendConstantsDirty = false;
  11685. this._alphaBlend = false;
  11686. this._blendFunctionParameters = new Array(4);
  11687. this._blendEquationParameters = new Array(2);
  11688. this._blendConstants = new Array(4);
  11689. this.reset();
  11690. }
  11691. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  11692. get: function () {
  11693. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  11694. },
  11695. enumerable: true,
  11696. configurable: true
  11697. });
  11698. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  11699. get: function () {
  11700. return this._alphaBlend;
  11701. },
  11702. set: function (value) {
  11703. if (this._alphaBlend === value) {
  11704. return;
  11705. }
  11706. this._alphaBlend = value;
  11707. this._isAlphaBlendDirty = true;
  11708. },
  11709. enumerable: true,
  11710. configurable: true
  11711. });
  11712. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  11713. if (this._blendConstants[0] === r &&
  11714. this._blendConstants[1] === g &&
  11715. this._blendConstants[2] === b &&
  11716. this._blendConstants[3] === a) {
  11717. return;
  11718. }
  11719. this._blendConstants[0] = r;
  11720. this._blendConstants[1] = g;
  11721. this._blendConstants[2] = b;
  11722. this._blendConstants[3] = a;
  11723. this._isBlendConstantsDirty = true;
  11724. };
  11725. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  11726. if (this._blendFunctionParameters[0] === value0 &&
  11727. this._blendFunctionParameters[1] === value1 &&
  11728. this._blendFunctionParameters[2] === value2 &&
  11729. this._blendFunctionParameters[3] === value3) {
  11730. return;
  11731. }
  11732. this._blendFunctionParameters[0] = value0;
  11733. this._blendFunctionParameters[1] = value1;
  11734. this._blendFunctionParameters[2] = value2;
  11735. this._blendFunctionParameters[3] = value3;
  11736. this._isBlendFunctionParametersDirty = true;
  11737. };
  11738. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  11739. if (this._blendEquationParameters[0] === rgb &&
  11740. this._blendEquationParameters[1] === alpha) {
  11741. return;
  11742. }
  11743. this._blendEquationParameters[0] = rgb;
  11744. this._blendEquationParameters[1] = alpha;
  11745. this._isBlendEquationParametersDirty = true;
  11746. };
  11747. _AlphaState.prototype.reset = function () {
  11748. this._alphaBlend = false;
  11749. this._blendFunctionParameters[0] = null;
  11750. this._blendFunctionParameters[1] = null;
  11751. this._blendFunctionParameters[2] = null;
  11752. this._blendFunctionParameters[3] = null;
  11753. this._blendEquationParameters[0] = null;
  11754. this._blendEquationParameters[1] = null;
  11755. this._blendConstants[0] = null;
  11756. this._blendConstants[1] = null;
  11757. this._blendConstants[2] = null;
  11758. this._blendConstants[3] = null;
  11759. this._isAlphaBlendDirty = true;
  11760. this._isBlendFunctionParametersDirty = false;
  11761. this._isBlendEquationParametersDirty = false;
  11762. this._isBlendConstantsDirty = false;
  11763. };
  11764. _AlphaState.prototype.apply = function (gl) {
  11765. if (!this.isDirty) {
  11766. return;
  11767. }
  11768. // Alpha blend
  11769. if (this._isAlphaBlendDirty) {
  11770. if (this._alphaBlend) {
  11771. gl.enable(gl.BLEND);
  11772. }
  11773. else {
  11774. gl.disable(gl.BLEND);
  11775. }
  11776. this._isAlphaBlendDirty = false;
  11777. }
  11778. // Alpha function
  11779. if (this._isBlendFunctionParametersDirty) {
  11780. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  11781. this._isBlendFunctionParametersDirty = false;
  11782. }
  11783. // Alpha equation
  11784. if (this._isBlendEquationParametersDirty) {
  11785. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  11786. this._isBlendEquationParametersDirty = false;
  11787. }
  11788. // Constants
  11789. if (this._isBlendConstantsDirty) {
  11790. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  11791. this._isBlendConstantsDirty = false;
  11792. }
  11793. };
  11794. return _AlphaState;
  11795. }());
  11796. BABYLON._AlphaState = _AlphaState;
  11797. })(BABYLON || (BABYLON = {}));
  11798. //# sourceMappingURL=alphaCullingState.js.map
  11799. var BABYLON;
  11800. (function (BABYLON) {
  11801. /**
  11802. * @hidden
  11803. **/
  11804. var _DepthCullingState = /** @class */ (function () {
  11805. /**
  11806. * Initializes the state.
  11807. */
  11808. function _DepthCullingState() {
  11809. this._isDepthTestDirty = false;
  11810. this._isDepthMaskDirty = false;
  11811. this._isDepthFuncDirty = false;
  11812. this._isCullFaceDirty = false;
  11813. this._isCullDirty = false;
  11814. this._isZOffsetDirty = false;
  11815. this._isFrontFaceDirty = false;
  11816. this.reset();
  11817. }
  11818. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  11819. get: function () {
  11820. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  11821. },
  11822. enumerable: true,
  11823. configurable: true
  11824. });
  11825. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  11826. get: function () {
  11827. return this._zOffset;
  11828. },
  11829. set: function (value) {
  11830. if (this._zOffset === value) {
  11831. return;
  11832. }
  11833. this._zOffset = value;
  11834. this._isZOffsetDirty = true;
  11835. },
  11836. enumerable: true,
  11837. configurable: true
  11838. });
  11839. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  11840. get: function () {
  11841. return this._cullFace;
  11842. },
  11843. set: function (value) {
  11844. if (this._cullFace === value) {
  11845. return;
  11846. }
  11847. this._cullFace = value;
  11848. this._isCullFaceDirty = true;
  11849. },
  11850. enumerable: true,
  11851. configurable: true
  11852. });
  11853. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11854. get: function () {
  11855. return this._cull;
  11856. },
  11857. set: function (value) {
  11858. if (this._cull === value) {
  11859. return;
  11860. }
  11861. this._cull = value;
  11862. this._isCullDirty = true;
  11863. },
  11864. enumerable: true,
  11865. configurable: true
  11866. });
  11867. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11868. get: function () {
  11869. return this._depthFunc;
  11870. },
  11871. set: function (value) {
  11872. if (this._depthFunc === value) {
  11873. return;
  11874. }
  11875. this._depthFunc = value;
  11876. this._isDepthFuncDirty = true;
  11877. },
  11878. enumerable: true,
  11879. configurable: true
  11880. });
  11881. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11882. get: function () {
  11883. return this._depthMask;
  11884. },
  11885. set: function (value) {
  11886. if (this._depthMask === value) {
  11887. return;
  11888. }
  11889. this._depthMask = value;
  11890. this._isDepthMaskDirty = true;
  11891. },
  11892. enumerable: true,
  11893. configurable: true
  11894. });
  11895. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11896. get: function () {
  11897. return this._depthTest;
  11898. },
  11899. set: function (value) {
  11900. if (this._depthTest === value) {
  11901. return;
  11902. }
  11903. this._depthTest = value;
  11904. this._isDepthTestDirty = true;
  11905. },
  11906. enumerable: true,
  11907. configurable: true
  11908. });
  11909. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11910. get: function () {
  11911. return this._frontFace;
  11912. },
  11913. set: function (value) {
  11914. if (this._frontFace === value) {
  11915. return;
  11916. }
  11917. this._frontFace = value;
  11918. this._isFrontFaceDirty = true;
  11919. },
  11920. enumerable: true,
  11921. configurable: true
  11922. });
  11923. _DepthCullingState.prototype.reset = function () {
  11924. this._depthMask = true;
  11925. this._depthTest = true;
  11926. this._depthFunc = null;
  11927. this._cullFace = null;
  11928. this._cull = null;
  11929. this._zOffset = 0;
  11930. this._frontFace = null;
  11931. this._isDepthTestDirty = true;
  11932. this._isDepthMaskDirty = true;
  11933. this._isDepthFuncDirty = false;
  11934. this._isCullFaceDirty = false;
  11935. this._isCullDirty = false;
  11936. this._isZOffsetDirty = false;
  11937. this._isFrontFaceDirty = false;
  11938. };
  11939. _DepthCullingState.prototype.apply = function (gl) {
  11940. if (!this.isDirty) {
  11941. return;
  11942. }
  11943. // Cull
  11944. if (this._isCullDirty) {
  11945. if (this.cull) {
  11946. gl.enable(gl.CULL_FACE);
  11947. }
  11948. else {
  11949. gl.disable(gl.CULL_FACE);
  11950. }
  11951. this._isCullDirty = false;
  11952. }
  11953. // Cull face
  11954. if (this._isCullFaceDirty) {
  11955. gl.cullFace(this.cullFace);
  11956. this._isCullFaceDirty = false;
  11957. }
  11958. // Depth mask
  11959. if (this._isDepthMaskDirty) {
  11960. gl.depthMask(this.depthMask);
  11961. this._isDepthMaskDirty = false;
  11962. }
  11963. // Depth test
  11964. if (this._isDepthTestDirty) {
  11965. if (this.depthTest) {
  11966. gl.enable(gl.DEPTH_TEST);
  11967. }
  11968. else {
  11969. gl.disable(gl.DEPTH_TEST);
  11970. }
  11971. this._isDepthTestDirty = false;
  11972. }
  11973. // Depth func
  11974. if (this._isDepthFuncDirty) {
  11975. gl.depthFunc(this.depthFunc);
  11976. this._isDepthFuncDirty = false;
  11977. }
  11978. // zOffset
  11979. if (this._isZOffsetDirty) {
  11980. if (this.zOffset) {
  11981. gl.enable(gl.POLYGON_OFFSET_FILL);
  11982. gl.polygonOffset(this.zOffset, 0);
  11983. }
  11984. else {
  11985. gl.disable(gl.POLYGON_OFFSET_FILL);
  11986. }
  11987. this._isZOffsetDirty = false;
  11988. }
  11989. // Front face
  11990. if (this._isFrontFaceDirty) {
  11991. gl.frontFace(this.frontFace);
  11992. this._isFrontFaceDirty = false;
  11993. }
  11994. };
  11995. return _DepthCullingState;
  11996. }());
  11997. BABYLON._DepthCullingState = _DepthCullingState;
  11998. })(BABYLON || (BABYLON = {}));
  11999. //# sourceMappingURL=depthCullingState.js.map
  12000. var BABYLON;
  12001. (function (BABYLON) {
  12002. /**
  12003. * @hidden
  12004. **/
  12005. var _StencilState = /** @class */ (function () {
  12006. function _StencilState() {
  12007. this._isStencilTestDirty = false;
  12008. this._isStencilMaskDirty = false;
  12009. this._isStencilFuncDirty = false;
  12010. this._isStencilOpDirty = false;
  12011. this.reset();
  12012. }
  12013. Object.defineProperty(_StencilState.prototype, "isDirty", {
  12014. get: function () {
  12015. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  12016. },
  12017. enumerable: true,
  12018. configurable: true
  12019. });
  12020. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  12021. get: function () {
  12022. return this._stencilFunc;
  12023. },
  12024. set: function (value) {
  12025. if (this._stencilFunc === value) {
  12026. return;
  12027. }
  12028. this._stencilFunc = value;
  12029. this._isStencilFuncDirty = true;
  12030. },
  12031. enumerable: true,
  12032. configurable: true
  12033. });
  12034. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  12035. get: function () {
  12036. return this._stencilFuncRef;
  12037. },
  12038. set: function (value) {
  12039. if (this._stencilFuncRef === value) {
  12040. return;
  12041. }
  12042. this._stencilFuncRef = value;
  12043. this._isStencilFuncDirty = true;
  12044. },
  12045. enumerable: true,
  12046. configurable: true
  12047. });
  12048. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  12049. get: function () {
  12050. return this._stencilFuncMask;
  12051. },
  12052. set: function (value) {
  12053. if (this._stencilFuncMask === value) {
  12054. return;
  12055. }
  12056. this._stencilFuncMask = value;
  12057. this._isStencilFuncDirty = true;
  12058. },
  12059. enumerable: true,
  12060. configurable: true
  12061. });
  12062. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  12063. get: function () {
  12064. return this._stencilOpStencilFail;
  12065. },
  12066. set: function (value) {
  12067. if (this._stencilOpStencilFail === value) {
  12068. return;
  12069. }
  12070. this._stencilOpStencilFail = value;
  12071. this._isStencilOpDirty = true;
  12072. },
  12073. enumerable: true,
  12074. configurable: true
  12075. });
  12076. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  12077. get: function () {
  12078. return this._stencilOpDepthFail;
  12079. },
  12080. set: function (value) {
  12081. if (this._stencilOpDepthFail === value) {
  12082. return;
  12083. }
  12084. this._stencilOpDepthFail = value;
  12085. this._isStencilOpDirty = true;
  12086. },
  12087. enumerable: true,
  12088. configurable: true
  12089. });
  12090. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  12091. get: function () {
  12092. return this._stencilOpStencilDepthPass;
  12093. },
  12094. set: function (value) {
  12095. if (this._stencilOpStencilDepthPass === value) {
  12096. return;
  12097. }
  12098. this._stencilOpStencilDepthPass = value;
  12099. this._isStencilOpDirty = true;
  12100. },
  12101. enumerable: true,
  12102. configurable: true
  12103. });
  12104. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  12105. get: function () {
  12106. return this._stencilMask;
  12107. },
  12108. set: function (value) {
  12109. if (this._stencilMask === value) {
  12110. return;
  12111. }
  12112. this._stencilMask = value;
  12113. this._isStencilMaskDirty = true;
  12114. },
  12115. enumerable: true,
  12116. configurable: true
  12117. });
  12118. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  12119. get: function () {
  12120. return this._stencilTest;
  12121. },
  12122. set: function (value) {
  12123. if (this._stencilTest === value) {
  12124. return;
  12125. }
  12126. this._stencilTest = value;
  12127. this._isStencilTestDirty = true;
  12128. },
  12129. enumerable: true,
  12130. configurable: true
  12131. });
  12132. _StencilState.prototype.reset = function () {
  12133. this._stencilTest = false;
  12134. this._stencilMask = 0xFF;
  12135. this._stencilFunc = BABYLON.Engine.ALWAYS;
  12136. this._stencilFuncRef = 1;
  12137. this._stencilFuncMask = 0xFF;
  12138. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  12139. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  12140. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  12141. this._isStencilTestDirty = true;
  12142. this._isStencilMaskDirty = true;
  12143. this._isStencilFuncDirty = true;
  12144. this._isStencilOpDirty = true;
  12145. };
  12146. _StencilState.prototype.apply = function (gl) {
  12147. if (!this.isDirty) {
  12148. return;
  12149. }
  12150. // Stencil test
  12151. if (this._isStencilTestDirty) {
  12152. if (this.stencilTest) {
  12153. gl.enable(gl.STENCIL_TEST);
  12154. }
  12155. else {
  12156. gl.disable(gl.STENCIL_TEST);
  12157. }
  12158. this._isStencilTestDirty = false;
  12159. }
  12160. // Stencil mask
  12161. if (this._isStencilMaskDirty) {
  12162. gl.stencilMask(this.stencilMask);
  12163. this._isStencilMaskDirty = false;
  12164. }
  12165. // Stencil func
  12166. if (this._isStencilFuncDirty) {
  12167. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  12168. this._isStencilFuncDirty = false;
  12169. }
  12170. // Stencil op
  12171. if (this._isStencilOpDirty) {
  12172. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  12173. this._isStencilOpDirty = false;
  12174. }
  12175. };
  12176. return _StencilState;
  12177. }());
  12178. BABYLON._StencilState = _StencilState;
  12179. })(BABYLON || (BABYLON = {}));
  12180. //# sourceMappingURL=stencilState.js.map
  12181. var __assign = (this && this.__assign) || function () {
  12182. __assign = Object.assign || function(t) {
  12183. for (var s, i = 1, n = arguments.length; i < n; i++) {
  12184. s = arguments[i];
  12185. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  12186. t[p] = s[p];
  12187. }
  12188. return t;
  12189. };
  12190. return __assign.apply(this, arguments);
  12191. };
  12192. var BABYLON;
  12193. (function (BABYLON) {
  12194. /**
  12195. * Keeps track of all the buffer info used in engine.
  12196. */
  12197. var BufferPointer = /** @class */ (function () {
  12198. function BufferPointer() {
  12199. }
  12200. return BufferPointer;
  12201. }());
  12202. /**
  12203. * Interface for attribute information associated with buffer instanciation
  12204. */
  12205. var InstancingAttributeInfo = /** @class */ (function () {
  12206. function InstancingAttributeInfo() {
  12207. }
  12208. return InstancingAttributeInfo;
  12209. }());
  12210. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  12211. /**
  12212. * Define options used to create a render target texture
  12213. */
  12214. var RenderTargetCreationOptions = /** @class */ (function () {
  12215. function RenderTargetCreationOptions() {
  12216. }
  12217. return RenderTargetCreationOptions;
  12218. }());
  12219. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  12220. /**
  12221. * Define options used to create a depth texture
  12222. */
  12223. var DepthTextureCreationOptions = /** @class */ (function () {
  12224. function DepthTextureCreationOptions() {
  12225. }
  12226. return DepthTextureCreationOptions;
  12227. }());
  12228. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  12229. /**
  12230. * Class used to describe the capabilities of the engine relatively to the current browser
  12231. */
  12232. var EngineCapabilities = /** @class */ (function () {
  12233. function EngineCapabilities() {
  12234. }
  12235. return EngineCapabilities;
  12236. }());
  12237. BABYLON.EngineCapabilities = EngineCapabilities;
  12238. /**
  12239. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  12240. */
  12241. var Engine = /** @class */ (function () {
  12242. /**
  12243. * Creates a new engine
  12244. * @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
  12245. * @param antialias defines enable antialiasing (default: false)
  12246. * @param options defines further options to be sent to the getContext() function
  12247. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  12248. */
  12249. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  12250. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  12251. var _this = this;
  12252. // Public members
  12253. /**
  12254. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  12255. */
  12256. this.forcePOTTextures = false;
  12257. /**
  12258. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  12259. */
  12260. this.isFullscreen = false;
  12261. /**
  12262. * Gets a boolean indicating if the pointer is currently locked
  12263. */
  12264. this.isPointerLock = false;
  12265. /**
  12266. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  12267. */
  12268. this.cullBackFaces = true;
  12269. /**
  12270. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  12271. */
  12272. this.renderEvenInBackground = true;
  12273. /**
  12274. * Gets or sets a boolean indicating that cache can be kept between frames
  12275. */
  12276. this.preventCacheWipeBetweenFrames = false;
  12277. /**
  12278. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  12279. **/
  12280. this.enableOfflineSupport = false;
  12281. /**
  12282. * 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)
  12283. **/
  12284. this.disableManifestCheck = false;
  12285. /**
  12286. * Gets the list of created scenes
  12287. */
  12288. this.scenes = new Array();
  12289. /**
  12290. * Gets the list of created postprocesses
  12291. */
  12292. this.postProcesses = new Array();
  12293. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  12294. this.validateShaderPrograms = false;
  12295. // Observables
  12296. /**
  12297. * Observable event triggered each time the rendering canvas is resized
  12298. */
  12299. this.onResizeObservable = new BABYLON.Observable();
  12300. /**
  12301. * Observable event triggered each time the canvas loses focus
  12302. */
  12303. this.onCanvasBlurObservable = new BABYLON.Observable();
  12304. /**
  12305. * Observable event triggered each time the canvas gains focus
  12306. */
  12307. this.onCanvasFocusObservable = new BABYLON.Observable();
  12308. /**
  12309. * Observable event triggered each time the canvas receives pointerout event
  12310. */
  12311. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  12312. /**
  12313. * Observable event triggered before each texture is initialized
  12314. */
  12315. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  12316. //WebVR
  12317. this._vrDisplay = undefined;
  12318. this._vrSupported = false;
  12319. this._vrExclusivePointerMode = false;
  12320. // Uniform buffers list
  12321. /**
  12322. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  12323. */
  12324. this.disableUniformBuffers = false;
  12325. /** @hidden */
  12326. this._uniformBuffers = new Array();
  12327. // Observables
  12328. /**
  12329. * Observable raised when the engine begins a new frame
  12330. */
  12331. this.onBeginFrameObservable = new BABYLON.Observable();
  12332. /**
  12333. * If set, will be used to request the next animation frame for the render loop
  12334. */
  12335. this.customAnimationFrameRequester = null;
  12336. /**
  12337. * Observable raised when the engine ends the current frame
  12338. */
  12339. this.onEndFrameObservable = new BABYLON.Observable();
  12340. /**
  12341. * Observable raised when the engine is about to compile a shader
  12342. */
  12343. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  12344. /**
  12345. * Observable raised when the engine has jsut compiled a shader
  12346. */
  12347. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  12348. this._windowIsBackground = false;
  12349. this._webGLVersion = 1.0;
  12350. /** @hidden */
  12351. this._badOS = false;
  12352. /** @hidden */
  12353. this._badDesktopOS = false;
  12354. /**
  12355. * Gets or sets a value indicating if we want to disable texture binding optimization.
  12356. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  12357. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  12358. */
  12359. this.disableTextureBindingOptimization = false;
  12360. /**
  12361. * Observable signaled when VR display mode changes
  12362. */
  12363. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  12364. /**
  12365. * Observable signaled when VR request present is complete
  12366. */
  12367. this.onVRRequestPresentComplete = new BABYLON.Observable();
  12368. /**
  12369. * Observable signaled when VR request present starts
  12370. */
  12371. this.onVRRequestPresentStart = new BABYLON.Observable();
  12372. this._colorWrite = true;
  12373. /** @hidden */
  12374. this._drawCalls = new BABYLON.PerfCounter();
  12375. /** @hidden */
  12376. this._textureCollisions = new BABYLON.PerfCounter();
  12377. this._renderingQueueLaunched = false;
  12378. this._activeRenderLoops = new Array();
  12379. // Deterministic lockstepMaxSteps
  12380. this._deterministicLockstep = false;
  12381. this._lockstepMaxSteps = 4;
  12382. // Lost context
  12383. /**
  12384. * Observable signaled when a context lost event is raised
  12385. */
  12386. this.onContextLostObservable = new BABYLON.Observable();
  12387. /**
  12388. * Observable signaled when a context restored event is raised
  12389. */
  12390. this.onContextRestoredObservable = new BABYLON.Observable();
  12391. this._contextWasLost = false;
  12392. this._doNotHandleContextLost = false;
  12393. // FPS
  12394. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  12395. this._fps = 60;
  12396. this._deltaTime = 0;
  12397. /**
  12398. * Turn this value on if you want to pause FPS computation when in background
  12399. */
  12400. this.disablePerformanceMonitorInBackground = false;
  12401. // States
  12402. /** @hidden */
  12403. this._depthCullingState = new BABYLON._DepthCullingState();
  12404. /** @hidden */
  12405. this._stencilState = new BABYLON._StencilState();
  12406. /** @hidden */
  12407. this._alphaState = new BABYLON._AlphaState();
  12408. /** @hidden */
  12409. this._alphaMode = Engine.ALPHA_DISABLE;
  12410. // Cache
  12411. this._internalTexturesCache = new Array();
  12412. /** @hidden */
  12413. this._activeChannel = 0;
  12414. this._currentTextureChannel = -1;
  12415. /** @hidden */
  12416. this._boundTexturesCache = {};
  12417. this._compiledEffects = {};
  12418. this._vertexAttribArraysEnabled = [];
  12419. this._uintIndicesCurrentlySet = false;
  12420. this._currentBoundBuffer = new Array();
  12421. /** @hidden */
  12422. this._currentFramebuffer = null;
  12423. this._currentBufferPointers = new Array();
  12424. this._currentInstanceLocations = new Array();
  12425. this._currentInstanceBuffers = new Array();
  12426. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12427. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12428. this._vaoRecordInProgress = false;
  12429. this._mustWipeVertexAttributes = false;
  12430. this._nextFreeTextureSlots = new Array();
  12431. this._maxSimultaneousTextures = 0;
  12432. this._activeRequests = new Array();
  12433. // Hardware supported Compressed Textures
  12434. this._texturesSupported = new Array();
  12435. /**
  12436. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  12437. */
  12438. this.premultipliedAlpha = true;
  12439. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  12440. this._onVRFullScreenTriggered = function () {
  12441. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  12442. //get the old size before we change
  12443. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  12444. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  12445. //get the width and height, change the render size
  12446. var leftEye = _this._vrDisplay.getEyeParameters('left');
  12447. _this.setHardwareScalingLevel(1);
  12448. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  12449. }
  12450. else {
  12451. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  12452. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  12453. }
  12454. };
  12455. this._unpackFlipYCached = null;
  12456. /**
  12457. * In case you are sharing the context with other applications, it might
  12458. * be interested to not cache the unpack flip y state to ensure a consistent
  12459. * value would be set.
  12460. */
  12461. this.enableUnpackFlipYCached = true;
  12462. this._boundUniforms = {};
  12463. // Register promises
  12464. BABYLON.PromisePolyfill.Apply();
  12465. var canvas = null;
  12466. Engine.Instances.push(this);
  12467. if (!canvasOrContext) {
  12468. return;
  12469. }
  12470. options = options || {};
  12471. if (canvasOrContext.getContext) {
  12472. canvas = canvasOrContext;
  12473. this._renderingCanvas = canvas;
  12474. if (antialias != null) {
  12475. options.antialias = antialias;
  12476. }
  12477. if (options.deterministicLockstep === undefined) {
  12478. options.deterministicLockstep = false;
  12479. }
  12480. if (options.lockstepMaxSteps === undefined) {
  12481. options.lockstepMaxSteps = 4;
  12482. }
  12483. if (options.preserveDrawingBuffer === undefined) {
  12484. options.preserveDrawingBuffer = false;
  12485. }
  12486. if (options.audioEngine === undefined) {
  12487. options.audioEngine = true;
  12488. }
  12489. if (options.stencil === undefined) {
  12490. options.stencil = true;
  12491. }
  12492. if (options.premultipliedAlpha === false) {
  12493. this.premultipliedAlpha = false;
  12494. }
  12495. this._deterministicLockstep = options.deterministicLockstep;
  12496. this._lockstepMaxSteps = options.lockstepMaxSteps;
  12497. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  12498. // Exceptions
  12499. if (navigator && navigator.userAgent) {
  12500. var ua = navigator.userAgent;
  12501. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  12502. var exception = _a[_i];
  12503. var key = exception.key;
  12504. var targets = exception.targets;
  12505. if (ua.indexOf(key) > -1) {
  12506. if (exception.capture && exception.captureConstraint) {
  12507. var capture = exception.capture;
  12508. var constraint = exception.captureConstraint;
  12509. var regex = new RegExp(capture);
  12510. var matches = regex.exec(ua);
  12511. if (matches && matches.length > 0) {
  12512. var capturedValue = parseInt(matches[matches.length - 1]);
  12513. if (capturedValue >= constraint) {
  12514. continue;
  12515. }
  12516. }
  12517. }
  12518. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  12519. var target = targets_1[_b];
  12520. switch (target) {
  12521. case "uniformBuffer":
  12522. this.disableUniformBuffers = true;
  12523. break;
  12524. case "textureBindingOptimization":
  12525. this.disableTextureBindingOptimization = true;
  12526. break;
  12527. }
  12528. }
  12529. }
  12530. }
  12531. }
  12532. // GL
  12533. if (!options.disableWebGL2Support) {
  12534. try {
  12535. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  12536. if (this._gl) {
  12537. this._webGLVersion = 2.0;
  12538. // Prevent weird browsers to lie :-)
  12539. if (!this._gl.deleteQuery) {
  12540. this._webGLVersion = 1.0;
  12541. }
  12542. }
  12543. }
  12544. catch (e) {
  12545. // Do nothing
  12546. }
  12547. }
  12548. if (!this._gl) {
  12549. if (!canvas) {
  12550. throw new Error("The provided canvas is null or undefined.");
  12551. }
  12552. try {
  12553. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  12554. }
  12555. catch (e) {
  12556. throw new Error("WebGL not supported");
  12557. }
  12558. }
  12559. if (!this._gl) {
  12560. throw new Error("WebGL not supported");
  12561. }
  12562. this._onCanvasFocus = function () {
  12563. _this.onCanvasFocusObservable.notifyObservers(_this);
  12564. };
  12565. this._onCanvasBlur = function () {
  12566. _this.onCanvasBlurObservable.notifyObservers(_this);
  12567. };
  12568. canvas.addEventListener("focus", this._onCanvasFocus);
  12569. canvas.addEventListener("blur", this._onCanvasBlur);
  12570. this._onBlur = function () {
  12571. if (_this.disablePerformanceMonitorInBackground) {
  12572. _this._performanceMonitor.disable();
  12573. }
  12574. _this._windowIsBackground = true;
  12575. };
  12576. this._onFocus = function () {
  12577. if (_this.disablePerformanceMonitorInBackground) {
  12578. _this._performanceMonitor.enable();
  12579. }
  12580. _this._windowIsBackground = false;
  12581. };
  12582. this._onCanvasPointerOut = function (ev) {
  12583. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  12584. };
  12585. window.addEventListener("blur", this._onBlur);
  12586. window.addEventListener("focus", this._onFocus);
  12587. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  12588. // Context lost
  12589. if (!this._doNotHandleContextLost) {
  12590. this._onContextLost = function (evt) {
  12591. evt.preventDefault();
  12592. _this._contextWasLost = true;
  12593. BABYLON.Tools.Warn("WebGL context lost.");
  12594. _this.onContextLostObservable.notifyObservers(_this);
  12595. };
  12596. this._onContextRestored = function (evt) {
  12597. // Adding a timeout to avoid race condition at browser level
  12598. setTimeout(function () {
  12599. // Rebuild gl context
  12600. _this._initGLContext();
  12601. // Rebuild effects
  12602. _this._rebuildEffects();
  12603. // Rebuild textures
  12604. _this._rebuildInternalTextures();
  12605. // Rebuild buffers
  12606. _this._rebuildBuffers();
  12607. // Cache
  12608. _this.wipeCaches(true);
  12609. BABYLON.Tools.Warn("WebGL context successfully restored.");
  12610. _this.onContextRestoredObservable.notifyObservers(_this);
  12611. _this._contextWasLost = false;
  12612. }, 0);
  12613. };
  12614. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  12615. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  12616. }
  12617. }
  12618. else {
  12619. this._gl = canvasOrContext;
  12620. this._renderingCanvas = this._gl.canvas;
  12621. if (this._gl.renderbufferStorageMultisample) {
  12622. this._webGLVersion = 2.0;
  12623. }
  12624. var attributes = this._gl.getContextAttributes();
  12625. if (attributes) {
  12626. options.stencil = attributes.stencil;
  12627. }
  12628. }
  12629. // Viewport
  12630. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  12631. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  12632. this.resize();
  12633. this._isStencilEnable = options.stencil ? true : false;
  12634. this._initGLContext();
  12635. if (canvas) {
  12636. // Fullscreen
  12637. this._onFullscreenChange = function () {
  12638. if (document.fullscreen !== undefined) {
  12639. _this.isFullscreen = document.fullscreen;
  12640. }
  12641. else if (document.mozFullScreen !== undefined) {
  12642. _this.isFullscreen = document.mozFullScreen;
  12643. }
  12644. else if (document.webkitIsFullScreen !== undefined) {
  12645. _this.isFullscreen = document.webkitIsFullScreen;
  12646. }
  12647. else if (document.msIsFullScreen !== undefined) {
  12648. _this.isFullscreen = document.msIsFullScreen;
  12649. }
  12650. // Pointer lock
  12651. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  12652. canvas.requestPointerLock = canvas.requestPointerLock ||
  12653. canvas.msRequestPointerLock ||
  12654. canvas.mozRequestPointerLock ||
  12655. canvas.webkitRequestPointerLock;
  12656. if (canvas.requestPointerLock) {
  12657. canvas.requestPointerLock();
  12658. }
  12659. }
  12660. };
  12661. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  12662. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  12663. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  12664. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  12665. // Pointer lock
  12666. this._onPointerLockChange = function () {
  12667. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  12668. document.webkitPointerLockElement === canvas ||
  12669. document.msPointerLockElement === canvas ||
  12670. document.pointerLockElement === canvas);
  12671. };
  12672. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  12673. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  12674. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  12675. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  12676. this._onVRDisplayPointerRestricted = function () {
  12677. if (canvas) {
  12678. canvas.requestPointerLock();
  12679. }
  12680. };
  12681. this._onVRDisplayPointerUnrestricted = function () {
  12682. document.exitPointerLock();
  12683. };
  12684. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  12685. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  12686. }
  12687. // Create Audio Engine if needed.
  12688. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  12689. Engine.audioEngine = Engine.AudioEngineFactory(this.getRenderingCanvas());
  12690. }
  12691. // Prepare buffer pointers
  12692. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12693. this._currentBufferPointers[i] = new BufferPointer();
  12694. }
  12695. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  12696. // Load WebVR Devices
  12697. if (options.autoEnableWebVR) {
  12698. this.initWebVR();
  12699. }
  12700. // Detect if we are running on a faulty buggy OS.
  12701. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  12702. // Detect if we are running on a faulty buggy desktop OS.
  12703. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  12704. console.log("Babylon.js v" + Engine.Version + " - " + this.description);
  12705. this.enableOfflineSupport = Engine.OfflineProviderFactory !== undefined;
  12706. }
  12707. Object.defineProperty(Engine, "LastCreatedEngine", {
  12708. /**
  12709. * Gets the latest created engine
  12710. */
  12711. get: function () {
  12712. if (Engine.Instances.length === 0) {
  12713. return null;
  12714. }
  12715. return Engine.Instances[Engine.Instances.length - 1];
  12716. },
  12717. enumerable: true,
  12718. configurable: true
  12719. });
  12720. Object.defineProperty(Engine, "LastCreatedScene", {
  12721. /**
  12722. * Gets the latest created scene
  12723. */
  12724. get: function () {
  12725. var lastCreatedEngine = Engine.LastCreatedEngine;
  12726. if (!lastCreatedEngine) {
  12727. return null;
  12728. }
  12729. if (lastCreatedEngine.scenes.length === 0) {
  12730. return null;
  12731. }
  12732. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  12733. },
  12734. enumerable: true,
  12735. configurable: true
  12736. });
  12737. /**
  12738. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  12739. * @param flag defines which part of the materials must be marked as dirty
  12740. * @param predicate defines a predicate used to filter which materials should be affected
  12741. */
  12742. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  12743. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  12744. var engine = Engine.Instances[engineIndex];
  12745. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  12746. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  12747. }
  12748. }
  12749. };
  12750. Object.defineProperty(Engine, "Version", {
  12751. /**
  12752. * Returns the current version of the framework
  12753. */
  12754. get: function () {
  12755. return "4.0.0-alpha.5";
  12756. },
  12757. enumerable: true,
  12758. configurable: true
  12759. });
  12760. Object.defineProperty(Engine.prototype, "description", {
  12761. /**
  12762. * Returns a string describing the current engine
  12763. */
  12764. get: function () {
  12765. var description = "WebGL" + this.webGLVersion;
  12766. if (this._caps.parallelShaderCompile) {
  12767. description += " - Parallel shader compilation";
  12768. }
  12769. return description;
  12770. },
  12771. enumerable: true,
  12772. configurable: true
  12773. });
  12774. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12775. /**
  12776. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12777. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12778. */
  12779. get: function () {
  12780. return this._vrExclusivePointerMode;
  12781. },
  12782. enumerable: true,
  12783. configurable: true
  12784. });
  12785. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12786. /**
  12787. * Gets a boolean indicating that the engine supports uniform buffers
  12788. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12789. */
  12790. get: function () {
  12791. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12792. },
  12793. enumerable: true,
  12794. configurable: true
  12795. });
  12796. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12797. /**
  12798. * Gets a boolean indicating that only power of 2 textures are supported
  12799. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12800. */
  12801. get: function () {
  12802. return this._webGLVersion < 2 || this.forcePOTTextures;
  12803. },
  12804. enumerable: true,
  12805. configurable: true
  12806. });
  12807. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12808. /**
  12809. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12810. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12811. */
  12812. get: function () {
  12813. return this._doNotHandleContextLost;
  12814. },
  12815. set: function (value) {
  12816. this._doNotHandleContextLost = value;
  12817. },
  12818. enumerable: true,
  12819. configurable: true
  12820. });
  12821. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12822. /**
  12823. * Gets the performance monitor attached to this engine
  12824. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12825. */
  12826. get: function () {
  12827. return this._performanceMonitor;
  12828. },
  12829. enumerable: true,
  12830. configurable: true
  12831. });
  12832. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12833. /**
  12834. * Gets the list of texture formats supported
  12835. */
  12836. get: function () {
  12837. return this._texturesSupported;
  12838. },
  12839. enumerable: true,
  12840. configurable: true
  12841. });
  12842. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12843. /**
  12844. * Gets the list of texture formats in use
  12845. */
  12846. get: function () {
  12847. return this._textureFormatInUse;
  12848. },
  12849. enumerable: true,
  12850. configurable: true
  12851. });
  12852. Object.defineProperty(Engine.prototype, "currentViewport", {
  12853. /**
  12854. * Gets the current viewport
  12855. */
  12856. get: function () {
  12857. return this._cachedViewport;
  12858. },
  12859. enumerable: true,
  12860. configurable: true
  12861. });
  12862. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12863. /**
  12864. * Gets the default empty texture
  12865. */
  12866. get: function () {
  12867. if (!this._emptyTexture) {
  12868. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12869. }
  12870. return this._emptyTexture;
  12871. },
  12872. enumerable: true,
  12873. configurable: true
  12874. });
  12875. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12876. /**
  12877. * Gets the default empty 3D texture
  12878. */
  12879. get: function () {
  12880. if (!this._emptyTexture3D) {
  12881. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12882. }
  12883. return this._emptyTexture3D;
  12884. },
  12885. enumerable: true,
  12886. configurable: true
  12887. });
  12888. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12889. /**
  12890. * Gets the default empty cube texture
  12891. */
  12892. get: function () {
  12893. if (!this._emptyCubeTexture) {
  12894. var faceData = new Uint8Array(4);
  12895. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12896. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12897. }
  12898. return this._emptyCubeTexture;
  12899. },
  12900. enumerable: true,
  12901. configurable: true
  12902. });
  12903. Engine.prototype._rebuildInternalTextures = function () {
  12904. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12905. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12906. var internalTexture = currentState_1[_i];
  12907. internalTexture._rebuild();
  12908. }
  12909. };
  12910. Engine.prototype._rebuildEffects = function () {
  12911. for (var key in this._compiledEffects) {
  12912. var effect = this._compiledEffects[key];
  12913. effect._prepareEffect();
  12914. }
  12915. BABYLON.Effect.ResetCache();
  12916. };
  12917. /**
  12918. * Gets a boolean indicating if all created effects are ready
  12919. * @returns true if all effects are ready
  12920. */
  12921. Engine.prototype.areAllEffectsReady = function () {
  12922. for (var key in this._compiledEffects) {
  12923. var effect = this._compiledEffects[key];
  12924. if (!effect.isReady()) {
  12925. return false;
  12926. }
  12927. }
  12928. return true;
  12929. };
  12930. Engine.prototype._rebuildBuffers = function () {
  12931. // Index / Vertex
  12932. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12933. var scene = _a[_i];
  12934. scene.resetCachedMaterial();
  12935. scene._rebuildGeometries();
  12936. scene._rebuildTextures();
  12937. }
  12938. // Uniforms
  12939. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12940. var uniformBuffer = _c[_b];
  12941. uniformBuffer._rebuild();
  12942. }
  12943. };
  12944. Engine.prototype._initGLContext = function () {
  12945. // Caps
  12946. this._caps = new EngineCapabilities();
  12947. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12948. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12949. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12950. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12951. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12952. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12953. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12954. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12955. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12956. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12957. // Infos
  12958. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12959. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12960. if (rendererInfo != null) {
  12961. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12962. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12963. }
  12964. if (!this._glVendor) {
  12965. this._glVendor = "Unknown vendor";
  12966. }
  12967. if (!this._glRenderer) {
  12968. this._glRenderer = "Unknown renderer";
  12969. }
  12970. // Constants
  12971. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12972. if (this._gl.RGBA16F !== 0x881A) {
  12973. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12974. }
  12975. if (this._gl.RGBA32F !== 0x8814) {
  12976. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12977. }
  12978. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12979. this._gl.DEPTH24_STENCIL8 = 35056;
  12980. }
  12981. // Extensions
  12982. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12983. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12984. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12985. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12986. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12987. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12988. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12989. 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');
  12990. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12991. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12992. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12993. this._caps.highPrecisionShaderSupported = false;
  12994. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12995. if (this._caps.timerQuery) {
  12996. if (this._webGLVersion === 1) {
  12997. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12998. }
  12999. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  13000. }
  13001. // Checks if some of the format renders first to allow the use of webgl inspector.
  13002. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  13003. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  13004. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  13005. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  13006. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  13007. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  13008. if (this._webGLVersion > 1) {
  13009. this._gl.HALF_FLOAT_OES = 0x140B;
  13010. }
  13011. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  13012. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  13013. // Draw buffers
  13014. if (this._webGLVersion > 1) {
  13015. this._caps.drawBuffersExtension = true;
  13016. }
  13017. else {
  13018. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  13019. if (drawBuffersExtension !== null) {
  13020. this._caps.drawBuffersExtension = true;
  13021. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  13022. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  13023. for (var i = 0; i < 16; i++) {
  13024. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  13025. }
  13026. }
  13027. else {
  13028. this._caps.drawBuffersExtension = false;
  13029. }
  13030. }
  13031. // Shader compiler threads
  13032. this._caps.parallelShaderCompile = this._gl.getExtension('KHR_parallel_shader_compile');
  13033. if (this._caps.parallelShaderCompile) {
  13034. var threads = this._gl.getParameter(this._caps.parallelShaderCompile.MAX_SHADER_COMPILER_THREADS_KHR);
  13035. this._caps.parallelShaderCompile.maxShaderCompilerThreadsKHR(threads);
  13036. }
  13037. // Depth Texture
  13038. if (this._webGLVersion > 1) {
  13039. this._caps.depthTextureExtension = true;
  13040. }
  13041. else {
  13042. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  13043. if (depthTextureExtension != null) {
  13044. this._caps.depthTextureExtension = true;
  13045. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  13046. }
  13047. }
  13048. // Vertex array object
  13049. if (this._webGLVersion > 1) {
  13050. this._caps.vertexArrayObject = true;
  13051. }
  13052. else {
  13053. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  13054. if (vertexArrayObjectExtension != null) {
  13055. this._caps.vertexArrayObject = true;
  13056. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  13057. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  13058. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  13059. }
  13060. else {
  13061. this._caps.vertexArrayObject = false;
  13062. }
  13063. }
  13064. // Instances count
  13065. if (this._webGLVersion > 1) {
  13066. this._caps.instancedArrays = true;
  13067. }
  13068. else {
  13069. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  13070. if (instanceExtension != null) {
  13071. this._caps.instancedArrays = true;
  13072. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  13073. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  13074. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  13075. }
  13076. else {
  13077. this._caps.instancedArrays = false;
  13078. }
  13079. }
  13080. // Intelligently add supported compressed formats in order to check for.
  13081. // Check for ASTC support first as it is most powerful and to be very cross platform.
  13082. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  13083. // Likely no hardware which supports both PVR & DXT, so order matters little.
  13084. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  13085. if (this._caps.astc) {
  13086. this.texturesSupported.push('-astc.ktx');
  13087. }
  13088. if (this._caps.s3tc) {
  13089. this.texturesSupported.push('-dxt.ktx');
  13090. }
  13091. if (this._caps.pvrtc) {
  13092. this.texturesSupported.push('-pvrtc.ktx');
  13093. }
  13094. if (this._caps.etc2) {
  13095. this.texturesSupported.push('-etc2.ktx');
  13096. }
  13097. if (this._caps.etc1) {
  13098. this.texturesSupported.push('-etc1.ktx');
  13099. }
  13100. if (this._gl.getShaderPrecisionFormat) {
  13101. var vertex_highp = this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER, this._gl.HIGH_FLOAT);
  13102. var fragment_highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  13103. if (vertex_highp && fragment_highp) {
  13104. this._caps.highPrecisionShaderSupported = vertex_highp.precision !== 0 && fragment_highp.precision !== 0;
  13105. }
  13106. }
  13107. // Depth buffer
  13108. this.setDepthBuffer(true);
  13109. this.setDepthFunctionToLessOrEqual();
  13110. this.setDepthWrite(true);
  13111. // Texture maps
  13112. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  13113. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  13114. this._nextFreeTextureSlots.push(slot);
  13115. }
  13116. };
  13117. Object.defineProperty(Engine.prototype, "webGLVersion", {
  13118. /**
  13119. * Gets version of the current webGL context
  13120. */
  13121. get: function () {
  13122. return this._webGLVersion;
  13123. },
  13124. enumerable: true,
  13125. configurable: true
  13126. });
  13127. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  13128. /**
  13129. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  13130. */
  13131. get: function () {
  13132. return this._isStencilEnable;
  13133. },
  13134. enumerable: true,
  13135. configurable: true
  13136. });
  13137. Engine.prototype._prepareWorkingCanvas = function () {
  13138. if (this._workingCanvas) {
  13139. return;
  13140. }
  13141. this._workingCanvas = document.createElement("canvas");
  13142. var context = this._workingCanvas.getContext("2d");
  13143. if (context) {
  13144. this._workingContext = context;
  13145. }
  13146. };
  13147. /**
  13148. * Reset the texture cache to empty state
  13149. */
  13150. Engine.prototype.resetTextureCache = function () {
  13151. for (var key in this._boundTexturesCache) {
  13152. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  13153. continue;
  13154. }
  13155. var boundTexture = this._boundTexturesCache[key];
  13156. if (boundTexture) {
  13157. this._removeDesignatedSlot(boundTexture);
  13158. }
  13159. this._boundTexturesCache[key] = null;
  13160. }
  13161. if (!this.disableTextureBindingOptimization) {
  13162. this._nextFreeTextureSlots = [];
  13163. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  13164. this._nextFreeTextureSlots.push(slot);
  13165. }
  13166. }
  13167. this._currentTextureChannel = -1;
  13168. };
  13169. /**
  13170. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  13171. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  13172. * @returns true if engine is in deterministic lock step mode
  13173. */
  13174. Engine.prototype.isDeterministicLockStep = function () {
  13175. return this._deterministicLockstep;
  13176. };
  13177. /**
  13178. * Gets the max steps when engine is running in deterministic lock step
  13179. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  13180. * @returns the max steps
  13181. */
  13182. Engine.prototype.getLockstepMaxSteps = function () {
  13183. return this._lockstepMaxSteps;
  13184. };
  13185. /**
  13186. * Gets an object containing information about the current webGL context
  13187. * @returns an object containing the vender, the renderer and the version of the current webGL context
  13188. */
  13189. Engine.prototype.getGlInfo = function () {
  13190. return {
  13191. vendor: this._glVendor,
  13192. renderer: this._glRenderer,
  13193. version: this._glVersion
  13194. };
  13195. };
  13196. /**
  13197. * Gets current aspect ratio
  13198. * @param camera defines the camera to use to get the aspect ratio
  13199. * @param useScreen defines if screen size must be used (or the current render target if any)
  13200. * @returns a number defining the aspect ratio
  13201. */
  13202. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  13203. if (useScreen === void 0) { useScreen = false; }
  13204. var viewport = camera.viewport;
  13205. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  13206. };
  13207. /**
  13208. * Gets current screen aspect ratio
  13209. * @returns a number defining the aspect ratio
  13210. */
  13211. Engine.prototype.getScreenAspectRatio = function () {
  13212. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  13213. };
  13214. /**
  13215. * Gets the current render width
  13216. * @param useScreen defines if screen size must be used (or the current render target if any)
  13217. * @returns a number defining the current render width
  13218. */
  13219. Engine.prototype.getRenderWidth = function (useScreen) {
  13220. if (useScreen === void 0) { useScreen = false; }
  13221. if (!useScreen && this._currentRenderTarget) {
  13222. return this._currentRenderTarget.width;
  13223. }
  13224. return this._gl.drawingBufferWidth;
  13225. };
  13226. /**
  13227. * Gets the current render height
  13228. * @param useScreen defines if screen size must be used (or the current render target if any)
  13229. * @returns a number defining the current render height
  13230. */
  13231. Engine.prototype.getRenderHeight = function (useScreen) {
  13232. if (useScreen === void 0) { useScreen = false; }
  13233. if (!useScreen && this._currentRenderTarget) {
  13234. return this._currentRenderTarget.height;
  13235. }
  13236. return this._gl.drawingBufferHeight;
  13237. };
  13238. /**
  13239. * Gets the HTML canvas attached with the current webGL context
  13240. * @returns a HTML canvas
  13241. */
  13242. Engine.prototype.getRenderingCanvas = function () {
  13243. return this._renderingCanvas;
  13244. };
  13245. /**
  13246. * Gets the client rect of the HTML canvas attached with the current webGL context
  13247. * @returns a client rectanglee
  13248. */
  13249. Engine.prototype.getRenderingCanvasClientRect = function () {
  13250. if (!this._renderingCanvas) {
  13251. return null;
  13252. }
  13253. return this._renderingCanvas.getBoundingClientRect();
  13254. };
  13255. /**
  13256. * Defines the hardware scaling level.
  13257. * By default the hardware scaling level is computed from the window device ratio.
  13258. * 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.
  13259. * @param level defines the level to use
  13260. */
  13261. Engine.prototype.setHardwareScalingLevel = function (level) {
  13262. this._hardwareScalingLevel = level;
  13263. this.resize();
  13264. };
  13265. /**
  13266. * Gets the current hardware scaling level.
  13267. * By default the hardware scaling level is computed from the window device ratio.
  13268. * 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.
  13269. * @returns a number indicating the current hardware scaling level
  13270. */
  13271. Engine.prototype.getHardwareScalingLevel = function () {
  13272. return this._hardwareScalingLevel;
  13273. };
  13274. /**
  13275. * Gets the list of loaded textures
  13276. * @returns an array containing all loaded textures
  13277. */
  13278. Engine.prototype.getLoadedTexturesCache = function () {
  13279. return this._internalTexturesCache;
  13280. };
  13281. /**
  13282. * Gets the object containing all engine capabilities
  13283. * @returns the EngineCapabilities object
  13284. */
  13285. Engine.prototype.getCaps = function () {
  13286. return this._caps;
  13287. };
  13288. /**
  13289. * Gets the current depth function
  13290. * @returns a number defining the depth function
  13291. */
  13292. Engine.prototype.getDepthFunction = function () {
  13293. return this._depthCullingState.depthFunc;
  13294. };
  13295. /**
  13296. * Sets the current depth function
  13297. * @param depthFunc defines the function to use
  13298. */
  13299. Engine.prototype.setDepthFunction = function (depthFunc) {
  13300. this._depthCullingState.depthFunc = depthFunc;
  13301. };
  13302. /**
  13303. * Sets the current depth function to GREATER
  13304. */
  13305. Engine.prototype.setDepthFunctionToGreater = function () {
  13306. this._depthCullingState.depthFunc = this._gl.GREATER;
  13307. };
  13308. /**
  13309. * Sets the current depth function to GEQUAL
  13310. */
  13311. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  13312. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  13313. };
  13314. /**
  13315. * Sets the current depth function to LESS
  13316. */
  13317. Engine.prototype.setDepthFunctionToLess = function () {
  13318. this._depthCullingState.depthFunc = this._gl.LESS;
  13319. };
  13320. /**
  13321. * Sets the current depth function to LEQUAL
  13322. */
  13323. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  13324. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  13325. };
  13326. /**
  13327. * Gets a boolean indicating if stencil buffer is enabled
  13328. * @returns the current stencil buffer state
  13329. */
  13330. Engine.prototype.getStencilBuffer = function () {
  13331. return this._stencilState.stencilTest;
  13332. };
  13333. /**
  13334. * Enable or disable the stencil buffer
  13335. * @param enable defines if the stencil buffer must be enabled or disabled
  13336. */
  13337. Engine.prototype.setStencilBuffer = function (enable) {
  13338. this._stencilState.stencilTest = enable;
  13339. };
  13340. /**
  13341. * Gets the current stencil mask
  13342. * @returns a number defining the new stencil mask to use
  13343. */
  13344. Engine.prototype.getStencilMask = function () {
  13345. return this._stencilState.stencilMask;
  13346. };
  13347. /**
  13348. * Sets the current stencil mask
  13349. * @param mask defines the new stencil mask to use
  13350. */
  13351. Engine.prototype.setStencilMask = function (mask) {
  13352. this._stencilState.stencilMask = mask;
  13353. };
  13354. /**
  13355. * Gets the current stencil function
  13356. * @returns a number defining the stencil function to use
  13357. */
  13358. Engine.prototype.getStencilFunction = function () {
  13359. return this._stencilState.stencilFunc;
  13360. };
  13361. /**
  13362. * Gets the current stencil reference value
  13363. * @returns a number defining the stencil reference value to use
  13364. */
  13365. Engine.prototype.getStencilFunctionReference = function () {
  13366. return this._stencilState.stencilFuncRef;
  13367. };
  13368. /**
  13369. * Gets the current stencil mask
  13370. * @returns a number defining the stencil mask to use
  13371. */
  13372. Engine.prototype.getStencilFunctionMask = function () {
  13373. return this._stencilState.stencilFuncMask;
  13374. };
  13375. /**
  13376. * Sets the current stencil function
  13377. * @param stencilFunc defines the new stencil function to use
  13378. */
  13379. Engine.prototype.setStencilFunction = function (stencilFunc) {
  13380. this._stencilState.stencilFunc = stencilFunc;
  13381. };
  13382. /**
  13383. * Sets the current stencil reference
  13384. * @param reference defines the new stencil reference to use
  13385. */
  13386. Engine.prototype.setStencilFunctionReference = function (reference) {
  13387. this._stencilState.stencilFuncRef = reference;
  13388. };
  13389. /**
  13390. * Sets the current stencil mask
  13391. * @param mask defines the new stencil mask to use
  13392. */
  13393. Engine.prototype.setStencilFunctionMask = function (mask) {
  13394. this._stencilState.stencilFuncMask = mask;
  13395. };
  13396. /**
  13397. * Gets the current stencil operation when stencil fails
  13398. * @returns a number defining stencil operation to use when stencil fails
  13399. */
  13400. Engine.prototype.getStencilOperationFail = function () {
  13401. return this._stencilState.stencilOpStencilFail;
  13402. };
  13403. /**
  13404. * Gets the current stencil operation when depth fails
  13405. * @returns a number defining stencil operation to use when depth fails
  13406. */
  13407. Engine.prototype.getStencilOperationDepthFail = function () {
  13408. return this._stencilState.stencilOpDepthFail;
  13409. };
  13410. /**
  13411. * Gets the current stencil operation when stencil passes
  13412. * @returns a number defining stencil operation to use when stencil passes
  13413. */
  13414. Engine.prototype.getStencilOperationPass = function () {
  13415. return this._stencilState.stencilOpStencilDepthPass;
  13416. };
  13417. /**
  13418. * Sets the stencil operation to use when stencil fails
  13419. * @param operation defines the stencil operation to use when stencil fails
  13420. */
  13421. Engine.prototype.setStencilOperationFail = function (operation) {
  13422. this._stencilState.stencilOpStencilFail = operation;
  13423. };
  13424. /**
  13425. * Sets the stencil operation to use when depth fails
  13426. * @param operation defines the stencil operation to use when depth fails
  13427. */
  13428. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  13429. this._stencilState.stencilOpDepthFail = operation;
  13430. };
  13431. /**
  13432. * Sets the stencil operation to use when stencil passes
  13433. * @param operation defines the stencil operation to use when stencil passes
  13434. */
  13435. Engine.prototype.setStencilOperationPass = function (operation) {
  13436. this._stencilState.stencilOpStencilDepthPass = operation;
  13437. };
  13438. /**
  13439. * Sets a boolean indicating if the dithering state is enabled or disabled
  13440. * @param value defines the dithering state
  13441. */
  13442. Engine.prototype.setDitheringState = function (value) {
  13443. if (value) {
  13444. this._gl.enable(this._gl.DITHER);
  13445. }
  13446. else {
  13447. this._gl.disable(this._gl.DITHER);
  13448. }
  13449. };
  13450. /**
  13451. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  13452. * @param value defines the rasterizer state
  13453. */
  13454. Engine.prototype.setRasterizerState = function (value) {
  13455. if (value) {
  13456. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  13457. }
  13458. else {
  13459. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  13460. }
  13461. };
  13462. /**
  13463. * stop executing a render loop function and remove it from the execution array
  13464. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  13465. */
  13466. Engine.prototype.stopRenderLoop = function (renderFunction) {
  13467. if (!renderFunction) {
  13468. this._activeRenderLoops = [];
  13469. return;
  13470. }
  13471. var index = this._activeRenderLoops.indexOf(renderFunction);
  13472. if (index >= 0) {
  13473. this._activeRenderLoops.splice(index, 1);
  13474. }
  13475. };
  13476. /** @hidden */
  13477. Engine.prototype._renderLoop = function () {
  13478. if (!this._contextWasLost) {
  13479. var shouldRender = true;
  13480. if (!this.renderEvenInBackground && this._windowIsBackground) {
  13481. shouldRender = false;
  13482. }
  13483. if (shouldRender) {
  13484. // Start new frame
  13485. this.beginFrame();
  13486. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  13487. var renderFunction = this._activeRenderLoops[index];
  13488. renderFunction();
  13489. }
  13490. // Present
  13491. this.endFrame();
  13492. }
  13493. }
  13494. if (this._activeRenderLoops.length > 0) {
  13495. // Register new frame
  13496. if (this.customAnimationFrameRequester) {
  13497. this.customAnimationFrameRequester.requestID = BABYLON.Tools.QueueNewFrame(this.customAnimationFrameRequester.renderFunction || this._bindedRenderFunction, this.customAnimationFrameRequester);
  13498. this._frameHandler = this.customAnimationFrameRequester.requestID;
  13499. }
  13500. else if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13501. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplay);
  13502. }
  13503. else {
  13504. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13505. }
  13506. }
  13507. else {
  13508. this._renderingQueueLaunched = false;
  13509. }
  13510. };
  13511. /**
  13512. * Register and execute a render loop. The engine can have more than one render function
  13513. * @param renderFunction defines the function to continuously execute
  13514. */
  13515. Engine.prototype.runRenderLoop = function (renderFunction) {
  13516. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  13517. return;
  13518. }
  13519. this._activeRenderLoops.push(renderFunction);
  13520. if (!this._renderingQueueLaunched) {
  13521. this._renderingQueueLaunched = true;
  13522. this._bindedRenderFunction = this._renderLoop.bind(this);
  13523. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13524. }
  13525. };
  13526. /**
  13527. * Toggle full screen mode
  13528. * @param requestPointerLock defines if a pointer lock should be requested from the user
  13529. */
  13530. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  13531. if (this.isFullscreen) {
  13532. BABYLON.Tools.ExitFullscreen();
  13533. }
  13534. else {
  13535. this._pointerLockRequested = requestPointerLock;
  13536. if (this._renderingCanvas) {
  13537. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  13538. }
  13539. }
  13540. };
  13541. /**
  13542. * Clear the current render buffer or the current render target (if any is set up)
  13543. * @param color defines the color to use
  13544. * @param backBuffer defines if the back buffer must be cleared
  13545. * @param depth defines if the depth buffer must be cleared
  13546. * @param stencil defines if the stencil buffer must be cleared
  13547. */
  13548. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  13549. if (stencil === void 0) { stencil = false; }
  13550. this.applyStates();
  13551. var mode = 0;
  13552. if (backBuffer && color) {
  13553. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  13554. mode |= this._gl.COLOR_BUFFER_BIT;
  13555. }
  13556. if (depth) {
  13557. this._gl.clearDepth(1.0);
  13558. mode |= this._gl.DEPTH_BUFFER_BIT;
  13559. }
  13560. if (stencil) {
  13561. this._gl.clearStencil(0);
  13562. mode |= this._gl.STENCIL_BUFFER_BIT;
  13563. }
  13564. this._gl.clear(mode);
  13565. };
  13566. /**
  13567. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  13568. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  13569. * @param y defines the y-coordinate of the corner of the clear rectangle
  13570. * @param width defines the width of the clear rectangle
  13571. * @param height defines the height of the clear rectangle
  13572. * @param clearColor defines the clear color
  13573. */
  13574. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  13575. var gl = this._gl;
  13576. // Save state
  13577. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  13578. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  13579. // Change state
  13580. gl.enable(gl.SCISSOR_TEST);
  13581. gl.scissor(x, y, width, height);
  13582. // Clear
  13583. this.clear(clearColor, true, true, true);
  13584. // Restore state
  13585. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  13586. if (curScissor === true) {
  13587. gl.enable(gl.SCISSOR_TEST);
  13588. }
  13589. else {
  13590. gl.disable(gl.SCISSOR_TEST);
  13591. }
  13592. };
  13593. /** @hidden */
  13594. Engine.prototype._viewport = function (x, y, width, height) {
  13595. if (x !== this._viewportCached.x ||
  13596. y !== this._viewportCached.y ||
  13597. width !== this._viewportCached.z ||
  13598. height !== this._viewportCached.w) {
  13599. this._viewportCached.x = x;
  13600. this._viewportCached.y = y;
  13601. this._viewportCached.z = width;
  13602. this._viewportCached.w = height;
  13603. this._gl.viewport(x, y, width, height);
  13604. }
  13605. };
  13606. /**
  13607. * Set the WebGL's viewport
  13608. * @param viewport defines the viewport element to be used
  13609. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  13610. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  13611. */
  13612. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  13613. var width = requiredWidth || this.getRenderWidth();
  13614. var height = requiredHeight || this.getRenderHeight();
  13615. var x = viewport.x || 0;
  13616. var y = viewport.y || 0;
  13617. this._cachedViewport = viewport;
  13618. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  13619. };
  13620. /**
  13621. * Directly set the WebGL Viewport
  13622. * @param x defines the x coordinate of the viewport (in screen space)
  13623. * @param y defines the y coordinate of the viewport (in screen space)
  13624. * @param width defines the width of the viewport (in screen space)
  13625. * @param height defines the height of the viewport (in screen space)
  13626. * @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
  13627. */
  13628. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  13629. var currentViewport = this._cachedViewport;
  13630. this._cachedViewport = null;
  13631. this._viewport(x, y, width, height);
  13632. return currentViewport;
  13633. };
  13634. /**
  13635. * Begin a new frame
  13636. */
  13637. Engine.prototype.beginFrame = function () {
  13638. this.onBeginFrameObservable.notifyObservers(this);
  13639. this._measureFps();
  13640. };
  13641. /**
  13642. * Enf the current frame
  13643. */
  13644. Engine.prototype.endFrame = function () {
  13645. // Force a flush in case we are using a bad OS.
  13646. if (this._badOS) {
  13647. this.flushFramebuffer();
  13648. }
  13649. // Submit frame to the vr device, if enabled
  13650. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13651. // TODO: We should only submit the frame if we read frameData successfully.
  13652. this._vrDisplay.submitFrame();
  13653. }
  13654. this.onEndFrameObservable.notifyObservers(this);
  13655. };
  13656. /**
  13657. * Resize the view according to the canvas' size
  13658. */
  13659. Engine.prototype.resize = function () {
  13660. // We're not resizing the size of the canvas while in VR mode & presenting
  13661. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13662. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13663. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13664. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13665. }
  13666. };
  13667. /**
  13668. * Force a specific size of the canvas
  13669. * @param width defines the new canvas' width
  13670. * @param height defines the new canvas' height
  13671. */
  13672. Engine.prototype.setSize = function (width, height) {
  13673. if (!this._renderingCanvas) {
  13674. return;
  13675. }
  13676. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13677. return;
  13678. }
  13679. this._renderingCanvas.width = width;
  13680. this._renderingCanvas.height = height;
  13681. for (var index = 0; index < this.scenes.length; index++) {
  13682. var scene = this.scenes[index];
  13683. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13684. var cam = scene.cameras[camIndex];
  13685. cam._currentRenderId = 0;
  13686. }
  13687. }
  13688. if (this.onResizeObservable.hasObservers) {
  13689. this.onResizeObservable.notifyObservers(this);
  13690. }
  13691. };
  13692. // WebVR functions
  13693. /**
  13694. * Gets a boolean indicating if a webVR device was detected
  13695. * @returns true if a webVR device was detected
  13696. */
  13697. Engine.prototype.isVRDevicePresent = function () {
  13698. return !!this._vrDisplay;
  13699. };
  13700. /**
  13701. * Gets the current webVR device
  13702. * @returns the current webVR device (or null)
  13703. */
  13704. Engine.prototype.getVRDevice = function () {
  13705. return this._vrDisplay;
  13706. };
  13707. /**
  13708. * Initializes a webVR display and starts listening to display change events
  13709. * The onVRDisplayChangedObservable will be notified upon these changes
  13710. * @returns The onVRDisplayChangedObservable
  13711. */
  13712. Engine.prototype.initWebVR = function () {
  13713. this.initWebVRAsync();
  13714. return this.onVRDisplayChangedObservable;
  13715. };
  13716. /**
  13717. * Initializes a webVR display and starts listening to display change events
  13718. * The onVRDisplayChangedObservable will be notified upon these changes
  13719. * @returns A promise containing a VRDisplay and if vr is supported
  13720. */
  13721. Engine.prototype.initWebVRAsync = function () {
  13722. var _this = this;
  13723. var notifyObservers = function () {
  13724. var eventArgs = {
  13725. vrDisplay: _this._vrDisplay,
  13726. vrSupported: _this._vrSupported
  13727. };
  13728. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13729. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13730. };
  13731. if (!this._onVrDisplayConnect) {
  13732. this._onVrDisplayConnect = function (event) {
  13733. _this._vrDisplay = event.display;
  13734. notifyObservers();
  13735. };
  13736. this._onVrDisplayDisconnect = function () {
  13737. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13738. _this._vrDisplay = undefined;
  13739. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13740. notifyObservers();
  13741. };
  13742. this._onVrDisplayPresentChange = function () {
  13743. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13744. };
  13745. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13746. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13747. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13748. }
  13749. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13750. this._webVRInitPromise.then(notifyObservers);
  13751. return this._webVRInitPromise;
  13752. };
  13753. /**
  13754. * Call this function to switch to webVR mode
  13755. * Will do nothing if webVR is not supported or if there is no webVR device
  13756. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13757. */
  13758. Engine.prototype.enableVR = function () {
  13759. var _this = this;
  13760. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13761. var onResolved = function () {
  13762. _this.onVRRequestPresentComplete.notifyObservers(true);
  13763. _this._onVRFullScreenTriggered();
  13764. };
  13765. var onRejected = function () {
  13766. _this.onVRRequestPresentComplete.notifyObservers(false);
  13767. };
  13768. this.onVRRequestPresentStart.notifyObservers(this);
  13769. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13770. }
  13771. };
  13772. /**
  13773. * Call this function to leave webVR mode
  13774. * Will do nothing if webVR is not supported or if there is no webVR device
  13775. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13776. */
  13777. Engine.prototype.disableVR = function () {
  13778. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13779. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13780. }
  13781. };
  13782. Engine.prototype._getVRDisplaysAsync = function () {
  13783. var _this = this;
  13784. return new Promise(function (res, rej) {
  13785. if (navigator.getVRDisplays) {
  13786. navigator.getVRDisplays().then(function (devices) {
  13787. _this._vrSupported = true;
  13788. // note that devices may actually be an empty array. This is fine;
  13789. // we expect this._vrDisplay to be undefined in this case.
  13790. _this._vrDisplay = devices[0];
  13791. res({
  13792. vrDisplay: _this._vrDisplay,
  13793. vrSupported: _this._vrSupported
  13794. });
  13795. });
  13796. }
  13797. else {
  13798. _this._vrDisplay = undefined;
  13799. _this._vrSupported = false;
  13800. res({
  13801. vrDisplay: _this._vrDisplay,
  13802. vrSupported: _this._vrSupported
  13803. });
  13804. }
  13805. });
  13806. };
  13807. /**
  13808. * Binds the frame buffer to the specified texture.
  13809. * @param texture The texture to render to or null for the default canvas
  13810. * @param faceIndex The face of the texture to render to in case of cube texture
  13811. * @param requiredWidth The width of the target to render to
  13812. * @param requiredHeight The height of the target to render to
  13813. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13814. * @param depthStencilTexture The depth stencil texture to use to render
  13815. * @param lodLevel defines le lod level to bind to the frame buffer
  13816. */
  13817. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13818. if (lodLevel === void 0) { lodLevel = 0; }
  13819. if (this._currentRenderTarget) {
  13820. this.unBindFramebuffer(this._currentRenderTarget);
  13821. }
  13822. this._currentRenderTarget = texture;
  13823. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13824. var gl = this._gl;
  13825. if (texture.isCube) {
  13826. if (faceIndex === undefined) {
  13827. faceIndex = 0;
  13828. }
  13829. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13830. if (depthStencilTexture) {
  13831. if (depthStencilTexture._generateStencilBuffer) {
  13832. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13833. }
  13834. else {
  13835. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13836. }
  13837. }
  13838. }
  13839. if (this._cachedViewport && !forceFullscreenViewport) {
  13840. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13841. }
  13842. else {
  13843. if (!requiredWidth) {
  13844. requiredWidth = texture.width;
  13845. if (lodLevel) {
  13846. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13847. }
  13848. }
  13849. if (!requiredHeight) {
  13850. requiredHeight = texture.height;
  13851. if (lodLevel) {
  13852. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13853. }
  13854. }
  13855. this._viewport(0, 0, requiredWidth, requiredHeight);
  13856. }
  13857. this.wipeCaches();
  13858. };
  13859. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13860. if (this._currentFramebuffer !== framebuffer) {
  13861. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13862. this._currentFramebuffer = framebuffer;
  13863. }
  13864. };
  13865. /**
  13866. * Unbind the current render target texture from the webGL context
  13867. * @param texture defines the render target texture to unbind
  13868. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13869. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13870. */
  13871. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13872. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13873. this._currentRenderTarget = null;
  13874. // If MSAA, we need to bitblt back to main texture
  13875. var gl = this._gl;
  13876. if (texture._MSAAFramebuffer) {
  13877. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13878. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13879. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13880. }
  13881. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13882. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13883. gl.generateMipmap(gl.TEXTURE_2D);
  13884. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13885. }
  13886. if (onBeforeUnbind) {
  13887. if (texture._MSAAFramebuffer) {
  13888. // Bind the correct framebuffer
  13889. this.bindUnboundFramebuffer(texture._framebuffer);
  13890. }
  13891. onBeforeUnbind();
  13892. }
  13893. this.bindUnboundFramebuffer(null);
  13894. };
  13895. /**
  13896. * Unbind a list of render target textures from the webGL context
  13897. * This is used only when drawBuffer extension or webGL2 are active
  13898. * @param textures defines the render target textures to unbind
  13899. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13900. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13901. */
  13902. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13903. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13904. this._currentRenderTarget = null;
  13905. // If MSAA, we need to bitblt back to main texture
  13906. var gl = this._gl;
  13907. if (textures[0]._MSAAFramebuffer) {
  13908. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13909. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13910. var attachments = textures[0]._attachments;
  13911. if (!attachments) {
  13912. attachments = new Array(textures.length);
  13913. textures[0]._attachments = attachments;
  13914. }
  13915. for (var i = 0; i < textures.length; i++) {
  13916. var texture = textures[i];
  13917. for (var j = 0; j < attachments.length; j++) {
  13918. attachments[j] = gl.NONE;
  13919. }
  13920. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13921. gl.readBuffer(attachments[i]);
  13922. gl.drawBuffers(attachments);
  13923. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13924. }
  13925. for (var i = 0; i < attachments.length; i++) {
  13926. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13927. }
  13928. gl.drawBuffers(attachments);
  13929. }
  13930. for (var i = 0; i < textures.length; i++) {
  13931. var texture = textures[i];
  13932. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13933. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13934. gl.generateMipmap(gl.TEXTURE_2D);
  13935. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13936. }
  13937. }
  13938. if (onBeforeUnbind) {
  13939. if (textures[0]._MSAAFramebuffer) {
  13940. // Bind the correct framebuffer
  13941. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13942. }
  13943. onBeforeUnbind();
  13944. }
  13945. this.bindUnboundFramebuffer(null);
  13946. };
  13947. /**
  13948. * Force the mipmap generation for the given render target texture
  13949. * @param texture defines the render target texture to use
  13950. */
  13951. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13952. if (texture.generateMipMaps) {
  13953. var gl = this._gl;
  13954. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13955. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13956. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13957. }
  13958. };
  13959. /**
  13960. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13961. */
  13962. Engine.prototype.flushFramebuffer = function () {
  13963. this._gl.flush();
  13964. };
  13965. /**
  13966. * Unbind the current render target and bind the default framebuffer
  13967. */
  13968. Engine.prototype.restoreDefaultFramebuffer = function () {
  13969. if (this._currentRenderTarget) {
  13970. this.unBindFramebuffer(this._currentRenderTarget);
  13971. }
  13972. else {
  13973. this.bindUnboundFramebuffer(null);
  13974. }
  13975. if (this._cachedViewport) {
  13976. this.setViewport(this._cachedViewport);
  13977. }
  13978. this.wipeCaches();
  13979. };
  13980. // UBOs
  13981. /**
  13982. * Create an uniform buffer
  13983. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13984. * @param elements defines the content of the uniform buffer
  13985. * @returns the webGL uniform buffer
  13986. */
  13987. Engine.prototype.createUniformBuffer = function (elements) {
  13988. var ubo = this._gl.createBuffer();
  13989. if (!ubo) {
  13990. throw new Error("Unable to create uniform buffer");
  13991. }
  13992. this.bindUniformBuffer(ubo);
  13993. if (elements instanceof Float32Array) {
  13994. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13995. }
  13996. else {
  13997. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13998. }
  13999. this.bindUniformBuffer(null);
  14000. ubo.references = 1;
  14001. return ubo;
  14002. };
  14003. /**
  14004. * Create a dynamic uniform buffer
  14005. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  14006. * @param elements defines the content of the uniform buffer
  14007. * @returns the webGL uniform buffer
  14008. */
  14009. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  14010. var ubo = this._gl.createBuffer();
  14011. if (!ubo) {
  14012. throw new Error("Unable to create dynamic uniform buffer");
  14013. }
  14014. this.bindUniformBuffer(ubo);
  14015. if (elements instanceof Float32Array) {
  14016. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  14017. }
  14018. else {
  14019. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  14020. }
  14021. this.bindUniformBuffer(null);
  14022. ubo.references = 1;
  14023. return ubo;
  14024. };
  14025. /**
  14026. * Update an existing uniform buffer
  14027. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  14028. * @param uniformBuffer defines the target uniform buffer
  14029. * @param elements defines the content to update
  14030. * @param offset defines the offset in the uniform buffer where update should start
  14031. * @param count defines the size of the data to update
  14032. */
  14033. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  14034. this.bindUniformBuffer(uniformBuffer);
  14035. if (offset === undefined) {
  14036. offset = 0;
  14037. }
  14038. if (count === undefined) {
  14039. if (elements instanceof Float32Array) {
  14040. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  14041. }
  14042. else {
  14043. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  14044. }
  14045. }
  14046. else {
  14047. if (elements instanceof Float32Array) {
  14048. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  14049. }
  14050. else {
  14051. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  14052. }
  14053. }
  14054. this.bindUniformBuffer(null);
  14055. };
  14056. // VBOs
  14057. Engine.prototype._resetVertexBufferBinding = function () {
  14058. this.bindArrayBuffer(null);
  14059. this._cachedVertexBuffers = null;
  14060. };
  14061. /**
  14062. * Creates a vertex buffer
  14063. * @param data the data for the vertex buffer
  14064. * @returns the new WebGL static buffer
  14065. */
  14066. Engine.prototype.createVertexBuffer = function (data) {
  14067. var vbo = this._gl.createBuffer();
  14068. if (!vbo) {
  14069. throw new Error("Unable to create vertex buffer");
  14070. }
  14071. this.bindArrayBuffer(vbo);
  14072. if (data instanceof Array) {
  14073. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  14074. }
  14075. else {
  14076. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  14077. }
  14078. this._resetVertexBufferBinding();
  14079. vbo.references = 1;
  14080. return vbo;
  14081. };
  14082. /**
  14083. * Creates a dynamic vertex buffer
  14084. * @param data the data for the dynamic vertex buffer
  14085. * @returns the new WebGL dynamic buffer
  14086. */
  14087. Engine.prototype.createDynamicVertexBuffer = function (data) {
  14088. var vbo = this._gl.createBuffer();
  14089. if (!vbo) {
  14090. throw new Error("Unable to create dynamic vertex buffer");
  14091. }
  14092. this.bindArrayBuffer(vbo);
  14093. if (data instanceof Array) {
  14094. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  14095. }
  14096. else {
  14097. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  14098. }
  14099. this._resetVertexBufferBinding();
  14100. vbo.references = 1;
  14101. return vbo;
  14102. };
  14103. /**
  14104. * Update a dynamic index buffer
  14105. * @param indexBuffer defines the target index buffer
  14106. * @param indices defines the data to update
  14107. * @param offset defines the offset in the target index buffer where update should start
  14108. */
  14109. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  14110. if (offset === void 0) { offset = 0; }
  14111. // Force cache update
  14112. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  14113. this.bindIndexBuffer(indexBuffer);
  14114. var arrayBuffer;
  14115. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  14116. arrayBuffer = indices;
  14117. }
  14118. else {
  14119. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  14120. }
  14121. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  14122. this._resetIndexBufferBinding();
  14123. };
  14124. /**
  14125. * Updates a dynamic vertex buffer.
  14126. * @param vertexBuffer the vertex buffer to update
  14127. * @param data the data used to update the vertex buffer
  14128. * @param byteOffset the byte offset of the data
  14129. * @param byteLength the byte length of the data
  14130. */
  14131. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  14132. this.bindArrayBuffer(vertexBuffer);
  14133. if (byteOffset === undefined) {
  14134. byteOffset = 0;
  14135. }
  14136. if (byteLength === undefined) {
  14137. if (data instanceof Array) {
  14138. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  14139. }
  14140. else {
  14141. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  14142. }
  14143. }
  14144. else {
  14145. if (data instanceof Array) {
  14146. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  14147. }
  14148. else {
  14149. if (data instanceof ArrayBuffer) {
  14150. data = new Uint8Array(data, byteOffset, byteLength);
  14151. }
  14152. else {
  14153. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  14154. }
  14155. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14156. }
  14157. }
  14158. this._resetVertexBufferBinding();
  14159. };
  14160. Engine.prototype._resetIndexBufferBinding = function () {
  14161. this.bindIndexBuffer(null);
  14162. this._cachedIndexBuffer = null;
  14163. };
  14164. /**
  14165. * Creates a new index buffer
  14166. * @param indices defines the content of the index buffer
  14167. * @param updatable defines if the index buffer must be updatable
  14168. * @returns a new webGL buffer
  14169. */
  14170. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  14171. var vbo = this._gl.createBuffer();
  14172. if (!vbo) {
  14173. throw new Error("Unable to create index buffer");
  14174. }
  14175. this.bindIndexBuffer(vbo);
  14176. // Check for 32 bits indices
  14177. var arrayBuffer;
  14178. var need32Bits = false;
  14179. if (indices instanceof Uint16Array) {
  14180. arrayBuffer = indices;
  14181. }
  14182. else {
  14183. //check 32 bit support
  14184. if (this._caps.uintIndices) {
  14185. if (indices instanceof Uint32Array) {
  14186. arrayBuffer = indices;
  14187. need32Bits = true;
  14188. }
  14189. else {
  14190. //number[] or Int32Array, check if 32 bit is necessary
  14191. for (var index = 0; index < indices.length; index++) {
  14192. if (indices[index] > 65535) {
  14193. need32Bits = true;
  14194. break;
  14195. }
  14196. }
  14197. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  14198. }
  14199. }
  14200. else {
  14201. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  14202. arrayBuffer = new Uint16Array(indices);
  14203. }
  14204. }
  14205. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  14206. this._resetIndexBufferBinding();
  14207. vbo.references = 1;
  14208. vbo.is32Bits = need32Bits;
  14209. return vbo;
  14210. };
  14211. /**
  14212. * Bind a webGL buffer to the webGL context
  14213. * @param buffer defines the buffer to bind
  14214. */
  14215. Engine.prototype.bindArrayBuffer = function (buffer) {
  14216. if (!this._vaoRecordInProgress) {
  14217. this._unbindVertexArrayObject();
  14218. }
  14219. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  14220. };
  14221. /**
  14222. * Bind an uniform buffer to the current webGL context
  14223. * @param buffer defines the buffer to bind
  14224. */
  14225. Engine.prototype.bindUniformBuffer = function (buffer) {
  14226. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  14227. };
  14228. /**
  14229. * Bind a buffer to the current webGL context at a given location
  14230. * @param buffer defines the buffer to bind
  14231. * @param location defines the index where to bind the buffer
  14232. */
  14233. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  14234. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  14235. };
  14236. /**
  14237. * Bind a specific block at a given index in a specific shader program
  14238. * @param shaderProgram defines the shader program
  14239. * @param blockName defines the block name
  14240. * @param index defines the index where to bind the block
  14241. */
  14242. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  14243. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  14244. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  14245. };
  14246. Engine.prototype.bindIndexBuffer = function (buffer) {
  14247. if (!this._vaoRecordInProgress) {
  14248. this._unbindVertexArrayObject();
  14249. }
  14250. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  14251. };
  14252. Engine.prototype.bindBuffer = function (buffer, target) {
  14253. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  14254. this._gl.bindBuffer(target, buffer);
  14255. this._currentBoundBuffer[target] = buffer;
  14256. }
  14257. };
  14258. /**
  14259. * update the bound buffer with the given data
  14260. * @param data defines the data to update
  14261. */
  14262. Engine.prototype.updateArrayBuffer = function (data) {
  14263. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14264. };
  14265. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  14266. var pointer = this._currentBufferPointers[indx];
  14267. var changed = false;
  14268. if (!pointer.active) {
  14269. changed = true;
  14270. pointer.active = true;
  14271. pointer.index = indx;
  14272. pointer.size = size;
  14273. pointer.type = type;
  14274. pointer.normalized = normalized;
  14275. pointer.stride = stride;
  14276. pointer.offset = offset;
  14277. pointer.buffer = buffer;
  14278. }
  14279. else {
  14280. if (pointer.buffer !== buffer) {
  14281. pointer.buffer = buffer;
  14282. changed = true;
  14283. }
  14284. if (pointer.size !== size) {
  14285. pointer.size = size;
  14286. changed = true;
  14287. }
  14288. if (pointer.type !== type) {
  14289. pointer.type = type;
  14290. changed = true;
  14291. }
  14292. if (pointer.normalized !== normalized) {
  14293. pointer.normalized = normalized;
  14294. changed = true;
  14295. }
  14296. if (pointer.stride !== stride) {
  14297. pointer.stride = stride;
  14298. changed = true;
  14299. }
  14300. if (pointer.offset !== offset) {
  14301. pointer.offset = offset;
  14302. changed = true;
  14303. }
  14304. }
  14305. if (changed || this._vaoRecordInProgress) {
  14306. this.bindArrayBuffer(buffer);
  14307. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  14308. }
  14309. };
  14310. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  14311. if (indexBuffer == null) {
  14312. return;
  14313. }
  14314. if (this._cachedIndexBuffer !== indexBuffer) {
  14315. this._cachedIndexBuffer = indexBuffer;
  14316. this.bindIndexBuffer(indexBuffer);
  14317. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  14318. }
  14319. };
  14320. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  14321. var attributes = effect.getAttributesNames();
  14322. if (!this._vaoRecordInProgress) {
  14323. this._unbindVertexArrayObject();
  14324. }
  14325. this.unbindAllAttributes();
  14326. for (var index = 0; index < attributes.length; index++) {
  14327. var order = effect.getAttributeLocation(index);
  14328. if (order >= 0) {
  14329. var vertexBuffer = vertexBuffers[attributes[index]];
  14330. if (!vertexBuffer) {
  14331. continue;
  14332. }
  14333. this._gl.enableVertexAttribArray(order);
  14334. if (!this._vaoRecordInProgress) {
  14335. this._vertexAttribArraysEnabled[order] = true;
  14336. }
  14337. var buffer = vertexBuffer.getBuffer();
  14338. if (buffer) {
  14339. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  14340. if (vertexBuffer.getIsInstanced()) {
  14341. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  14342. if (!this._vaoRecordInProgress) {
  14343. this._currentInstanceLocations.push(order);
  14344. this._currentInstanceBuffers.push(buffer);
  14345. }
  14346. }
  14347. }
  14348. }
  14349. }
  14350. };
  14351. /**
  14352. * Records a vertex array object
  14353. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14354. * @param vertexBuffers defines the list of vertex buffers to store
  14355. * @param indexBuffer defines the index buffer to store
  14356. * @param effect defines the effect to store
  14357. * @returns the new vertex array object
  14358. */
  14359. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  14360. var vao = this._gl.createVertexArray();
  14361. this._vaoRecordInProgress = true;
  14362. this._gl.bindVertexArray(vao);
  14363. this._mustWipeVertexAttributes = true;
  14364. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14365. this.bindIndexBuffer(indexBuffer);
  14366. this._vaoRecordInProgress = false;
  14367. this._gl.bindVertexArray(null);
  14368. return vao;
  14369. };
  14370. /**
  14371. * Bind a specific vertex array object
  14372. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14373. * @param vertexArrayObject defines the vertex array object to bind
  14374. * @param indexBuffer defines the index buffer to bind
  14375. */
  14376. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  14377. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  14378. this._cachedVertexArrayObject = vertexArrayObject;
  14379. this._gl.bindVertexArray(vertexArrayObject);
  14380. this._cachedVertexBuffers = null;
  14381. this._cachedIndexBuffer = null;
  14382. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  14383. this._mustWipeVertexAttributes = true;
  14384. }
  14385. };
  14386. /**
  14387. * Bind webGl buffers directly to the webGL context
  14388. * @param vertexBuffer defines the vertex buffer to bind
  14389. * @param indexBuffer defines the index buffer to bind
  14390. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  14391. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  14392. * @param effect defines the effect associated with the vertex buffer
  14393. */
  14394. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  14395. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  14396. this._cachedVertexBuffers = vertexBuffer;
  14397. this._cachedEffectForVertexBuffers = effect;
  14398. var attributesCount = effect.getAttributesCount();
  14399. this._unbindVertexArrayObject();
  14400. this.unbindAllAttributes();
  14401. var offset = 0;
  14402. for (var index = 0; index < attributesCount; index++) {
  14403. if (index < vertexDeclaration.length) {
  14404. var order = effect.getAttributeLocation(index);
  14405. if (order >= 0) {
  14406. this._gl.enableVertexAttribArray(order);
  14407. this._vertexAttribArraysEnabled[order] = true;
  14408. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  14409. }
  14410. offset += vertexDeclaration[index] * 4;
  14411. }
  14412. }
  14413. }
  14414. this._bindIndexBufferWithCache(indexBuffer);
  14415. };
  14416. Engine.prototype._unbindVertexArrayObject = function () {
  14417. if (!this._cachedVertexArrayObject) {
  14418. return;
  14419. }
  14420. this._cachedVertexArrayObject = null;
  14421. this._gl.bindVertexArray(null);
  14422. };
  14423. /**
  14424. * Bind a list of vertex buffers to the webGL context
  14425. * @param vertexBuffers defines the list of vertex buffers to bind
  14426. * @param indexBuffer defines the index buffer to bind
  14427. * @param effect defines the effect associated with the vertex buffers
  14428. */
  14429. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  14430. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  14431. this._cachedVertexBuffers = vertexBuffers;
  14432. this._cachedEffectForVertexBuffers = effect;
  14433. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14434. }
  14435. this._bindIndexBufferWithCache(indexBuffer);
  14436. };
  14437. /**
  14438. * Unbind all instance attributes
  14439. */
  14440. Engine.prototype.unbindInstanceAttributes = function () {
  14441. var boundBuffer;
  14442. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  14443. var instancesBuffer = this._currentInstanceBuffers[i];
  14444. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  14445. boundBuffer = instancesBuffer;
  14446. this.bindArrayBuffer(instancesBuffer);
  14447. }
  14448. var offsetLocation = this._currentInstanceLocations[i];
  14449. this._gl.vertexAttribDivisor(offsetLocation, 0);
  14450. }
  14451. this._currentInstanceBuffers.length = 0;
  14452. this._currentInstanceLocations.length = 0;
  14453. };
  14454. /**
  14455. * Release and free the memory of a vertex array object
  14456. * @param vao defines the vertex array object to delete
  14457. */
  14458. Engine.prototype.releaseVertexArrayObject = function (vao) {
  14459. this._gl.deleteVertexArray(vao);
  14460. };
  14461. /** @hidden */
  14462. Engine.prototype._releaseBuffer = function (buffer) {
  14463. buffer.references--;
  14464. if (buffer.references === 0) {
  14465. this._gl.deleteBuffer(buffer);
  14466. return true;
  14467. }
  14468. return false;
  14469. };
  14470. /**
  14471. * Creates a webGL buffer to use with instanciation
  14472. * @param capacity defines the size of the buffer
  14473. * @returns the webGL buffer
  14474. */
  14475. Engine.prototype.createInstancesBuffer = function (capacity) {
  14476. var buffer = this._gl.createBuffer();
  14477. if (!buffer) {
  14478. throw new Error("Unable to create instance buffer");
  14479. }
  14480. buffer.capacity = capacity;
  14481. this.bindArrayBuffer(buffer);
  14482. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  14483. return buffer;
  14484. };
  14485. /**
  14486. * Delete a webGL buffer used with instanciation
  14487. * @param buffer defines the webGL buffer to delete
  14488. */
  14489. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  14490. this._gl.deleteBuffer(buffer);
  14491. };
  14492. /**
  14493. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  14494. * @param instancesBuffer defines the webGL buffer to update and bind
  14495. * @param data defines the data to store in the buffer
  14496. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  14497. */
  14498. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  14499. this.bindArrayBuffer(instancesBuffer);
  14500. if (data) {
  14501. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14502. }
  14503. if (offsetLocations[0].index !== undefined) {
  14504. var stride = 0;
  14505. for (var i = 0; i < offsetLocations.length; i++) {
  14506. var ai = offsetLocations[i];
  14507. stride += ai.attributeSize * 4;
  14508. }
  14509. for (var i = 0; i < offsetLocations.length; i++) {
  14510. var ai = offsetLocations[i];
  14511. if (!this._vertexAttribArraysEnabled[ai.index]) {
  14512. this._gl.enableVertexAttribArray(ai.index);
  14513. this._vertexAttribArraysEnabled[ai.index] = true;
  14514. }
  14515. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  14516. this._gl.vertexAttribDivisor(ai.index, 1);
  14517. this._currentInstanceLocations.push(ai.index);
  14518. this._currentInstanceBuffers.push(instancesBuffer);
  14519. }
  14520. }
  14521. else {
  14522. for (var index = 0; index < 4; index++) {
  14523. var offsetLocation = offsetLocations[index];
  14524. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  14525. this._gl.enableVertexAttribArray(offsetLocation);
  14526. this._vertexAttribArraysEnabled[offsetLocation] = true;
  14527. }
  14528. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  14529. this._gl.vertexAttribDivisor(offsetLocation, 1);
  14530. this._currentInstanceLocations.push(offsetLocation);
  14531. this._currentInstanceBuffers.push(instancesBuffer);
  14532. }
  14533. }
  14534. };
  14535. /**
  14536. * Apply all cached states (depth, culling, stencil and alpha)
  14537. */
  14538. Engine.prototype.applyStates = function () {
  14539. this._depthCullingState.apply(this._gl);
  14540. this._stencilState.apply(this._gl);
  14541. this._alphaState.apply(this._gl);
  14542. };
  14543. /**
  14544. * Send a draw order
  14545. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14546. * @param indexStart defines the starting index
  14547. * @param indexCount defines the number of index to draw
  14548. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14549. */
  14550. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  14551. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  14552. };
  14553. /**
  14554. * Draw a list of points
  14555. * @param verticesStart defines the index of first vertex to draw
  14556. * @param verticesCount defines the count of vertices to draw
  14557. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14558. */
  14559. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  14560. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  14561. };
  14562. /**
  14563. * Draw a list of unindexed primitives
  14564. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14565. * @param verticesStart defines the index of first vertex to draw
  14566. * @param verticesCount defines the count of vertices to draw
  14567. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14568. */
  14569. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  14570. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  14571. };
  14572. /**
  14573. * Draw a list of indexed primitives
  14574. * @param fillMode defines the primitive to use
  14575. * @param indexStart defines the starting index
  14576. * @param indexCount defines the number of index to draw
  14577. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14578. */
  14579. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  14580. // Apply states
  14581. this.applyStates();
  14582. this._drawCalls.addCount(1, false);
  14583. // Render
  14584. var drawMode = this._drawMode(fillMode);
  14585. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  14586. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  14587. if (instancesCount) {
  14588. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  14589. }
  14590. else {
  14591. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  14592. }
  14593. };
  14594. /**
  14595. * Draw a list of unindexed primitives
  14596. * @param fillMode defines the primitive to use
  14597. * @param verticesStart defines the index of first vertex to draw
  14598. * @param verticesCount defines the count of vertices to draw
  14599. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14600. */
  14601. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  14602. // Apply states
  14603. this.applyStates();
  14604. this._drawCalls.addCount(1, false);
  14605. var drawMode = this._drawMode(fillMode);
  14606. if (instancesCount) {
  14607. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  14608. }
  14609. else {
  14610. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  14611. }
  14612. };
  14613. Engine.prototype._drawMode = function (fillMode) {
  14614. switch (fillMode) {
  14615. // Triangle views
  14616. case BABYLON.Material.TriangleFillMode:
  14617. return this._gl.TRIANGLES;
  14618. case BABYLON.Material.PointFillMode:
  14619. return this._gl.POINTS;
  14620. case BABYLON.Material.WireFrameFillMode:
  14621. return this._gl.LINES;
  14622. // Draw modes
  14623. case BABYLON.Material.PointListDrawMode:
  14624. return this._gl.POINTS;
  14625. case BABYLON.Material.LineListDrawMode:
  14626. return this._gl.LINES;
  14627. case BABYLON.Material.LineLoopDrawMode:
  14628. return this._gl.LINE_LOOP;
  14629. case BABYLON.Material.LineStripDrawMode:
  14630. return this._gl.LINE_STRIP;
  14631. case BABYLON.Material.TriangleStripDrawMode:
  14632. return this._gl.TRIANGLE_STRIP;
  14633. case BABYLON.Material.TriangleFanDrawMode:
  14634. return this._gl.TRIANGLE_FAN;
  14635. default:
  14636. return this._gl.TRIANGLES;
  14637. }
  14638. };
  14639. // Shaders
  14640. /** @hidden */
  14641. Engine.prototype._releaseEffect = function (effect) {
  14642. if (this._compiledEffects[effect._key]) {
  14643. delete this._compiledEffects[effect._key];
  14644. this._deleteProgram(effect.getProgram());
  14645. }
  14646. };
  14647. /** @hidden */
  14648. Engine.prototype._deleteProgram = function (program) {
  14649. if (program) {
  14650. program.__SPECTOR_rebuildProgram = null;
  14651. if (program.transformFeedback) {
  14652. this.deleteTransformFeedback(program.transformFeedback);
  14653. program.transformFeedback = null;
  14654. }
  14655. this._gl.deleteProgram(program);
  14656. }
  14657. };
  14658. /**
  14659. * Create a new effect (used to store vertex/fragment shaders)
  14660. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14661. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14662. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14663. * @param samplers defines an array of string used to represent textures
  14664. * @param defines defines the string containing the defines to use to compile the shaders
  14665. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14666. * @param onCompiled defines a function to call when the effect creation is successful
  14667. * @param onError defines a function to call when the effect creation has failed
  14668. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14669. * @returns the new Effect
  14670. */
  14671. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14672. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14673. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14674. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14675. if (this._compiledEffects[name]) {
  14676. var compiledEffect = this._compiledEffects[name];
  14677. if (onCompiled && compiledEffect.isReady()) {
  14678. onCompiled(compiledEffect);
  14679. }
  14680. return compiledEffect;
  14681. }
  14682. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14683. effect._key = name;
  14684. this._compiledEffects[name] = effect;
  14685. return effect;
  14686. };
  14687. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  14688. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  14689. };
  14690. Engine.prototype._compileRawShader = function (source, type) {
  14691. var gl = this._gl;
  14692. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  14693. if (!shader) {
  14694. throw new Error("Something went wrong while compile the shader.");
  14695. }
  14696. gl.shaderSource(shader, source);
  14697. gl.compileShader(shader);
  14698. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  14699. var log = gl.getShaderInfoLog(shader);
  14700. if (log) {
  14701. throw new Error(log);
  14702. }
  14703. }
  14704. return shader;
  14705. };
  14706. /**
  14707. * Directly creates a webGL program
  14708. * @param vertexCode defines the vertex shader code to use
  14709. * @param fragmentCode defines the fragment shader code to use
  14710. * @param context defines the webGL context to use (if not set, the current one will be used)
  14711. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14712. * @returns the new webGL program
  14713. */
  14714. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14715. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14716. context = context || this._gl;
  14717. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  14718. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  14719. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14720. };
  14721. /**
  14722. * Creates a webGL program
  14723. * @param vertexCode defines the vertex shader code to use
  14724. * @param fragmentCode defines the fragment shader code to use
  14725. * @param defines defines the string containing the defines to use to compile the shaders
  14726. * @param context defines the webGL context to use (if not set, the current one will be used)
  14727. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14728. * @returns the new webGL program
  14729. */
  14730. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14731. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14732. context = context || this._gl;
  14733. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14734. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14735. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  14736. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  14737. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14738. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14739. return program;
  14740. };
  14741. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14742. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14743. var shaderProgram = context.createProgram();
  14744. if (!shaderProgram) {
  14745. throw new Error("Unable to create program");
  14746. }
  14747. context.attachShader(shaderProgram, vertexShader);
  14748. context.attachShader(shaderProgram, fragmentShader);
  14749. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14750. var transformFeedback = this.createTransformFeedback();
  14751. this.bindTransformFeedback(transformFeedback);
  14752. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14753. shaderProgram.transformFeedback = transformFeedback;
  14754. }
  14755. context.linkProgram(shaderProgram);
  14756. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14757. this.bindTransformFeedback(null);
  14758. }
  14759. shaderProgram.context = context;
  14760. shaderProgram.vertexShader = vertexShader;
  14761. shaderProgram.fragmentShader = fragmentShader;
  14762. if (!this._caps.parallelShaderCompile) {
  14763. this._finalizeProgram(shaderProgram);
  14764. }
  14765. else {
  14766. shaderProgram.isParallelCompiled = true;
  14767. }
  14768. return shaderProgram;
  14769. };
  14770. Engine.prototype._finalizeProgram = function (shaderProgram) {
  14771. var context = shaderProgram.context;
  14772. var vertexShader = shaderProgram.vertexShader;
  14773. var fragmentShader = shaderProgram.fragmentShader;
  14774. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14775. if (!linked) {
  14776. var error = context.getProgramInfoLog(shaderProgram);
  14777. if (error) {
  14778. throw new Error(error);
  14779. }
  14780. }
  14781. if (this.validateShaderPrograms) {
  14782. context.validateProgram(shaderProgram);
  14783. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14784. if (!validated) {
  14785. var error = context.getProgramInfoLog(shaderProgram);
  14786. if (error) {
  14787. throw new Error(error);
  14788. }
  14789. }
  14790. }
  14791. context.deleteShader(vertexShader);
  14792. context.deleteShader(fragmentShader);
  14793. shaderProgram.context = undefined;
  14794. shaderProgram.vertexShader = undefined;
  14795. shaderProgram.fragmentShader = undefined;
  14796. if (shaderProgram.onCompiled) {
  14797. shaderProgram.onCompiled();
  14798. shaderProgram.onCompiled = undefined;
  14799. }
  14800. };
  14801. /** @hidden */
  14802. Engine.prototype._isProgramCompiled = function (shaderProgram) {
  14803. if (!shaderProgram.isParallelCompiled) {
  14804. return true;
  14805. }
  14806. if (this._gl.getProgramParameter(shaderProgram, this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)) {
  14807. this._finalizeProgram(shaderProgram);
  14808. return true;
  14809. }
  14810. return false;
  14811. };
  14812. /** @hidden */
  14813. Engine.prototype._executeWhenProgramIsCompiled = function (shaderProgram, action) {
  14814. if (!shaderProgram.isParallelCompiled) {
  14815. action();
  14816. return;
  14817. }
  14818. shaderProgram.onCompiled = action;
  14819. };
  14820. /**
  14821. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14822. * @param shaderProgram defines the webGL program to use
  14823. * @param uniformsNames defines the list of uniform names
  14824. * @returns an array of webGL uniform locations
  14825. */
  14826. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14827. var results = new Array();
  14828. for (var index = 0; index < uniformsNames.length; index++) {
  14829. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14830. }
  14831. return results;
  14832. };
  14833. /**
  14834. * Gets the lsit of active attributes for a given webGL program
  14835. * @param shaderProgram defines the webGL program to use
  14836. * @param attributesNames defines the list of attribute names to get
  14837. * @returns an array of indices indicating the offset of each attribute
  14838. */
  14839. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14840. var results = [];
  14841. for (var index = 0; index < attributesNames.length; index++) {
  14842. try {
  14843. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14844. }
  14845. catch (e) {
  14846. results.push(-1);
  14847. }
  14848. }
  14849. return results;
  14850. };
  14851. /**
  14852. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14853. * @param effect defines the effect to activate
  14854. */
  14855. Engine.prototype.enableEffect = function (effect) {
  14856. if (!effect || effect === this._currentEffect) {
  14857. return;
  14858. }
  14859. // Use program
  14860. this.bindSamplers(effect);
  14861. this._currentEffect = effect;
  14862. if (effect.onBind) {
  14863. effect.onBind(effect);
  14864. }
  14865. if (effect._onBindObservable) {
  14866. effect._onBindObservable.notifyObservers(effect);
  14867. }
  14868. };
  14869. /**
  14870. * Set the value of an uniform to an array of int32
  14871. * @param uniform defines the webGL uniform location where to store the value
  14872. * @param array defines the array of int32 to store
  14873. */
  14874. Engine.prototype.setIntArray = function (uniform, array) {
  14875. if (!uniform) {
  14876. return;
  14877. }
  14878. this._gl.uniform1iv(uniform, array);
  14879. };
  14880. /**
  14881. * Set the value of an uniform to an array of int32 (stored as vec2)
  14882. * @param uniform defines the webGL uniform location where to store the value
  14883. * @param array defines the array of int32 to store
  14884. */
  14885. Engine.prototype.setIntArray2 = function (uniform, array) {
  14886. if (!uniform || array.length % 2 !== 0) {
  14887. return;
  14888. }
  14889. this._gl.uniform2iv(uniform, array);
  14890. };
  14891. /**
  14892. * Set the value of an uniform to an array of int32 (stored as vec3)
  14893. * @param uniform defines the webGL uniform location where to store the value
  14894. * @param array defines the array of int32 to store
  14895. */
  14896. Engine.prototype.setIntArray3 = function (uniform, array) {
  14897. if (!uniform || array.length % 3 !== 0) {
  14898. return;
  14899. }
  14900. this._gl.uniform3iv(uniform, array);
  14901. };
  14902. /**
  14903. * Set the value of an uniform to an array of int32 (stored as vec4)
  14904. * @param uniform defines the webGL uniform location where to store the value
  14905. * @param array defines the array of int32 to store
  14906. */
  14907. Engine.prototype.setIntArray4 = function (uniform, array) {
  14908. if (!uniform || array.length % 4 !== 0) {
  14909. return;
  14910. }
  14911. this._gl.uniform4iv(uniform, array);
  14912. };
  14913. /**
  14914. * Set the value of an uniform to an array of float32
  14915. * @param uniform defines the webGL uniform location where to store the value
  14916. * @param array defines the array of float32 to store
  14917. */
  14918. Engine.prototype.setFloatArray = function (uniform, array) {
  14919. if (!uniform) {
  14920. return;
  14921. }
  14922. this._gl.uniform1fv(uniform, array);
  14923. };
  14924. /**
  14925. * Set the value of an uniform to an array of float32 (stored as vec2)
  14926. * @param uniform defines the webGL uniform location where to store the value
  14927. * @param array defines the array of float32 to store
  14928. */
  14929. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14930. if (!uniform || array.length % 2 !== 0) {
  14931. return;
  14932. }
  14933. this._gl.uniform2fv(uniform, array);
  14934. };
  14935. /**
  14936. * Set the value of an uniform to an array of float32 (stored as vec3)
  14937. * @param uniform defines the webGL uniform location where to store the value
  14938. * @param array defines the array of float32 to store
  14939. */
  14940. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14941. if (!uniform || array.length % 3 !== 0) {
  14942. return;
  14943. }
  14944. this._gl.uniform3fv(uniform, array);
  14945. };
  14946. /**
  14947. * Set the value of an uniform to an array of float32 (stored as vec4)
  14948. * @param uniform defines the webGL uniform location where to store the value
  14949. * @param array defines the array of float32 to store
  14950. */
  14951. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14952. if (!uniform || array.length % 4 !== 0) {
  14953. return;
  14954. }
  14955. this._gl.uniform4fv(uniform, array);
  14956. };
  14957. /**
  14958. * Set the value of an uniform to an array of number
  14959. * @param uniform defines the webGL uniform location where to store the value
  14960. * @param array defines the array of number to store
  14961. */
  14962. Engine.prototype.setArray = function (uniform, array) {
  14963. if (!uniform) {
  14964. return;
  14965. }
  14966. this._gl.uniform1fv(uniform, array);
  14967. };
  14968. /**
  14969. * Set the value of an uniform to an array of number (stored as vec2)
  14970. * @param uniform defines the webGL uniform location where to store the value
  14971. * @param array defines the array of number to store
  14972. */
  14973. Engine.prototype.setArray2 = function (uniform, array) {
  14974. if (!uniform || array.length % 2 !== 0) {
  14975. return;
  14976. }
  14977. this._gl.uniform2fv(uniform, array);
  14978. };
  14979. /**
  14980. * Set the value of an uniform to an array of number (stored as vec3)
  14981. * @param uniform defines the webGL uniform location where to store the value
  14982. * @param array defines the array of number to store
  14983. */
  14984. Engine.prototype.setArray3 = function (uniform, array) {
  14985. if (!uniform || array.length % 3 !== 0) {
  14986. return;
  14987. }
  14988. this._gl.uniform3fv(uniform, array);
  14989. };
  14990. /**
  14991. * Set the value of an uniform to an array of number (stored as vec4)
  14992. * @param uniform defines the webGL uniform location where to store the value
  14993. * @param array defines the array of number to store
  14994. */
  14995. Engine.prototype.setArray4 = function (uniform, array) {
  14996. if (!uniform || array.length % 4 !== 0) {
  14997. return;
  14998. }
  14999. this._gl.uniform4fv(uniform, array);
  15000. };
  15001. /**
  15002. * Set the value of an uniform to an array of float32 (stored as matrices)
  15003. * @param uniform defines the webGL uniform location where to store the value
  15004. * @param matrices defines the array of float32 to store
  15005. */
  15006. Engine.prototype.setMatrices = function (uniform, matrices) {
  15007. if (!uniform) {
  15008. return;
  15009. }
  15010. this._gl.uniformMatrix4fv(uniform, false, matrices);
  15011. };
  15012. /**
  15013. * Set the value of an uniform to a matrix
  15014. * @param uniform defines the webGL uniform location where to store the value
  15015. * @param matrix defines the matrix to store
  15016. */
  15017. Engine.prototype.setMatrix = function (uniform, matrix) {
  15018. if (!uniform) {
  15019. return;
  15020. }
  15021. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  15022. };
  15023. /**
  15024. * Set the value of an uniform to a matrix (3x3)
  15025. * @param uniform defines the webGL uniform location where to store the value
  15026. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  15027. */
  15028. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  15029. if (!uniform) {
  15030. return;
  15031. }
  15032. this._gl.uniformMatrix3fv(uniform, false, matrix);
  15033. };
  15034. /**
  15035. * Set the value of an uniform to a matrix (2x2)
  15036. * @param uniform defines the webGL uniform location where to store the value
  15037. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  15038. */
  15039. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  15040. if (!uniform) {
  15041. return;
  15042. }
  15043. this._gl.uniformMatrix2fv(uniform, false, matrix);
  15044. };
  15045. /**
  15046. * Set the value of an uniform to a number (int)
  15047. * @param uniform defines the webGL uniform location where to store the value
  15048. * @param value defines the int number to store
  15049. */
  15050. Engine.prototype.setInt = function (uniform, value) {
  15051. if (!uniform) {
  15052. return;
  15053. }
  15054. this._gl.uniform1i(uniform, value);
  15055. };
  15056. /**
  15057. * Set the value of an uniform to a number (float)
  15058. * @param uniform defines the webGL uniform location where to store the value
  15059. * @param value defines the float number to store
  15060. */
  15061. Engine.prototype.setFloat = function (uniform, value) {
  15062. if (!uniform) {
  15063. return;
  15064. }
  15065. this._gl.uniform1f(uniform, value);
  15066. };
  15067. /**
  15068. * Set the value of an uniform to a vec2
  15069. * @param uniform defines the webGL uniform location where to store the value
  15070. * @param x defines the 1st component of the value
  15071. * @param y defines the 2nd component of the value
  15072. */
  15073. Engine.prototype.setFloat2 = function (uniform, x, y) {
  15074. if (!uniform) {
  15075. return;
  15076. }
  15077. this._gl.uniform2f(uniform, x, y);
  15078. };
  15079. /**
  15080. * Set the value of an uniform to a vec3
  15081. * @param uniform defines the webGL uniform location where to store the value
  15082. * @param x defines the 1st component of the value
  15083. * @param y defines the 2nd component of the value
  15084. * @param z defines the 3rd component of the value
  15085. */
  15086. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  15087. if (!uniform) {
  15088. return;
  15089. }
  15090. this._gl.uniform3f(uniform, x, y, z);
  15091. };
  15092. /**
  15093. * Set the value of an uniform to a boolean
  15094. * @param uniform defines the webGL uniform location where to store the value
  15095. * @param bool defines the boolean to store
  15096. */
  15097. Engine.prototype.setBool = function (uniform, bool) {
  15098. if (!uniform) {
  15099. return;
  15100. }
  15101. this._gl.uniform1i(uniform, bool);
  15102. };
  15103. /**
  15104. * Set the value of an uniform to a vec4
  15105. * @param uniform defines the webGL uniform location where to store the value
  15106. * @param x defines the 1st component of the value
  15107. * @param y defines the 2nd component of the value
  15108. * @param z defines the 3rd component of the value
  15109. * @param w defines the 4th component of the value
  15110. */
  15111. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  15112. if (!uniform) {
  15113. return;
  15114. }
  15115. this._gl.uniform4f(uniform, x, y, z, w);
  15116. };
  15117. /**
  15118. * Set the value of an uniform to a Color3
  15119. * @param uniform defines the webGL uniform location where to store the value
  15120. * @param color3 defines the color to store
  15121. */
  15122. Engine.prototype.setColor3 = function (uniform, color3) {
  15123. if (!uniform) {
  15124. return;
  15125. }
  15126. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  15127. };
  15128. /**
  15129. * Set the value of an uniform to a Color3 and an alpha value
  15130. * @param uniform defines the webGL uniform location where to store the value
  15131. * @param color3 defines the color to store
  15132. * @param alpha defines the alpha component to store
  15133. */
  15134. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  15135. if (!uniform) {
  15136. return;
  15137. }
  15138. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  15139. };
  15140. /**
  15141. * Sets a Color4 on a uniform variable
  15142. * @param uniform defines the uniform location
  15143. * @param color4 defines the value to be set
  15144. */
  15145. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  15146. if (!uniform) {
  15147. return;
  15148. }
  15149. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  15150. };
  15151. // States
  15152. /**
  15153. * Set various states to the webGL context
  15154. * @param culling defines backface culling state
  15155. * @param zOffset defines the value to apply to zOffset (0 by default)
  15156. * @param force defines if states must be applied even if cache is up to date
  15157. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  15158. */
  15159. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  15160. if (zOffset === void 0) { zOffset = 0; }
  15161. if (reverseSide === void 0) { reverseSide = false; }
  15162. // Culling
  15163. if (this._depthCullingState.cull !== culling || force) {
  15164. this._depthCullingState.cull = culling;
  15165. }
  15166. // Cull face
  15167. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  15168. if (this._depthCullingState.cullFace !== cullFace || force) {
  15169. this._depthCullingState.cullFace = cullFace;
  15170. }
  15171. // Z offset
  15172. this.setZOffset(zOffset);
  15173. // Front face
  15174. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  15175. if (this._depthCullingState.frontFace !== frontFace || force) {
  15176. this._depthCullingState.frontFace = frontFace;
  15177. }
  15178. };
  15179. /**
  15180. * Set the z offset to apply to current rendering
  15181. * @param value defines the offset to apply
  15182. */
  15183. Engine.prototype.setZOffset = function (value) {
  15184. this._depthCullingState.zOffset = value;
  15185. };
  15186. /**
  15187. * Gets the current value of the zOffset
  15188. * @returns the current zOffset state
  15189. */
  15190. Engine.prototype.getZOffset = function () {
  15191. return this._depthCullingState.zOffset;
  15192. };
  15193. /**
  15194. * Enable or disable depth buffering
  15195. * @param enable defines the state to set
  15196. */
  15197. Engine.prototype.setDepthBuffer = function (enable) {
  15198. this._depthCullingState.depthTest = enable;
  15199. };
  15200. /**
  15201. * Gets a boolean indicating if depth writing is enabled
  15202. * @returns the current depth writing state
  15203. */
  15204. Engine.prototype.getDepthWrite = function () {
  15205. return this._depthCullingState.depthMask;
  15206. };
  15207. /**
  15208. * Enable or disable depth writing
  15209. * @param enable defines the state to set
  15210. */
  15211. Engine.prototype.setDepthWrite = function (enable) {
  15212. this._depthCullingState.depthMask = enable;
  15213. };
  15214. /**
  15215. * Enable or disable color writing
  15216. * @param enable defines the state to set
  15217. */
  15218. Engine.prototype.setColorWrite = function (enable) {
  15219. this._gl.colorMask(enable, enable, enable, enable);
  15220. this._colorWrite = enable;
  15221. };
  15222. /**
  15223. * Gets a boolean indicating if color writing is enabled
  15224. * @returns the current color writing state
  15225. */
  15226. Engine.prototype.getColorWrite = function () {
  15227. return this._colorWrite;
  15228. };
  15229. /**
  15230. * Sets alpha constants used by some alpha blending modes
  15231. * @param r defines the red component
  15232. * @param g defines the green component
  15233. * @param b defines the blue component
  15234. * @param a defines the alpha component
  15235. */
  15236. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  15237. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  15238. };
  15239. /**
  15240. * Sets the current alpha mode
  15241. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  15242. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  15243. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  15244. */
  15245. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  15246. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  15247. if (this._alphaMode === mode) {
  15248. return;
  15249. }
  15250. switch (mode) {
  15251. case Engine.ALPHA_DISABLE:
  15252. this._alphaState.alphaBlend = false;
  15253. break;
  15254. case Engine.ALPHA_PREMULTIPLIED:
  15255. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  15256. this._alphaState.alphaBlend = true;
  15257. break;
  15258. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  15259. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15260. this._alphaState.alphaBlend = true;
  15261. break;
  15262. case Engine.ALPHA_COMBINE:
  15263. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  15264. this._alphaState.alphaBlend = true;
  15265. break;
  15266. case Engine.ALPHA_ONEONE:
  15267. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  15268. this._alphaState.alphaBlend = true;
  15269. break;
  15270. case Engine.ALPHA_ADD:
  15271. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  15272. this._alphaState.alphaBlend = true;
  15273. break;
  15274. case Engine.ALPHA_SUBTRACT:
  15275. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15276. this._alphaState.alphaBlend = true;
  15277. break;
  15278. case Engine.ALPHA_MULTIPLY:
  15279. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  15280. this._alphaState.alphaBlend = true;
  15281. break;
  15282. case Engine.ALPHA_MAXIMIZED:
  15283. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15284. this._alphaState.alphaBlend = true;
  15285. break;
  15286. case Engine.ALPHA_INTERPOLATE:
  15287. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  15288. this._alphaState.alphaBlend = true;
  15289. break;
  15290. case Engine.ALPHA_SCREENMODE:
  15291. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15292. this._alphaState.alphaBlend = true;
  15293. break;
  15294. }
  15295. if (!noDepthWriteChange) {
  15296. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  15297. }
  15298. this._alphaMode = mode;
  15299. };
  15300. /**
  15301. * Gets the current alpha mode
  15302. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  15303. * @returns the current alpha mode
  15304. */
  15305. Engine.prototype.getAlphaMode = function () {
  15306. return this._alphaMode;
  15307. };
  15308. // Textures
  15309. /**
  15310. * Clears the list of texture accessible through engine.
  15311. * This can help preventing texture load conflict due to name collision.
  15312. */
  15313. Engine.prototype.clearInternalTexturesCache = function () {
  15314. this._internalTexturesCache = [];
  15315. };
  15316. /**
  15317. * Force the entire cache to be cleared
  15318. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  15319. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  15320. */
  15321. Engine.prototype.wipeCaches = function (bruteForce) {
  15322. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  15323. return;
  15324. }
  15325. this._currentEffect = null;
  15326. this._viewportCached.x = 0;
  15327. this._viewportCached.y = 0;
  15328. this._viewportCached.z = 0;
  15329. this._viewportCached.w = 0;
  15330. if (bruteForce) {
  15331. this.resetTextureCache();
  15332. this._currentProgram = null;
  15333. this._stencilState.reset();
  15334. this._depthCullingState.reset();
  15335. this.setDepthFunctionToLessOrEqual();
  15336. this._alphaState.reset();
  15337. this._unpackFlipYCached = null;
  15338. }
  15339. this._resetVertexBufferBinding();
  15340. this._cachedIndexBuffer = null;
  15341. this._cachedEffectForVertexBuffers = null;
  15342. this._unbindVertexArrayObject();
  15343. this.bindIndexBuffer(null);
  15344. };
  15345. /**
  15346. * Set the compressed texture format to use, based on the formats you have, and the formats
  15347. * supported by the hardware / browser.
  15348. *
  15349. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  15350. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  15351. * to API arguments needed to compressed textures. This puts the burden on the container
  15352. * generator to house the arcane code for determining these for current & future formats.
  15353. *
  15354. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  15355. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  15356. *
  15357. * Note: The result of this call is not taken into account when a texture is base64.
  15358. *
  15359. * @param formatsAvailable defines the list of those format families you have created
  15360. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  15361. *
  15362. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  15363. * @returns The extension selected.
  15364. */
  15365. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  15366. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  15367. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  15368. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  15369. return this._textureFormatInUse = this._texturesSupported[i];
  15370. }
  15371. }
  15372. }
  15373. // actively set format to nothing, to allow this to be called more than once
  15374. // and possibly fail the 2nd time
  15375. this._textureFormatInUse = null;
  15376. return null;
  15377. };
  15378. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  15379. var gl = this._gl;
  15380. var magFilter = gl.NEAREST;
  15381. var minFilter = gl.NEAREST;
  15382. switch (samplingMode) {
  15383. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  15384. magFilter = gl.LINEAR;
  15385. if (generateMipMaps) {
  15386. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15387. }
  15388. else {
  15389. minFilter = gl.LINEAR;
  15390. }
  15391. break;
  15392. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  15393. magFilter = gl.LINEAR;
  15394. if (generateMipMaps) {
  15395. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15396. }
  15397. else {
  15398. minFilter = gl.LINEAR;
  15399. }
  15400. break;
  15401. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  15402. magFilter = gl.NEAREST;
  15403. if (generateMipMaps) {
  15404. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15405. }
  15406. else {
  15407. minFilter = gl.NEAREST;
  15408. }
  15409. break;
  15410. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  15411. magFilter = gl.NEAREST;
  15412. if (generateMipMaps) {
  15413. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15414. }
  15415. else {
  15416. minFilter = gl.NEAREST;
  15417. }
  15418. break;
  15419. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  15420. magFilter = gl.NEAREST;
  15421. if (generateMipMaps) {
  15422. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15423. }
  15424. else {
  15425. minFilter = gl.LINEAR;
  15426. }
  15427. break;
  15428. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  15429. magFilter = gl.NEAREST;
  15430. if (generateMipMaps) {
  15431. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15432. }
  15433. else {
  15434. minFilter = gl.LINEAR;
  15435. }
  15436. break;
  15437. case Engine.TEXTURE_NEAREST_LINEAR:
  15438. magFilter = gl.NEAREST;
  15439. minFilter = gl.LINEAR;
  15440. break;
  15441. case Engine.TEXTURE_NEAREST_NEAREST:
  15442. magFilter = gl.NEAREST;
  15443. minFilter = gl.NEAREST;
  15444. break;
  15445. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  15446. magFilter = gl.LINEAR;
  15447. if (generateMipMaps) {
  15448. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15449. }
  15450. else {
  15451. minFilter = gl.NEAREST;
  15452. }
  15453. break;
  15454. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  15455. magFilter = gl.LINEAR;
  15456. if (generateMipMaps) {
  15457. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15458. }
  15459. else {
  15460. minFilter = gl.NEAREST;
  15461. }
  15462. break;
  15463. case Engine.TEXTURE_LINEAR_LINEAR:
  15464. magFilter = gl.LINEAR;
  15465. minFilter = gl.LINEAR;
  15466. break;
  15467. case Engine.TEXTURE_LINEAR_NEAREST:
  15468. magFilter = gl.LINEAR;
  15469. minFilter = gl.NEAREST;
  15470. break;
  15471. }
  15472. return {
  15473. min: minFilter,
  15474. mag: magFilter
  15475. };
  15476. };
  15477. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  15478. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15479. var img;
  15480. var onload = function () {
  15481. loadedImages[index] = img;
  15482. loadedImages._internalCount++;
  15483. if (scene) {
  15484. scene._removePendingData(img);
  15485. }
  15486. if (loadedImages._internalCount === 6) {
  15487. onfinish(loadedImages);
  15488. }
  15489. };
  15490. var onerror = function (message, exception) {
  15491. if (scene) {
  15492. scene._removePendingData(img);
  15493. }
  15494. if (onErrorCallBack) {
  15495. onErrorCallBack(message, exception);
  15496. }
  15497. };
  15498. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.offlineProvider : null);
  15499. if (scene) {
  15500. scene._addPendingData(img);
  15501. }
  15502. };
  15503. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  15504. if (onError === void 0) { onError = null; }
  15505. var loadedImages = [];
  15506. loadedImages._internalCount = 0;
  15507. for (var index = 0; index < 6; index++) {
  15508. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  15509. }
  15510. };
  15511. /** @hidden */
  15512. Engine.prototype._createTexture = function () {
  15513. var texture = this._gl.createTexture();
  15514. if (!texture) {
  15515. throw new Error("Unable to create texture");
  15516. }
  15517. return texture;
  15518. };
  15519. /**
  15520. * Usually called from BABYLON.Texture.ts.
  15521. * Passed information to create a WebGLTexture
  15522. * @param urlArg defines a value which contains one of the following:
  15523. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  15524. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  15525. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  15526. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  15527. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  15528. * @param scene needed for loading to the correct scene
  15529. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  15530. * @param onLoad optional callback to be called upon successful completion
  15531. * @param onError optional callback to be called upon failure
  15532. * @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
  15533. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  15534. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  15535. * @param forcedExtension defines the extension to use to pick the right loader
  15536. * @returns a InternalTexture for assignment back into BABYLON.Texture
  15537. */
  15538. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  15539. var _this = this;
  15540. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15541. if (onLoad === void 0) { onLoad = null; }
  15542. if (onError === void 0) { onError = null; }
  15543. if (buffer === void 0) { buffer = null; }
  15544. if (fallback === void 0) { fallback = null; }
  15545. if (format === void 0) { format = null; }
  15546. if (forcedExtension === void 0) { forcedExtension = null; }
  15547. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  15548. var fromData = url.substr(0, 5) === "data:";
  15549. var fromBlob = url.substr(0, 5) === "blob:";
  15550. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  15551. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  15552. // establish the file extension, if possible
  15553. var lastDot = url.lastIndexOf('.');
  15554. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  15555. var loader = null;
  15556. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15557. var availableLoader = _a[_i];
  15558. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  15559. loader = availableLoader;
  15560. break;
  15561. }
  15562. }
  15563. if (loader) {
  15564. url = loader.transformUrl(url, this._textureFormatInUse);
  15565. }
  15566. if (scene) {
  15567. scene._addPendingData(texture);
  15568. }
  15569. texture.url = url;
  15570. texture.generateMipMaps = !noMipmap;
  15571. texture.samplingMode = samplingMode;
  15572. texture.invertY = invertY;
  15573. if (!this._doNotHandleContextLost) {
  15574. // Keep a link to the buffer only if we plan to handle context lost
  15575. texture._buffer = buffer;
  15576. }
  15577. var onLoadObserver = null;
  15578. if (onLoad && !fallback) {
  15579. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  15580. }
  15581. if (!fallback) {
  15582. this._internalTexturesCache.push(texture);
  15583. }
  15584. var onInternalError = function (message, exception) {
  15585. if (scene) {
  15586. scene._removePendingData(texture);
  15587. }
  15588. var customFallback = false;
  15589. if (loader) {
  15590. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  15591. if (fallbackUrl) {
  15592. // Add Back
  15593. customFallback = true;
  15594. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15595. }
  15596. }
  15597. if (!customFallback) {
  15598. if (onLoadObserver) {
  15599. texture.onLoadedObservable.remove(onLoadObserver);
  15600. }
  15601. if (BABYLON.Tools.UseFallbackTexture) {
  15602. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15603. }
  15604. }
  15605. if (onError) {
  15606. onError(message || "Unknown error", exception);
  15607. }
  15608. };
  15609. // processing for non-image formats
  15610. if (loader) {
  15611. var callback = function (data) {
  15612. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  15613. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  15614. done();
  15615. return false;
  15616. }, samplingMode);
  15617. });
  15618. };
  15619. if (!buffer) {
  15620. this._loadFile(url, callback, undefined, scene ? scene.offlineProvider : undefined, true, function (request, exception) {
  15621. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  15622. });
  15623. }
  15624. else {
  15625. callback(buffer);
  15626. }
  15627. }
  15628. else {
  15629. var onload = function (img) {
  15630. if (fromBlob && !_this._doNotHandleContextLost) {
  15631. // We need to store the image if we need to rebuild the texture
  15632. // in case of a webgl context lost
  15633. texture._buffer = img;
  15634. }
  15635. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  15636. var gl = _this._gl;
  15637. var isPot = (img.width === potWidth && img.height === potHeight);
  15638. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  15639. if (isPot) {
  15640. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15641. return false;
  15642. }
  15643. var maxTextureSize = _this._caps.maxTextureSize;
  15644. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  15645. _this._prepareWorkingCanvas();
  15646. if (!_this._workingCanvas || !_this._workingContext) {
  15647. return false;
  15648. }
  15649. _this._workingCanvas.width = potWidth;
  15650. _this._workingCanvas.height = potHeight;
  15651. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  15652. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15653. texture.width = potWidth;
  15654. texture.height = potHeight;
  15655. return false;
  15656. }
  15657. else {
  15658. // Using shaders when possible to rescale because canvas.drawImage is lossy
  15659. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15660. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  15661. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15662. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15663. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15664. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15665. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15666. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  15667. _this._releaseTexture(source_1);
  15668. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15669. continuationCallback();
  15670. });
  15671. }
  15672. return true;
  15673. }, samplingMode);
  15674. };
  15675. if (!fromData || isBase64) {
  15676. if (buffer instanceof HTMLImageElement) {
  15677. onload(buffer);
  15678. }
  15679. else {
  15680. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.offlineProvider : null);
  15681. }
  15682. }
  15683. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  15684. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.offlineProvider : null);
  15685. }
  15686. else {
  15687. onload(buffer);
  15688. }
  15689. }
  15690. return texture;
  15691. };
  15692. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  15693. var _this = this;
  15694. var rtt = this.createRenderTargetTexture({
  15695. width: destination.width,
  15696. height: destination.height,
  15697. }, {
  15698. generateMipMaps: false,
  15699. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  15700. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  15701. generateDepthBuffer: false,
  15702. generateStencilBuffer: false
  15703. });
  15704. if (!this._rescalePostProcess) {
  15705. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  15706. }
  15707. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  15708. _this._rescalePostProcess.onApply = function (effect) {
  15709. effect._bindTexture("textureSampler", source);
  15710. };
  15711. var hostingScene = scene;
  15712. if (!hostingScene) {
  15713. hostingScene = _this.scenes[_this.scenes.length - 1];
  15714. }
  15715. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  15716. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  15717. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  15718. _this.unBindFramebuffer(rtt);
  15719. _this._releaseTexture(rtt);
  15720. if (onComplete) {
  15721. onComplete();
  15722. }
  15723. });
  15724. };
  15725. /**
  15726. * Update a raw texture
  15727. * @param texture defines the texture to update
  15728. * @param data defines the data to store in the texture
  15729. * @param format defines the format of the data
  15730. * @param invertY defines if data must be stored with Y axis inverted
  15731. * @param compression defines the compression used (null by default)
  15732. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15733. */
  15734. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  15735. if (compression === void 0) { compression = null; }
  15736. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15737. if (!texture) {
  15738. return;
  15739. }
  15740. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  15741. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  15742. // babylon's internalFormat but gl's texImage2D format
  15743. var internalFormat = this._getInternalFormat(format);
  15744. var textureType = this._getWebGLTextureType(type);
  15745. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15746. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15747. if (!this._doNotHandleContextLost) {
  15748. texture._bufferView = data;
  15749. texture.format = format;
  15750. texture.type = type;
  15751. texture.invertY = invertY;
  15752. texture._compression = compression;
  15753. }
  15754. if (texture.width % 4 !== 0) {
  15755. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15756. }
  15757. if (compression && data) {
  15758. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  15759. }
  15760. else {
  15761. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  15762. }
  15763. if (texture.generateMipMaps) {
  15764. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15765. }
  15766. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15767. // this.resetTextureCache();
  15768. texture.isReady = true;
  15769. };
  15770. /**
  15771. * Creates a raw texture
  15772. * @param data defines the data to store in the texture
  15773. * @param width defines the width of the texture
  15774. * @param height defines the height of the texture
  15775. * @param format defines the format of the data
  15776. * @param generateMipMaps defines if the engine should generate the mip levels
  15777. * @param invertY defines if data must be stored with Y axis inverted
  15778. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15779. * @param compression defines the compression used (null by default)
  15780. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15781. * @returns the raw texture inside an InternalTexture
  15782. */
  15783. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  15784. if (compression === void 0) { compression = null; }
  15785. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15786. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  15787. texture.baseWidth = width;
  15788. texture.baseHeight = height;
  15789. texture.width = width;
  15790. texture.height = height;
  15791. texture.format = format;
  15792. texture.generateMipMaps = generateMipMaps;
  15793. texture.samplingMode = samplingMode;
  15794. texture.invertY = invertY;
  15795. texture._compression = compression;
  15796. texture.type = type;
  15797. if (!this._doNotHandleContextLost) {
  15798. texture._bufferView = data;
  15799. }
  15800. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15801. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15802. // Filters
  15803. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15804. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15805. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15806. if (generateMipMaps) {
  15807. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15808. }
  15809. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15810. this._internalTexturesCache.push(texture);
  15811. return texture;
  15812. };
  15813. /** @hidden */
  15814. Engine.prototype._unpackFlipY = function (value) {
  15815. if (this._unpackFlipYCached !== value) {
  15816. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15817. if (this.enableUnpackFlipYCached) {
  15818. this._unpackFlipYCached = value;
  15819. }
  15820. }
  15821. };
  15822. /** @hidden */
  15823. Engine.prototype._getUnpackAlignement = function () {
  15824. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  15825. };
  15826. /**
  15827. * Creates a dynamic texture
  15828. * @param width defines the width of the texture
  15829. * @param height defines the height of the texture
  15830. * @param generateMipMaps defines if the engine should generate the mip levels
  15831. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15832. * @returns the dynamic texture inside an InternalTexture
  15833. */
  15834. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15835. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15836. texture.baseWidth = width;
  15837. texture.baseHeight = height;
  15838. if (generateMipMaps) {
  15839. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15840. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15841. }
  15842. // this.resetTextureCache();
  15843. texture.width = width;
  15844. texture.height = height;
  15845. texture.isReady = false;
  15846. texture.generateMipMaps = generateMipMaps;
  15847. texture.samplingMode = samplingMode;
  15848. this.updateTextureSamplingMode(samplingMode, texture);
  15849. this._internalTexturesCache.push(texture);
  15850. return texture;
  15851. };
  15852. /**
  15853. * Update the sampling mode of a given texture
  15854. * @param samplingMode defines the required sampling mode
  15855. * @param texture defines the texture to update
  15856. */
  15857. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15858. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  15859. if (texture.isCube) {
  15860. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15861. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15862. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15863. }
  15864. else if (texture.is3D) {
  15865. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15866. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15867. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15868. }
  15869. else {
  15870. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15871. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15872. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15873. }
  15874. texture.samplingMode = samplingMode;
  15875. };
  15876. /**
  15877. * Update the content of a dynamic texture
  15878. * @param texture defines the texture to update
  15879. * @param canvas defines the canvas containing the source
  15880. * @param invertY defines if data must be stored with Y axis inverted
  15881. * @param premulAlpha defines if alpha is stored as premultiplied
  15882. * @param format defines the format of the data
  15883. * @param forceBindTexture if the texture should be forced to be bound eg. after a graphics context loss (Default: false)
  15884. */
  15885. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format, forceBindTexture) {
  15886. if (premulAlpha === void 0) { premulAlpha = false; }
  15887. if (forceBindTexture === void 0) { forceBindTexture = false; }
  15888. if (!texture) {
  15889. return;
  15890. }
  15891. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true, forceBindTexture);
  15892. this._unpackFlipY(invertY);
  15893. if (premulAlpha) {
  15894. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15895. }
  15896. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15897. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15898. if (texture.generateMipMaps) {
  15899. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15900. }
  15901. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15902. if (premulAlpha) {
  15903. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15904. }
  15905. texture.isReady = true;
  15906. };
  15907. /**
  15908. * Update a video texture
  15909. * @param texture defines the texture to update
  15910. * @param video defines the video element to use
  15911. * @param invertY defines if data must be stored with Y axis inverted
  15912. */
  15913. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15914. if (!texture || texture._isDisabled) {
  15915. return;
  15916. }
  15917. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15918. this._unpackFlipY(!invertY); // Video are upside down by default
  15919. try {
  15920. // Testing video texture support
  15921. if (this._videoTextureSupported === undefined) {
  15922. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15923. if (this._gl.getError() !== 0) {
  15924. this._videoTextureSupported = false;
  15925. }
  15926. else {
  15927. this._videoTextureSupported = true;
  15928. }
  15929. }
  15930. // Copy video through the current working canvas if video texture is not supported
  15931. if (!this._videoTextureSupported) {
  15932. if (!texture._workingCanvas) {
  15933. texture._workingCanvas = document.createElement("canvas");
  15934. var context = texture._workingCanvas.getContext("2d");
  15935. if (!context) {
  15936. throw new Error("Unable to get 2d context");
  15937. }
  15938. texture._workingContext = context;
  15939. texture._workingCanvas.width = texture.width;
  15940. texture._workingCanvas.height = texture.height;
  15941. }
  15942. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15943. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15944. }
  15945. else {
  15946. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15947. }
  15948. if (texture.generateMipMaps) {
  15949. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15950. }
  15951. if (!wasPreviouslyBound) {
  15952. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15953. }
  15954. // this.resetTextureCache();
  15955. texture.isReady = true;
  15956. }
  15957. catch (ex) {
  15958. // Something unexpected
  15959. // Let's disable the texture
  15960. texture._isDisabled = true;
  15961. }
  15962. };
  15963. /**
  15964. * Updates a depth texture Comparison Mode and Function.
  15965. * If the comparison Function is equal to 0, the mode will be set to none.
  15966. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15967. * @param texture The texture to set the comparison function for
  15968. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15969. */
  15970. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15971. if (this.webGLVersion === 1) {
  15972. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15973. return;
  15974. }
  15975. var gl = this._gl;
  15976. if (texture.isCube) {
  15977. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15978. if (comparisonFunction === 0) {
  15979. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15980. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15981. }
  15982. else {
  15983. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15984. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15985. }
  15986. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15987. }
  15988. else {
  15989. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15990. if (comparisonFunction === 0) {
  15991. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15992. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15993. }
  15994. else {
  15995. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15996. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15997. }
  15998. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15999. }
  16000. texture._comparisonFunction = comparisonFunction;
  16001. };
  16002. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  16003. var width = size.width || size;
  16004. var height = size.height || size;
  16005. internalTexture.baseWidth = width;
  16006. internalTexture.baseHeight = height;
  16007. internalTexture.width = width;
  16008. internalTexture.height = height;
  16009. internalTexture.isReady = true;
  16010. internalTexture.samples = 1;
  16011. internalTexture.generateMipMaps = false;
  16012. internalTexture._generateDepthBuffer = true;
  16013. internalTexture._generateStencilBuffer = generateStencil;
  16014. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16015. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16016. internalTexture._comparisonFunction = comparisonFunction;
  16017. var gl = this._gl;
  16018. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16019. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  16020. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  16021. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  16022. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16023. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16024. if (comparisonFunction === 0) {
  16025. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  16026. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  16027. }
  16028. else {
  16029. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  16030. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  16031. }
  16032. };
  16033. /**
  16034. * Creates a depth stencil texture.
  16035. * This is only available in WebGL 2 or with the depth texture extension available.
  16036. * @param size The size of face edge in the texture.
  16037. * @param options The options defining the texture.
  16038. * @returns The texture
  16039. */
  16040. Engine.prototype.createDepthStencilTexture = function (size, options) {
  16041. if (options.isCube) {
  16042. var width = size.width || size;
  16043. return this._createDepthStencilCubeTexture(width, options);
  16044. }
  16045. else {
  16046. return this._createDepthStencilTexture(size, options);
  16047. }
  16048. };
  16049. /**
  16050. * Creates a depth stencil texture.
  16051. * This is only available in WebGL 2 or with the depth texture extension available.
  16052. * @param size The size of face edge in the texture.
  16053. * @param options The options defining the texture.
  16054. * @returns The texture
  16055. */
  16056. Engine.prototype._createDepthStencilTexture = function (size, options) {
  16057. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  16058. if (!this._caps.depthTextureExtension) {
  16059. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  16060. return internalTexture;
  16061. }
  16062. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  16063. var gl = this._gl;
  16064. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  16065. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  16066. if (this.webGLVersion > 1) {
  16067. if (internalOptions.generateStencil) {
  16068. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  16069. }
  16070. else {
  16071. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  16072. }
  16073. }
  16074. else {
  16075. if (internalOptions.generateStencil) {
  16076. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  16077. }
  16078. else {
  16079. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  16080. }
  16081. }
  16082. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16083. return internalTexture;
  16084. };
  16085. /**
  16086. * Creates a depth stencil cube texture.
  16087. * This is only available in WebGL 2.
  16088. * @param size The size of face edge in the cube texture.
  16089. * @param options The options defining the cube texture.
  16090. * @returns The cube texture
  16091. */
  16092. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  16093. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  16094. internalTexture.isCube = true;
  16095. if (this.webGLVersion === 1) {
  16096. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  16097. return internalTexture;
  16098. }
  16099. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  16100. var gl = this._gl;
  16101. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  16102. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  16103. // Create the depth/stencil buffer
  16104. for (var face = 0; face < 6; face++) {
  16105. if (internalOptions.generateStencil) {
  16106. 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);
  16107. }
  16108. else {
  16109. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  16110. }
  16111. }
  16112. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16113. return internalTexture;
  16114. };
  16115. /**
  16116. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  16117. * @param renderTarget The render target to set the frame buffer for
  16118. */
  16119. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  16120. // Create the framebuffer
  16121. var internalTexture = renderTarget.getInternalTexture();
  16122. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  16123. return;
  16124. }
  16125. var gl = this._gl;
  16126. var depthStencilTexture = renderTarget.depthStencilTexture;
  16127. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  16128. if (depthStencilTexture.isCube) {
  16129. if (depthStencilTexture._generateStencilBuffer) {
  16130. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  16131. }
  16132. else {
  16133. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  16134. }
  16135. }
  16136. else {
  16137. if (depthStencilTexture._generateStencilBuffer) {
  16138. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  16139. }
  16140. else {
  16141. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  16142. }
  16143. }
  16144. this.bindUnboundFramebuffer(null);
  16145. };
  16146. /**
  16147. * Creates a new render target texture
  16148. * @param size defines the size of the texture
  16149. * @param options defines the options used to create the texture
  16150. * @returns a new render target texture stored in an InternalTexture
  16151. */
  16152. Engine.prototype.createRenderTargetTexture = function (size, options) {
  16153. var fullOptions = new RenderTargetCreationOptions();
  16154. if (options !== undefined && typeof options === "object") {
  16155. fullOptions.generateMipMaps = options.generateMipMaps;
  16156. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  16157. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  16158. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  16159. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  16160. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  16161. }
  16162. else {
  16163. fullOptions.generateMipMaps = options;
  16164. fullOptions.generateDepthBuffer = true;
  16165. fullOptions.generateStencilBuffer = false;
  16166. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16167. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  16168. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  16169. }
  16170. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16171. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16172. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16173. }
  16174. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16175. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16176. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16177. }
  16178. var gl = this._gl;
  16179. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16180. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16181. var width = size.width || size;
  16182. var height = size.height || size;
  16183. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  16184. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16185. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16186. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  16187. }
  16188. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16189. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16190. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16191. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16192. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  16193. // Create the framebuffer
  16194. var currentFrameBuffer = this._currentFramebuffer;
  16195. var framebuffer = gl.createFramebuffer();
  16196. this.bindUnboundFramebuffer(framebuffer);
  16197. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16198. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  16199. if (fullOptions.generateMipMaps) {
  16200. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16201. }
  16202. // Unbind
  16203. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16204. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16205. this.bindUnboundFramebuffer(currentFrameBuffer);
  16206. texture._framebuffer = framebuffer;
  16207. texture.baseWidth = width;
  16208. texture.baseHeight = height;
  16209. texture.width = width;
  16210. texture.height = height;
  16211. texture.isReady = true;
  16212. texture.samples = 1;
  16213. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  16214. texture.samplingMode = fullOptions.samplingMode;
  16215. texture.type = fullOptions.type;
  16216. texture.format = fullOptions.format;
  16217. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16218. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  16219. // this.resetTextureCache();
  16220. this._internalTexturesCache.push(texture);
  16221. return texture;
  16222. };
  16223. /**
  16224. * Create a multi render target texture
  16225. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  16226. * @param size defines the size of the texture
  16227. * @param options defines the creation options
  16228. * @returns the cube texture as an InternalTexture
  16229. */
  16230. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  16231. var generateMipMaps = false;
  16232. var generateDepthBuffer = true;
  16233. var generateStencilBuffer = false;
  16234. var generateDepthTexture = false;
  16235. var textureCount = 1;
  16236. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  16237. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  16238. var types = new Array();
  16239. var samplingModes = new Array();
  16240. if (options !== undefined) {
  16241. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  16242. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  16243. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  16244. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  16245. textureCount = options.textureCount || 1;
  16246. if (options.types) {
  16247. types = options.types;
  16248. }
  16249. if (options.samplingModes) {
  16250. samplingModes = options.samplingModes;
  16251. }
  16252. }
  16253. var gl = this._gl;
  16254. // Create the framebuffer
  16255. var framebuffer = gl.createFramebuffer();
  16256. this.bindUnboundFramebuffer(framebuffer);
  16257. var width = size.width || size;
  16258. var height = size.height || size;
  16259. var textures = [];
  16260. var attachments = [];
  16261. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  16262. for (var i = 0; i < textureCount; i++) {
  16263. var samplingMode = samplingModes[i] || defaultSamplingMode;
  16264. var type = types[i] || defaultType;
  16265. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16266. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16267. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16268. }
  16269. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16270. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16271. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16272. }
  16273. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16274. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16275. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16276. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  16277. }
  16278. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16279. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16280. textures.push(texture);
  16281. attachments.push(attachment);
  16282. gl.activeTexture(gl["TEXTURE" + i]);
  16283. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  16284. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16285. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16286. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16287. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16288. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16289. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16290. if (generateMipMaps) {
  16291. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16292. }
  16293. // Unbind
  16294. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16295. texture._framebuffer = framebuffer;
  16296. texture._depthStencilBuffer = depthStencilBuffer;
  16297. texture.baseWidth = width;
  16298. texture.baseHeight = height;
  16299. texture.width = width;
  16300. texture.height = height;
  16301. texture.isReady = true;
  16302. texture.samples = 1;
  16303. texture.generateMipMaps = generateMipMaps;
  16304. texture.samplingMode = samplingMode;
  16305. texture.type = type;
  16306. texture._generateDepthBuffer = generateDepthBuffer;
  16307. texture._generateStencilBuffer = generateStencilBuffer;
  16308. texture._attachments = attachments;
  16309. this._internalTexturesCache.push(texture);
  16310. }
  16311. if (generateDepthTexture && this._caps.depthTextureExtension) {
  16312. // Depth texture
  16313. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16314. gl.activeTexture(gl.TEXTURE0);
  16315. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  16316. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16317. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16318. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16319. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16320. 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);
  16321. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  16322. depthTexture._framebuffer = framebuffer;
  16323. depthTexture.baseWidth = width;
  16324. depthTexture.baseHeight = height;
  16325. depthTexture.width = width;
  16326. depthTexture.height = height;
  16327. depthTexture.isReady = true;
  16328. depthTexture.samples = 1;
  16329. depthTexture.generateMipMaps = generateMipMaps;
  16330. depthTexture.samplingMode = gl.NEAREST;
  16331. depthTexture._generateDepthBuffer = generateDepthBuffer;
  16332. depthTexture._generateStencilBuffer = generateStencilBuffer;
  16333. textures.push(depthTexture);
  16334. this._internalTexturesCache.push(depthTexture);
  16335. }
  16336. gl.drawBuffers(attachments);
  16337. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16338. this.bindUnboundFramebuffer(null);
  16339. this.resetTextureCache();
  16340. return textures;
  16341. };
  16342. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  16343. if (samples === void 0) { samples = 1; }
  16344. var depthStencilBuffer = null;
  16345. var gl = this._gl;
  16346. // Create the depth/stencil buffer
  16347. if (generateStencilBuffer) {
  16348. depthStencilBuffer = gl.createRenderbuffer();
  16349. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16350. if (samples > 1) {
  16351. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  16352. }
  16353. else {
  16354. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  16355. }
  16356. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16357. }
  16358. else if (generateDepthBuffer) {
  16359. depthStencilBuffer = gl.createRenderbuffer();
  16360. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16361. if (samples > 1) {
  16362. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  16363. }
  16364. else {
  16365. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  16366. }
  16367. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16368. }
  16369. return depthStencilBuffer;
  16370. };
  16371. /**
  16372. * Updates the sample count of a render target texture
  16373. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16374. * @param texture defines the texture to update
  16375. * @param samples defines the sample count to set
  16376. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16377. */
  16378. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  16379. if (this.webGLVersion < 2 || !texture) {
  16380. return 1;
  16381. }
  16382. if (texture.samples === samples) {
  16383. return samples;
  16384. }
  16385. var gl = this._gl;
  16386. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16387. // Dispose previous render buffers
  16388. if (texture._depthStencilBuffer) {
  16389. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16390. texture._depthStencilBuffer = null;
  16391. }
  16392. if (texture._MSAAFramebuffer) {
  16393. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16394. texture._MSAAFramebuffer = null;
  16395. }
  16396. if (texture._MSAARenderBuffer) {
  16397. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16398. texture._MSAARenderBuffer = null;
  16399. }
  16400. if (samples > 1) {
  16401. var framebuffer = gl.createFramebuffer();
  16402. if (!framebuffer) {
  16403. throw new Error("Unable to create multi sampled framebuffer");
  16404. }
  16405. texture._MSAAFramebuffer = framebuffer;
  16406. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  16407. var colorRenderbuffer = gl.createRenderbuffer();
  16408. if (!colorRenderbuffer) {
  16409. throw new Error("Unable to create multi sampled framebuffer");
  16410. }
  16411. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16412. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16413. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  16414. texture._MSAARenderBuffer = colorRenderbuffer;
  16415. }
  16416. else {
  16417. this.bindUnboundFramebuffer(texture._framebuffer);
  16418. }
  16419. texture.samples = samples;
  16420. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  16421. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16422. this.bindUnboundFramebuffer(null);
  16423. return samples;
  16424. };
  16425. /**
  16426. * Update the sample count for a given multiple render target texture
  16427. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16428. * @param textures defines the textures to update
  16429. * @param samples defines the sample count to set
  16430. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16431. */
  16432. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  16433. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  16434. return 1;
  16435. }
  16436. if (textures[0].samples === samples) {
  16437. return samples;
  16438. }
  16439. var gl = this._gl;
  16440. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16441. // Dispose previous render buffers
  16442. if (textures[0]._depthStencilBuffer) {
  16443. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  16444. textures[0]._depthStencilBuffer = null;
  16445. }
  16446. if (textures[0]._MSAAFramebuffer) {
  16447. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  16448. textures[0]._MSAAFramebuffer = null;
  16449. }
  16450. for (var i = 0; i < textures.length; i++) {
  16451. if (textures[i]._MSAARenderBuffer) {
  16452. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  16453. textures[i]._MSAARenderBuffer = null;
  16454. }
  16455. }
  16456. if (samples > 1) {
  16457. var framebuffer = gl.createFramebuffer();
  16458. if (!framebuffer) {
  16459. throw new Error("Unable to create multi sampled framebuffer");
  16460. }
  16461. this.bindUnboundFramebuffer(framebuffer);
  16462. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  16463. var attachments = [];
  16464. for (var i = 0; i < textures.length; i++) {
  16465. var texture = textures[i];
  16466. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16467. var colorRenderbuffer = gl.createRenderbuffer();
  16468. if (!colorRenderbuffer) {
  16469. throw new Error("Unable to create multi sampled framebuffer");
  16470. }
  16471. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16472. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16473. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  16474. texture._MSAAFramebuffer = framebuffer;
  16475. texture._MSAARenderBuffer = colorRenderbuffer;
  16476. texture.samples = samples;
  16477. texture._depthStencilBuffer = depthStencilBuffer;
  16478. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16479. attachments.push(attachment);
  16480. }
  16481. gl.drawBuffers(attachments);
  16482. }
  16483. else {
  16484. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  16485. }
  16486. this.bindUnboundFramebuffer(null);
  16487. return samples;
  16488. };
  16489. /** @hidden */
  16490. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  16491. if (faceIndex === void 0) { faceIndex = 0; }
  16492. if (lod === void 0) { lod = 0; }
  16493. var gl = this._gl;
  16494. var target = gl.TEXTURE_2D;
  16495. if (texture.isCube) {
  16496. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16497. }
  16498. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  16499. };
  16500. /** @hidden */
  16501. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  16502. if (faceIndex === void 0) { faceIndex = 0; }
  16503. if (lod === void 0) { lod = 0; }
  16504. var gl = this._gl;
  16505. var textureType = this._getWebGLTextureType(texture.type);
  16506. var format = this._getInternalFormat(texture.format);
  16507. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16508. this._unpackFlipY(texture.invertY);
  16509. var target = gl.TEXTURE_2D;
  16510. if (texture.isCube) {
  16511. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16512. }
  16513. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  16514. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  16515. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  16516. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  16517. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  16518. };
  16519. /** @hidden */
  16520. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  16521. if (faceIndex === void 0) { faceIndex = 0; }
  16522. if (lod === void 0) { lod = 0; }
  16523. var gl = this._gl;
  16524. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16525. this._bindTextureDirectly(bindTarget, texture, true);
  16526. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  16527. this._bindTextureDirectly(bindTarget, null, true);
  16528. };
  16529. /** @hidden */
  16530. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  16531. if (faceIndex === void 0) { faceIndex = 0; }
  16532. if (lod === void 0) { lod = 0; }
  16533. var gl = this._gl;
  16534. var textureType = this._getWebGLTextureType(texture.type);
  16535. var format = this._getInternalFormat(texture.format);
  16536. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16537. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16538. this._bindTextureDirectly(bindTarget, texture, true);
  16539. this._unpackFlipY(texture.invertY);
  16540. var target = gl.TEXTURE_2D;
  16541. if (texture.isCube) {
  16542. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16543. }
  16544. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  16545. this._bindTextureDirectly(bindTarget, null, true);
  16546. };
  16547. /**
  16548. * Creates a new render target cube texture
  16549. * @param size defines the size of the texture
  16550. * @param options defines the options used to create the texture
  16551. * @returns a new render target cube texture stored in an InternalTexture
  16552. */
  16553. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  16554. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  16555. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  16556. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16557. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16558. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16559. }
  16560. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16561. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16562. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16563. }
  16564. var gl = this._gl;
  16565. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16566. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16567. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  16568. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16569. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16570. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  16571. }
  16572. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16573. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16574. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16575. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16576. for (var face = 0; face < 6; face++) {
  16577. 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);
  16578. }
  16579. // Create the framebuffer
  16580. var framebuffer = gl.createFramebuffer();
  16581. this.bindUnboundFramebuffer(framebuffer);
  16582. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  16583. // MipMaps
  16584. if (fullOptions.generateMipMaps) {
  16585. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16586. }
  16587. // Unbind
  16588. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16589. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16590. this.bindUnboundFramebuffer(null);
  16591. texture._framebuffer = framebuffer;
  16592. texture.width = size;
  16593. texture.height = size;
  16594. texture.isReady = true;
  16595. texture.isCube = true;
  16596. texture.samples = 1;
  16597. texture.generateMipMaps = fullOptions.generateMipMaps;
  16598. texture.samplingMode = fullOptions.samplingMode;
  16599. texture.type = fullOptions.type;
  16600. texture.format = fullOptions.format;
  16601. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16602. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  16603. this._internalTexturesCache.push(texture);
  16604. return texture;
  16605. };
  16606. /**
  16607. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  16608. * @param rootUrl defines the url where the file to load is located
  16609. * @param scene defines the current scene
  16610. * @param lodScale defines scale to apply to the mip map selection
  16611. * @param lodOffset defines offset to apply to the mip map selection
  16612. * @param onLoad defines an optional callback raised when the texture is loaded
  16613. * @param onError defines an optional callback raised if there is an issue to load the texture
  16614. * @param format defines the format of the data
  16615. * @param forcedExtension defines the extension to use to pick the right loader
  16616. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  16617. * @returns the cube texture as an InternalTexture
  16618. */
  16619. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  16620. var _this = this;
  16621. if (onLoad === void 0) { onLoad = null; }
  16622. if (onError === void 0) { onError = null; }
  16623. if (forcedExtension === void 0) { forcedExtension = null; }
  16624. if (createPolynomials === void 0) { createPolynomials = true; }
  16625. var callback = function (loadData) {
  16626. if (!loadData) {
  16627. if (onLoad) {
  16628. onLoad(null);
  16629. }
  16630. return;
  16631. }
  16632. var texture = loadData.texture;
  16633. if (!createPolynomials) {
  16634. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  16635. }
  16636. else if (loadData.info.sphericalPolynomial) {
  16637. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  16638. }
  16639. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  16640. if (_this._caps.textureLOD) {
  16641. // Do not add extra process if texture lod is supported.
  16642. if (onLoad) {
  16643. onLoad(texture);
  16644. }
  16645. return;
  16646. }
  16647. var mipSlices = 3;
  16648. var gl = _this._gl;
  16649. var width = loadData.width;
  16650. if (!width) {
  16651. return;
  16652. }
  16653. var textures = [];
  16654. for (var i = 0; i < mipSlices; i++) {
  16655. //compute LOD from even spacing in smoothness (matching shader calculation)
  16656. var smoothness = i / (mipSlices - 1);
  16657. var roughness = 1 - smoothness;
  16658. var minLODIndex = lodOffset; // roughness = 0
  16659. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  16660. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  16661. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  16662. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  16663. glTextureFromLod.type = texture.type;
  16664. glTextureFromLod.format = texture.format;
  16665. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  16666. glTextureFromLod.height = glTextureFromLod.width;
  16667. glTextureFromLod.isCube = true;
  16668. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  16669. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16670. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  16671. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16672. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16673. if (loadData.isDDS) {
  16674. var info = loadData.info;
  16675. var data = loadData.data;
  16676. _this._unpackFlipY(info.isCompressed);
  16677. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  16678. }
  16679. else {
  16680. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  16681. }
  16682. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16683. // Wrap in a base texture for easy binding.
  16684. var lodTexture = new BABYLON.BaseTexture(scene);
  16685. lodTexture.isCube = true;
  16686. lodTexture._texture = glTextureFromLod;
  16687. glTextureFromLod.isReady = true;
  16688. textures.push(lodTexture);
  16689. }
  16690. texture._lodTextureHigh = textures[2];
  16691. texture._lodTextureMid = textures[1];
  16692. texture._lodTextureLow = textures[0];
  16693. if (onLoad) {
  16694. onLoad(texture);
  16695. }
  16696. };
  16697. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  16698. };
  16699. /**
  16700. * Creates a cube texture
  16701. * @param rootUrl defines the url where the files to load is located
  16702. * @param scene defines the current scene
  16703. * @param files defines the list of files to load (1 per face)
  16704. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  16705. * @param onLoad defines an optional callback raised when the texture is loaded
  16706. * @param onError defines an optional callback raised if there is an issue to load the texture
  16707. * @param format defines the format of the data
  16708. * @param forcedExtension defines the extension to use to pick the right loader
  16709. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  16710. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  16711. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  16712. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  16713. * @returns the cube texture as an InternalTexture
  16714. */
  16715. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  16716. var _this = this;
  16717. if (onLoad === void 0) { onLoad = null; }
  16718. if (onError === void 0) { onError = null; }
  16719. if (forcedExtension === void 0) { forcedExtension = null; }
  16720. if (createPolynomials === void 0) { createPolynomials = false; }
  16721. if (lodScale === void 0) { lodScale = 0; }
  16722. if (lodOffset === void 0) { lodOffset = 0; }
  16723. if (fallback === void 0) { fallback = null; }
  16724. var gl = this._gl;
  16725. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  16726. texture.isCube = true;
  16727. texture.url = rootUrl;
  16728. texture.generateMipMaps = !noMipmap;
  16729. texture._lodGenerationScale = lodScale;
  16730. texture._lodGenerationOffset = lodOffset;
  16731. if (!this._doNotHandleContextLost) {
  16732. texture._extension = forcedExtension;
  16733. texture._files = files;
  16734. }
  16735. var lastDot = rootUrl.lastIndexOf('.');
  16736. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  16737. var loader = null;
  16738. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  16739. var availableLoader = _a[_i];
  16740. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  16741. loader = availableLoader;
  16742. break;
  16743. }
  16744. }
  16745. var onInternalError = function (request, exception) {
  16746. if (loader) {
  16747. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  16748. if (fallbackUrl) {
  16749. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  16750. }
  16751. }
  16752. if (onError && request) {
  16753. onError(request.status + " " + request.statusText, exception);
  16754. }
  16755. };
  16756. if (loader) {
  16757. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  16758. var onloaddata = function (data) {
  16759. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16760. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  16761. };
  16762. if (files && files.length === 6) {
  16763. if (loader.supportCascades) {
  16764. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  16765. }
  16766. else if (onError) {
  16767. onError("Textures type does not support cascades.");
  16768. }
  16769. }
  16770. else {
  16771. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  16772. }
  16773. }
  16774. else {
  16775. if (!files) {
  16776. throw new Error("Cannot load cubemap because files were not defined");
  16777. }
  16778. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  16779. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  16780. var height = width;
  16781. _this._prepareWorkingCanvas();
  16782. if (!_this._workingCanvas || !_this._workingContext) {
  16783. return;
  16784. }
  16785. _this._workingCanvas.width = width;
  16786. _this._workingCanvas.height = height;
  16787. var faces = [
  16788. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16789. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16790. ];
  16791. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16792. _this._unpackFlipY(false);
  16793. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16794. for (var index = 0; index < faces.length; index++) {
  16795. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16796. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16797. }
  16798. if (!noMipmap) {
  16799. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16800. }
  16801. _this._setCubeMapTextureParams(!noMipmap);
  16802. texture.width = width;
  16803. texture.height = height;
  16804. texture.isReady = true;
  16805. if (format) {
  16806. texture.format = format;
  16807. }
  16808. texture.onLoadedObservable.notifyObservers(texture);
  16809. texture.onLoadedObservable.clear();
  16810. if (onLoad) {
  16811. onLoad();
  16812. }
  16813. }, files, onError);
  16814. }
  16815. this._internalTexturesCache.push(texture);
  16816. return texture;
  16817. };
  16818. /**
  16819. * @hidden
  16820. */
  16821. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  16822. var gl = this._gl;
  16823. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16824. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16825. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16826. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16827. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16828. // this.resetTextureCache();
  16829. };
  16830. /**
  16831. * Update a raw cube texture
  16832. * @param texture defines the texture to udpdate
  16833. * @param data defines the data to store
  16834. * @param format defines the data format
  16835. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16836. * @param invertY defines if data must be stored with Y axis inverted
  16837. * @param compression defines the compression used (null by default)
  16838. * @param level defines which level of the texture to update
  16839. */
  16840. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16841. if (compression === void 0) { compression = null; }
  16842. if (level === void 0) { level = 0; }
  16843. texture._bufferViewArray = data;
  16844. texture.format = format;
  16845. texture.type = type;
  16846. texture.invertY = invertY;
  16847. texture._compression = compression;
  16848. var gl = this._gl;
  16849. var textureType = this._getWebGLTextureType(type);
  16850. var internalFormat = this._getInternalFormat(format);
  16851. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16852. var needConversion = false;
  16853. if (internalFormat === gl.RGB) {
  16854. internalFormat = gl.RGBA;
  16855. needConversion = true;
  16856. }
  16857. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16858. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16859. if (texture.width % 4 !== 0) {
  16860. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16861. }
  16862. // Data are known to be in +X +Y +Z -X -Y -Z
  16863. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16864. var faceData = data[faceIndex];
  16865. if (compression) {
  16866. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16867. }
  16868. else {
  16869. if (needConversion) {
  16870. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16871. }
  16872. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16873. }
  16874. }
  16875. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16876. if (isPot && texture.generateMipMaps && level === 0) {
  16877. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16878. }
  16879. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16880. // this.resetTextureCache();
  16881. texture.isReady = true;
  16882. };
  16883. /**
  16884. * Creates a new raw cube texture
  16885. * @param data defines the array of data to use to create each face
  16886. * @param size defines the size of the textures
  16887. * @param format defines the format of the data
  16888. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16889. * @param generateMipMaps defines if the engine should generate the mip levels
  16890. * @param invertY defines if data must be stored with Y axis inverted
  16891. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16892. * @param compression defines the compression used (null by default)
  16893. * @returns the cube texture as an InternalTexture
  16894. */
  16895. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16896. if (compression === void 0) { compression = null; }
  16897. var gl = this._gl;
  16898. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16899. texture.isCube = true;
  16900. texture.format = format;
  16901. texture.type = type;
  16902. if (!this._doNotHandleContextLost) {
  16903. texture._bufferViewArray = data;
  16904. }
  16905. var textureType = this._getWebGLTextureType(type);
  16906. var internalFormat = this._getInternalFormat(format);
  16907. if (internalFormat === gl.RGB) {
  16908. internalFormat = gl.RGBA;
  16909. }
  16910. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  16911. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16912. generateMipMaps = false;
  16913. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16914. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16915. }
  16916. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16917. generateMipMaps = false;
  16918. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16919. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16920. }
  16921. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  16922. generateMipMaps = false;
  16923. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  16924. }
  16925. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  16926. generateMipMaps = false;
  16927. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  16928. }
  16929. var width = size;
  16930. var height = width;
  16931. texture.width = width;
  16932. texture.height = height;
  16933. // Double check on POT to generate Mips.
  16934. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16935. if (!isPot) {
  16936. generateMipMaps = false;
  16937. }
  16938. // Upload data if needed. The texture won't be ready until then.
  16939. if (data) {
  16940. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16941. }
  16942. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16943. // Filters
  16944. if (data && generateMipMaps) {
  16945. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16946. }
  16947. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16948. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16949. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16950. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16951. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16952. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16953. texture.generateMipMaps = generateMipMaps;
  16954. return texture;
  16955. };
  16956. /**
  16957. * Creates a new raw cube texture from a specified url
  16958. * @param url defines the url where the data is located
  16959. * @param scene defines the current scene
  16960. * @param size defines the size of the textures
  16961. * @param format defines the format of the data
  16962. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16963. * @param noMipmap defines if the engine should avoid generating the mip levels
  16964. * @param callback defines a callback used to extract texture data from loaded data
  16965. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16966. * @param onLoad defines a callback called when texture is loaded
  16967. * @param onError defines a callback called if there is an error
  16968. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16969. * @param invertY defines if data must be stored with Y axis inverted
  16970. * @returns the cube texture as an InternalTexture
  16971. */
  16972. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16973. var _this = this;
  16974. if (onLoad === void 0) { onLoad = null; }
  16975. if (onError === void 0) { onError = null; }
  16976. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16977. if (invertY === void 0) { invertY = false; }
  16978. var gl = this._gl;
  16979. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16980. scene._addPendingData(texture);
  16981. texture.url = url;
  16982. this._internalTexturesCache.push(texture);
  16983. var onerror = function (request, exception) {
  16984. scene._removePendingData(texture);
  16985. if (onError && request) {
  16986. onError(request.status + " " + request.statusText, exception);
  16987. }
  16988. };
  16989. var internalCallback = function (data) {
  16990. var width = texture.width;
  16991. var faceDataArrays = callback(data);
  16992. if (!faceDataArrays) {
  16993. return;
  16994. }
  16995. if (mipmapGenerator) {
  16996. var textureType = _this._getWebGLTextureType(type);
  16997. var internalFormat = _this._getInternalFormat(format);
  16998. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16999. var needConversion = false;
  17000. if (internalFormat === gl.RGB) {
  17001. internalFormat = gl.RGBA;
  17002. needConversion = true;
  17003. }
  17004. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  17005. _this._unpackFlipY(false);
  17006. var mipData = mipmapGenerator(faceDataArrays);
  17007. for (var level = 0; level < mipData.length; level++) {
  17008. var mipSize = width >> level;
  17009. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  17010. var mipFaceData = mipData[level][faceIndex];
  17011. if (needConversion) {
  17012. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  17013. }
  17014. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  17015. }
  17016. }
  17017. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  17018. }
  17019. else {
  17020. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  17021. }
  17022. texture.isReady = true;
  17023. // this.resetTextureCache();
  17024. scene._removePendingData(texture);
  17025. if (onLoad) {
  17026. onLoad();
  17027. }
  17028. };
  17029. this._loadFile(url, function (data) {
  17030. internalCallback(data);
  17031. }, undefined, scene.offlineProvider, true, onerror);
  17032. return texture;
  17033. };
  17034. /**
  17035. * Update a raw 3D texture
  17036. * @param texture defines the texture to update
  17037. * @param data defines the data to store
  17038. * @param format defines the data format
  17039. * @param invertY defines if data must be stored with Y axis inverted
  17040. * @param compression defines the used compression (can be null)
  17041. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  17042. */
  17043. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  17044. if (compression === void 0) { compression = null; }
  17045. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  17046. var internalType = this._getWebGLTextureType(textureType);
  17047. var internalFormat = this._getInternalFormat(format);
  17048. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  17049. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  17050. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  17051. if (!this._doNotHandleContextLost) {
  17052. texture._bufferView = data;
  17053. texture.format = format;
  17054. texture.invertY = invertY;
  17055. texture._compression = compression;
  17056. }
  17057. if (texture.width % 4 !== 0) {
  17058. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  17059. }
  17060. if (compression && data) {
  17061. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  17062. }
  17063. else {
  17064. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  17065. }
  17066. if (texture.generateMipMaps) {
  17067. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  17068. }
  17069. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17070. // this.resetTextureCache();
  17071. texture.isReady = true;
  17072. };
  17073. /**
  17074. * Creates a new raw 3D texture
  17075. * @param data defines the data used to create the texture
  17076. * @param width defines the width of the texture
  17077. * @param height defines the height of the texture
  17078. * @param depth defines the depth of the texture
  17079. * @param format defines the format of the texture
  17080. * @param generateMipMaps defines if the engine must generate mip levels
  17081. * @param invertY defines if data must be stored with Y axis inverted
  17082. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  17083. * @param compression defines the compressed used (can be null)
  17084. * @param textureType defines the compressed used (can be null)
  17085. * @returns a new raw 3D texture (stored in an InternalTexture)
  17086. */
  17087. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  17088. if (compression === void 0) { compression = null; }
  17089. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  17090. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  17091. texture.baseWidth = width;
  17092. texture.baseHeight = height;
  17093. texture.baseDepth = depth;
  17094. texture.width = width;
  17095. texture.height = height;
  17096. texture.depth = depth;
  17097. texture.format = format;
  17098. texture.type = textureType;
  17099. texture.generateMipMaps = generateMipMaps;
  17100. texture.samplingMode = samplingMode;
  17101. texture.is3D = true;
  17102. if (!this._doNotHandleContextLost) {
  17103. texture._bufferView = data;
  17104. }
  17105. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  17106. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  17107. // Filters
  17108. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  17109. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  17110. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  17111. if (generateMipMaps) {
  17112. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  17113. }
  17114. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17115. this._internalTexturesCache.push(texture);
  17116. return texture;
  17117. };
  17118. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  17119. var gl = this._gl;
  17120. if (!gl) {
  17121. return;
  17122. }
  17123. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  17124. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  17125. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  17126. if (!noMipmap && !isCompressed) {
  17127. gl.generateMipmap(gl.TEXTURE_2D);
  17128. }
  17129. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  17130. // this.resetTextureCache();
  17131. if (scene) {
  17132. scene._removePendingData(texture);
  17133. }
  17134. texture.onLoadedObservable.notifyObservers(texture);
  17135. texture.onLoadedObservable.clear();
  17136. };
  17137. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  17138. var _this = this;
  17139. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  17140. var maxTextureSize = this.getCaps().maxTextureSize;
  17141. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  17142. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  17143. var gl = this._gl;
  17144. if (!gl) {
  17145. return;
  17146. }
  17147. if (!texture._webGLTexture) {
  17148. // this.resetTextureCache();
  17149. if (scene) {
  17150. scene._removePendingData(texture);
  17151. }
  17152. return;
  17153. }
  17154. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  17155. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  17156. texture.baseWidth = width;
  17157. texture.baseHeight = height;
  17158. texture.width = potWidth;
  17159. texture.height = potHeight;
  17160. texture.isReady = true;
  17161. if (processFunction(potWidth, potHeight, function () {
  17162. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  17163. })) {
  17164. // Returning as texture needs extra async steps
  17165. return;
  17166. }
  17167. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  17168. };
  17169. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  17170. // Create new RGBA data container.
  17171. var rgbaData;
  17172. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  17173. rgbaData = new Float32Array(width * height * 4);
  17174. }
  17175. else {
  17176. rgbaData = new Uint32Array(width * height * 4);
  17177. }
  17178. // Convert each pixel.
  17179. for (var x = 0; x < width; x++) {
  17180. for (var y = 0; y < height; y++) {
  17181. var index = (y * width + x) * 3;
  17182. var newIndex = (y * width + x) * 4;
  17183. // Map Old Value to new value.
  17184. rgbaData[newIndex + 0] = rgbData[index + 0];
  17185. rgbaData[newIndex + 1] = rgbData[index + 1];
  17186. rgbaData[newIndex + 2] = rgbData[index + 2];
  17187. // Add fully opaque alpha channel.
  17188. rgbaData[newIndex + 3] = 1;
  17189. }
  17190. }
  17191. return rgbaData;
  17192. };
  17193. /** @hidden */
  17194. Engine.prototype._releaseFramebufferObjects = function (texture) {
  17195. var gl = this._gl;
  17196. if (texture._framebuffer) {
  17197. gl.deleteFramebuffer(texture._framebuffer);
  17198. texture._framebuffer = null;
  17199. }
  17200. if (texture._depthStencilBuffer) {
  17201. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  17202. texture._depthStencilBuffer = null;
  17203. }
  17204. if (texture._MSAAFramebuffer) {
  17205. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  17206. texture._MSAAFramebuffer = null;
  17207. }
  17208. if (texture._MSAARenderBuffer) {
  17209. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  17210. texture._MSAARenderBuffer = null;
  17211. }
  17212. };
  17213. /** @hidden */
  17214. Engine.prototype._releaseTexture = function (texture) {
  17215. var gl = this._gl;
  17216. this._releaseFramebufferObjects(texture);
  17217. gl.deleteTexture(texture._webGLTexture);
  17218. // Unbind channels
  17219. this.unbindAllTextures();
  17220. var index = this._internalTexturesCache.indexOf(texture);
  17221. if (index !== -1) {
  17222. this._internalTexturesCache.splice(index, 1);
  17223. }
  17224. // Integrated fixed lod samplers.
  17225. if (texture._lodTextureHigh) {
  17226. texture._lodTextureHigh.dispose();
  17227. }
  17228. if (texture._lodTextureMid) {
  17229. texture._lodTextureMid.dispose();
  17230. }
  17231. if (texture._lodTextureLow) {
  17232. texture._lodTextureLow.dispose();
  17233. }
  17234. // Set output texture of post process to null if the texture has been released/disposed
  17235. this.scenes.forEach(function (scene) {
  17236. scene.postProcesses.forEach(function (postProcess) {
  17237. if (postProcess._outputTexture == texture) {
  17238. postProcess._outputTexture = null;
  17239. }
  17240. });
  17241. scene.cameras.forEach(function (camera) {
  17242. camera._postProcesses.forEach(function (postProcess) {
  17243. if (postProcess) {
  17244. if (postProcess._outputTexture == texture) {
  17245. postProcess._outputTexture = null;
  17246. }
  17247. }
  17248. });
  17249. });
  17250. });
  17251. };
  17252. Engine.prototype.setProgram = function (program) {
  17253. if (this._currentProgram !== program) {
  17254. this._gl.useProgram(program);
  17255. this._currentProgram = program;
  17256. }
  17257. };
  17258. /**
  17259. * Binds an effect to the webGL context
  17260. * @param effect defines the effect to bind
  17261. */
  17262. Engine.prototype.bindSamplers = function (effect) {
  17263. this.setProgram(effect.getProgram());
  17264. var samplers = effect.getSamplers();
  17265. for (var index = 0; index < samplers.length; index++) {
  17266. var uniform = effect.getUniform(samplers[index]);
  17267. if (uniform) {
  17268. this._boundUniforms[index] = uniform;
  17269. }
  17270. }
  17271. this._currentEffect = null;
  17272. };
  17273. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  17274. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  17275. return;
  17276. }
  17277. // Remove
  17278. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17279. // Bind last to it
  17280. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  17281. // Bind to dummy
  17282. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  17283. };
  17284. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  17285. if (!internalTexture) {
  17286. return -1;
  17287. }
  17288. internalTexture._initialSlot = channel;
  17289. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  17290. if (channel !== internalTexture._designatedSlot) {
  17291. this._textureCollisions.addCount(1, false);
  17292. }
  17293. }
  17294. else {
  17295. if (channel !== internalTexture._designatedSlot) {
  17296. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  17297. return internalTexture._designatedSlot;
  17298. }
  17299. else {
  17300. // No slot for this texture, let's pick a new one (if we find a free slot)
  17301. if (this._nextFreeTextureSlots.length) {
  17302. return this._nextFreeTextureSlots[0];
  17303. }
  17304. // We need to recycle the oldest bound texture, sorry.
  17305. this._textureCollisions.addCount(1, false);
  17306. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  17307. }
  17308. }
  17309. }
  17310. return channel;
  17311. };
  17312. Engine.prototype._linkTrackers = function (previous, next) {
  17313. previous.next = next;
  17314. next.previous = previous;
  17315. };
  17316. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  17317. var currentSlot = internalTexture._designatedSlot;
  17318. if (currentSlot === -1) {
  17319. return -1;
  17320. }
  17321. internalTexture._designatedSlot = -1;
  17322. if (this.disableTextureBindingOptimization) {
  17323. return -1;
  17324. }
  17325. // Remove from bound list
  17326. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17327. // Free the slot
  17328. this._boundTexturesCache[currentSlot] = null;
  17329. this._nextFreeTextureSlots.push(currentSlot);
  17330. return currentSlot;
  17331. };
  17332. Engine.prototype._activateCurrentTexture = function () {
  17333. if (this._currentTextureChannel !== this._activeChannel) {
  17334. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  17335. this._currentTextureChannel = this._activeChannel;
  17336. }
  17337. };
  17338. /** @hidden */
  17339. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  17340. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  17341. if (force === void 0) { force = false; }
  17342. var wasPreviouslyBound = false;
  17343. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  17344. this._activeChannel = texture._designatedSlot;
  17345. }
  17346. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  17347. var isTextureForRendering = texture && texture._initialSlot > -1;
  17348. if (currentTextureBound !== texture || force) {
  17349. if (currentTextureBound) {
  17350. this._removeDesignatedSlot(currentTextureBound);
  17351. }
  17352. this._activateCurrentTexture();
  17353. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  17354. this._boundTexturesCache[this._activeChannel] = texture;
  17355. if (texture) {
  17356. if (!this.disableTextureBindingOptimization) {
  17357. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  17358. if (slotIndex > -1) {
  17359. this._nextFreeTextureSlots.splice(slotIndex, 1);
  17360. }
  17361. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  17362. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  17363. }
  17364. texture._designatedSlot = this._activeChannel;
  17365. }
  17366. }
  17367. else if (forTextureDataUpdate) {
  17368. wasPreviouslyBound = true;
  17369. this._activateCurrentTexture();
  17370. }
  17371. if (isTextureForRendering && !forTextureDataUpdate) {
  17372. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  17373. }
  17374. return wasPreviouslyBound;
  17375. };
  17376. /** @hidden */
  17377. Engine.prototype._bindTexture = function (channel, texture) {
  17378. if (channel < 0) {
  17379. return;
  17380. }
  17381. if (texture) {
  17382. channel = this._getCorrectTextureChannel(channel, texture);
  17383. }
  17384. this._activeChannel = channel;
  17385. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  17386. };
  17387. /**
  17388. * Sets a texture to the webGL context from a postprocess
  17389. * @param channel defines the channel to use
  17390. * @param postProcess defines the source postprocess
  17391. */
  17392. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17393. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  17394. };
  17395. /**
  17396. * Binds the output of the passed in post process to the texture channel specified
  17397. * @param channel The channel the texture should be bound to
  17398. * @param postProcess The post process which's output should be bound
  17399. */
  17400. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  17401. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  17402. };
  17403. /**
  17404. * Unbind all textures from the webGL context
  17405. */
  17406. Engine.prototype.unbindAllTextures = function () {
  17407. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  17408. this._activeChannel = channel;
  17409. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17410. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17411. if (this.webGLVersion > 1) {
  17412. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17413. }
  17414. }
  17415. };
  17416. /**
  17417. * Sets a texture to the according uniform.
  17418. * @param channel The texture channel
  17419. * @param uniform The uniform to set
  17420. * @param texture The texture to apply
  17421. */
  17422. Engine.prototype.setTexture = function (channel, uniform, texture) {
  17423. if (channel < 0) {
  17424. return;
  17425. }
  17426. if (uniform) {
  17427. this._boundUniforms[channel] = uniform;
  17428. }
  17429. this._setTexture(channel, texture);
  17430. };
  17431. /**
  17432. * Sets a depth stencil texture from a render target to the according uniform.
  17433. * @param channel The texture channel
  17434. * @param uniform The uniform to set
  17435. * @param texture The render target texture containing the depth stencil texture to apply
  17436. */
  17437. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  17438. if (channel < 0) {
  17439. return;
  17440. }
  17441. if (uniform) {
  17442. this._boundUniforms[channel] = uniform;
  17443. }
  17444. if (!texture || !texture.depthStencilTexture) {
  17445. this._setTexture(channel, null);
  17446. }
  17447. else {
  17448. this._setTexture(channel, texture, false, true);
  17449. }
  17450. };
  17451. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  17452. var uniform = this._boundUniforms[sourceSlot];
  17453. if (uniform._currentState === destination) {
  17454. return;
  17455. }
  17456. this._gl.uniform1i(uniform, destination);
  17457. uniform._currentState = destination;
  17458. };
  17459. Engine.prototype._getTextureWrapMode = function (mode) {
  17460. switch (mode) {
  17461. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  17462. return this._gl.REPEAT;
  17463. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  17464. return this._gl.CLAMP_TO_EDGE;
  17465. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  17466. return this._gl.MIRRORED_REPEAT;
  17467. }
  17468. return this._gl.REPEAT;
  17469. };
  17470. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  17471. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  17472. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  17473. // Not ready?
  17474. if (!texture) {
  17475. if (this._boundTexturesCache[channel] != null) {
  17476. this._activeChannel = channel;
  17477. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17478. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17479. if (this.webGLVersion > 1) {
  17480. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17481. }
  17482. }
  17483. return false;
  17484. }
  17485. // Video
  17486. if (texture.video) {
  17487. this._activeChannel = channel;
  17488. texture.update();
  17489. }
  17490. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  17491. texture.delayLoad();
  17492. return false;
  17493. }
  17494. var internalTexture;
  17495. if (depthStencilTexture) {
  17496. internalTexture = texture.depthStencilTexture;
  17497. }
  17498. else if (texture.isReady()) {
  17499. internalTexture = texture.getInternalTexture();
  17500. }
  17501. else if (texture.isCube) {
  17502. internalTexture = this.emptyCubeTexture;
  17503. }
  17504. else if (texture.is3D) {
  17505. internalTexture = this.emptyTexture3D;
  17506. }
  17507. else {
  17508. internalTexture = this.emptyTexture;
  17509. }
  17510. if (!isPartOfTextureArray) {
  17511. channel = this._getCorrectTextureChannel(channel, internalTexture);
  17512. }
  17513. var needToBind = true;
  17514. if (this._boundTexturesCache[channel] === internalTexture) {
  17515. this._moveBoundTextureOnTop(internalTexture);
  17516. if (!isPartOfTextureArray) {
  17517. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  17518. }
  17519. needToBind = false;
  17520. }
  17521. this._activeChannel = channel;
  17522. if (internalTexture && internalTexture.is3D) {
  17523. if (needToBind) {
  17524. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  17525. }
  17526. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17527. internalTexture._cachedWrapU = texture.wrapU;
  17528. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17529. }
  17530. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17531. internalTexture._cachedWrapV = texture.wrapV;
  17532. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17533. }
  17534. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  17535. internalTexture._cachedWrapR = texture.wrapR;
  17536. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  17537. }
  17538. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  17539. }
  17540. else if (internalTexture && internalTexture.isCube) {
  17541. if (needToBind) {
  17542. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  17543. }
  17544. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  17545. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  17546. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  17547. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  17548. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  17549. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  17550. }
  17551. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  17552. }
  17553. else {
  17554. if (needToBind) {
  17555. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  17556. }
  17557. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17558. internalTexture._cachedWrapU = texture.wrapU;
  17559. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17560. }
  17561. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17562. internalTexture._cachedWrapV = texture.wrapV;
  17563. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17564. }
  17565. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  17566. }
  17567. return true;
  17568. };
  17569. /**
  17570. * Sets an array of texture to the webGL context
  17571. * @param channel defines the channel where the texture array must be set
  17572. * @param uniform defines the associated uniform location
  17573. * @param textures defines the array of textures to bind
  17574. */
  17575. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  17576. if (channel < 0 || !uniform) {
  17577. return;
  17578. }
  17579. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  17580. this._textureUnits = new Int32Array(textures.length);
  17581. }
  17582. for (var i = 0; i < textures.length; i++) {
  17583. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  17584. }
  17585. this._gl.uniform1iv(uniform, this._textureUnits);
  17586. for (var index = 0; index < textures.length; index++) {
  17587. this._setTexture(this._textureUnits[index], textures[index], true);
  17588. }
  17589. };
  17590. /** @hidden */
  17591. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  17592. var internalTexture = texture.getInternalTexture();
  17593. if (!internalTexture) {
  17594. return;
  17595. }
  17596. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  17597. var value = texture.anisotropicFilteringLevel;
  17598. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  17599. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  17600. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  17601. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  17602. }
  17603. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  17604. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  17605. internalTexture._cachedAnisotropicFilteringLevel = value;
  17606. }
  17607. };
  17608. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  17609. this._bindTextureDirectly(target, texture, true, true);
  17610. this._gl.texParameterf(target, parameter, value);
  17611. };
  17612. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  17613. if (texture) {
  17614. this._bindTextureDirectly(target, texture, true, true);
  17615. }
  17616. this._gl.texParameteri(target, parameter, value);
  17617. };
  17618. /**
  17619. * Reads pixels from the current frame buffer. Please note that this function can be slow
  17620. * @param x defines the x coordinate of the rectangle where pixels must be read
  17621. * @param y defines the y coordinate of the rectangle where pixels must be read
  17622. * @param width defines the width of the rectangle where pixels must be read
  17623. * @param height defines the height of the rectangle where pixels must be read
  17624. * @returns a Uint8Array containing RGBA colors
  17625. */
  17626. Engine.prototype.readPixels = function (x, y, width, height) {
  17627. var data = new Uint8Array(height * width * 4);
  17628. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  17629. return data;
  17630. };
  17631. /**
  17632. * Add an externaly attached data from its key.
  17633. * This method call will fail and return false, if such key already exists.
  17634. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17635. * @param key the unique key that identifies the data
  17636. * @param data the data object to associate to the key for this Engine instance
  17637. * @return true if no such key were already present and the data was added successfully, false otherwise
  17638. */
  17639. Engine.prototype.addExternalData = function (key, data) {
  17640. if (!this._externalData) {
  17641. this._externalData = new BABYLON.StringDictionary();
  17642. }
  17643. return this._externalData.add(key, data);
  17644. };
  17645. /**
  17646. * Get an externaly attached data from its key
  17647. * @param key the unique key that identifies the data
  17648. * @return the associated data, if present (can be null), or undefined if not present
  17649. */
  17650. Engine.prototype.getExternalData = function (key) {
  17651. if (!this._externalData) {
  17652. this._externalData = new BABYLON.StringDictionary();
  17653. }
  17654. return this._externalData.get(key);
  17655. };
  17656. /**
  17657. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17658. * @param key the unique key that identifies the data
  17659. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17660. * @return the associated data, can be null if the factory returned null.
  17661. */
  17662. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17663. if (!this._externalData) {
  17664. this._externalData = new BABYLON.StringDictionary();
  17665. }
  17666. return this._externalData.getOrAddWithFactory(key, factory);
  17667. };
  17668. /**
  17669. * Remove an externaly attached data from the Engine instance
  17670. * @param key the unique key that identifies the data
  17671. * @return true if the data was successfully removed, false if it doesn't exist
  17672. */
  17673. Engine.prototype.removeExternalData = function (key) {
  17674. if (!this._externalData) {
  17675. this._externalData = new BABYLON.StringDictionary();
  17676. }
  17677. return this._externalData.remove(key);
  17678. };
  17679. /**
  17680. * Unbind all vertex attributes from the webGL context
  17681. */
  17682. Engine.prototype.unbindAllAttributes = function () {
  17683. if (this._mustWipeVertexAttributes) {
  17684. this._mustWipeVertexAttributes = false;
  17685. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  17686. this._gl.disableVertexAttribArray(i);
  17687. this._vertexAttribArraysEnabled[i] = false;
  17688. this._currentBufferPointers[i].active = false;
  17689. }
  17690. return;
  17691. }
  17692. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  17693. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  17694. continue;
  17695. }
  17696. this._gl.disableVertexAttribArray(i);
  17697. this._vertexAttribArraysEnabled[i] = false;
  17698. this._currentBufferPointers[i].active = false;
  17699. }
  17700. };
  17701. /**
  17702. * 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
  17703. */
  17704. Engine.prototype.releaseEffects = function () {
  17705. for (var name in this._compiledEffects) {
  17706. this._deleteProgram(this._compiledEffects[name]._program);
  17707. }
  17708. this._compiledEffects = {};
  17709. };
  17710. /**
  17711. * Dispose and release all associated resources
  17712. */
  17713. Engine.prototype.dispose = function () {
  17714. this.hideLoadingUI();
  17715. this.stopRenderLoop();
  17716. // Release postProcesses
  17717. while (this.postProcesses.length) {
  17718. this.postProcesses[0].dispose();
  17719. }
  17720. // Empty texture
  17721. if (this._emptyTexture) {
  17722. this._releaseTexture(this._emptyTexture);
  17723. this._emptyTexture = null;
  17724. }
  17725. if (this._emptyCubeTexture) {
  17726. this._releaseTexture(this._emptyCubeTexture);
  17727. this._emptyCubeTexture = null;
  17728. }
  17729. // Rescale PP
  17730. if (this._rescalePostProcess) {
  17731. this._rescalePostProcess.dispose();
  17732. }
  17733. // Release scenes
  17734. while (this.scenes.length) {
  17735. this.scenes[0].dispose();
  17736. }
  17737. // Release audio engine
  17738. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  17739. Engine.audioEngine.dispose();
  17740. }
  17741. // Release effects
  17742. this.releaseEffects();
  17743. // Unbind
  17744. this.unbindAllAttributes();
  17745. this._boundUniforms = [];
  17746. if (this._dummyFramebuffer) {
  17747. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  17748. }
  17749. //WebVR
  17750. this.disableVR();
  17751. // Events
  17752. if (BABYLON.Tools.IsWindowObjectExist()) {
  17753. window.removeEventListener("blur", this._onBlur);
  17754. window.removeEventListener("focus", this._onFocus);
  17755. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  17756. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  17757. if (this._renderingCanvas) {
  17758. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  17759. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  17760. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  17761. if (!this._doNotHandleContextLost) {
  17762. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  17763. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  17764. }
  17765. }
  17766. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  17767. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  17768. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  17769. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  17770. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  17771. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  17772. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  17773. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  17774. if (this._onVrDisplayConnect) {
  17775. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  17776. if (this._onVrDisplayDisconnect) {
  17777. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  17778. }
  17779. if (this._onVrDisplayPresentChange) {
  17780. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  17781. }
  17782. this._onVrDisplayConnect = null;
  17783. this._onVrDisplayDisconnect = null;
  17784. }
  17785. }
  17786. // Remove from Instances
  17787. var index = Engine.Instances.indexOf(this);
  17788. if (index >= 0) {
  17789. Engine.Instances.splice(index, 1);
  17790. }
  17791. this._workingCanvas = null;
  17792. this._workingContext = null;
  17793. this._currentBufferPointers = [];
  17794. this._renderingCanvas = null;
  17795. this._currentProgram = null;
  17796. this._bindedRenderFunction = null;
  17797. this.onResizeObservable.clear();
  17798. this.onCanvasBlurObservable.clear();
  17799. this.onCanvasFocusObservable.clear();
  17800. this.onCanvasPointerOutObservable.clear();
  17801. this.onBeginFrameObservable.clear();
  17802. this.onEndFrameObservable.clear();
  17803. BABYLON.Effect.ResetCache();
  17804. // Abort active requests
  17805. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17806. var request = _a[_i];
  17807. request.abort();
  17808. }
  17809. };
  17810. // Loading screen
  17811. /**
  17812. * Display the loading screen
  17813. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17814. */
  17815. Engine.prototype.displayLoadingUI = function () {
  17816. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17817. return;
  17818. }
  17819. var loadingScreen = this.loadingScreen;
  17820. if (loadingScreen) {
  17821. loadingScreen.displayLoadingUI();
  17822. }
  17823. };
  17824. /**
  17825. * Hide the loading screen
  17826. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17827. */
  17828. Engine.prototype.hideLoadingUI = function () {
  17829. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17830. return;
  17831. }
  17832. var loadingScreen = this.loadingScreen;
  17833. if (loadingScreen) {
  17834. loadingScreen.hideLoadingUI();
  17835. }
  17836. };
  17837. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17838. /**
  17839. * Gets the current loading screen object
  17840. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17841. */
  17842. get: function () {
  17843. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas) {
  17844. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17845. }
  17846. return this._loadingScreen;
  17847. },
  17848. /**
  17849. * Sets the current loading screen object
  17850. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17851. */
  17852. set: function (loadingScreen) {
  17853. this._loadingScreen = loadingScreen;
  17854. },
  17855. enumerable: true,
  17856. configurable: true
  17857. });
  17858. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17859. /**
  17860. * Sets the current loading screen text
  17861. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17862. */
  17863. set: function (text) {
  17864. this.loadingScreen.loadingUIText = text;
  17865. },
  17866. enumerable: true,
  17867. configurable: true
  17868. });
  17869. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17870. /**
  17871. * Sets the current loading screen background color
  17872. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17873. */
  17874. set: function (color) {
  17875. this.loadingScreen.loadingUIBackgroundColor = color;
  17876. },
  17877. enumerable: true,
  17878. configurable: true
  17879. });
  17880. /**
  17881. * Attach a new callback raised when context lost event is fired
  17882. * @param callback defines the callback to call
  17883. */
  17884. Engine.prototype.attachContextLostEvent = function (callback) {
  17885. if (this._renderingCanvas) {
  17886. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17887. }
  17888. };
  17889. /**
  17890. * Attach a new callback raised when context restored event is fired
  17891. * @param callback defines the callback to call
  17892. */
  17893. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17894. if (this._renderingCanvas) {
  17895. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17896. }
  17897. };
  17898. /**
  17899. * Gets the source code of the vertex shader associated with a specific webGL program
  17900. * @param program defines the program to use
  17901. * @returns a string containing the source code of the vertex shader associated with the program
  17902. */
  17903. Engine.prototype.getVertexShaderSource = function (program) {
  17904. var shaders = this._gl.getAttachedShaders(program);
  17905. if (!shaders) {
  17906. return null;
  17907. }
  17908. return this._gl.getShaderSource(shaders[0]);
  17909. };
  17910. /**
  17911. * Gets the source code of the fragment shader associated with a specific webGL program
  17912. * @param program defines the program to use
  17913. * @returns a string containing the source code of the fragment shader associated with the program
  17914. */
  17915. Engine.prototype.getFragmentShaderSource = function (program) {
  17916. var shaders = this._gl.getAttachedShaders(program);
  17917. if (!shaders) {
  17918. return null;
  17919. }
  17920. return this._gl.getShaderSource(shaders[1]);
  17921. };
  17922. /**
  17923. * Get the current error code of the webGL context
  17924. * @returns the error code
  17925. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17926. */
  17927. Engine.prototype.getError = function () {
  17928. return this._gl.getError();
  17929. };
  17930. // FPS
  17931. /**
  17932. * Gets the current framerate
  17933. * @returns a number representing the framerate
  17934. */
  17935. Engine.prototype.getFps = function () {
  17936. return this._fps;
  17937. };
  17938. /**
  17939. * Gets the time spent between current and previous frame
  17940. * @returns a number representing the delta time in ms
  17941. */
  17942. Engine.prototype.getDeltaTime = function () {
  17943. return this._deltaTime;
  17944. };
  17945. Engine.prototype._measureFps = function () {
  17946. this._performanceMonitor.sampleFrame();
  17947. this._fps = this._performanceMonitor.averageFPS;
  17948. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17949. };
  17950. /** @hidden */
  17951. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17952. if (faceIndex === void 0) { faceIndex = -1; }
  17953. if (level === void 0) { level = 0; }
  17954. if (buffer === void 0) { buffer = null; }
  17955. var gl = this._gl;
  17956. if (!this._dummyFramebuffer) {
  17957. var dummy = gl.createFramebuffer();
  17958. if (!dummy) {
  17959. throw new Error("Unable to create dummy framebuffer");
  17960. }
  17961. this._dummyFramebuffer = dummy;
  17962. }
  17963. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17964. if (faceIndex > -1) {
  17965. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17966. }
  17967. else {
  17968. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17969. }
  17970. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17971. switch (readType) {
  17972. case gl.UNSIGNED_BYTE:
  17973. if (!buffer) {
  17974. buffer = new Uint8Array(4 * width * height);
  17975. }
  17976. readType = gl.UNSIGNED_BYTE;
  17977. break;
  17978. default:
  17979. if (!buffer) {
  17980. buffer = new Float32Array(4 * width * height);
  17981. }
  17982. readType = gl.FLOAT;
  17983. break;
  17984. }
  17985. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17986. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17987. return buffer;
  17988. };
  17989. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17990. if (this._webGLVersion > 1) {
  17991. return this._caps.colorBufferFloat;
  17992. }
  17993. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17994. };
  17995. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17996. if (this._webGLVersion > 1) {
  17997. return this._caps.colorBufferFloat;
  17998. }
  17999. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  18000. };
  18001. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  18002. Engine.prototype._canRenderToFramebuffer = function (type) {
  18003. var gl = this._gl;
  18004. //clear existing errors
  18005. while (gl.getError() !== gl.NO_ERROR) { }
  18006. var successful = true;
  18007. var texture = gl.createTexture();
  18008. gl.bindTexture(gl.TEXTURE_2D, texture);
  18009. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  18010. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  18011. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  18012. var fb = gl.createFramebuffer();
  18013. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  18014. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  18015. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  18016. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  18017. successful = successful && (gl.getError() === gl.NO_ERROR);
  18018. //try render by clearing frame buffer's color buffer
  18019. if (successful) {
  18020. gl.clear(gl.COLOR_BUFFER_BIT);
  18021. successful = successful && (gl.getError() === gl.NO_ERROR);
  18022. }
  18023. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  18024. if (successful) {
  18025. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  18026. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  18027. var readFormat = gl.RGBA;
  18028. var readType = gl.UNSIGNED_BYTE;
  18029. var buffer = new Uint8Array(4);
  18030. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  18031. successful = successful && (gl.getError() === gl.NO_ERROR);
  18032. }
  18033. //clean up
  18034. gl.deleteTexture(texture);
  18035. gl.deleteFramebuffer(fb);
  18036. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  18037. //clear accumulated errors
  18038. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  18039. return successful;
  18040. };
  18041. /** @hidden */
  18042. Engine.prototype._getWebGLTextureType = function (type) {
  18043. if (this._webGLVersion === 1) {
  18044. switch (type) {
  18045. case Engine.TEXTURETYPE_FLOAT:
  18046. return this._gl.FLOAT;
  18047. case Engine.TEXTURETYPE_HALF_FLOAT:
  18048. return this._gl.HALF_FLOAT_OES;
  18049. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  18050. return this._gl.UNSIGNED_BYTE;
  18051. }
  18052. return this._gl.UNSIGNED_BYTE;
  18053. }
  18054. switch (type) {
  18055. case Engine.TEXTURETYPE_BYTE:
  18056. return this._gl.BYTE;
  18057. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  18058. return this._gl.UNSIGNED_BYTE;
  18059. case Engine.TEXTURETYPE_SHORT:
  18060. return this._gl.SHORT;
  18061. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  18062. return this._gl.UNSIGNED_SHORT;
  18063. case Engine.TEXTURETYPE_INT:
  18064. return this._gl.INT;
  18065. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  18066. return this._gl.UNSIGNED_INT;
  18067. case Engine.TEXTURETYPE_FLOAT:
  18068. return this._gl.FLOAT;
  18069. case Engine.TEXTURETYPE_HALF_FLOAT:
  18070. return this._gl.HALF_FLOAT;
  18071. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  18072. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  18073. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  18074. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  18075. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  18076. return this._gl.UNSIGNED_SHORT_5_6_5;
  18077. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  18078. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  18079. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  18080. return this._gl.UNSIGNED_INT_24_8;
  18081. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  18082. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  18083. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  18084. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  18085. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  18086. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  18087. }
  18088. return this._gl.UNSIGNED_BYTE;
  18089. };
  18090. Engine.prototype._getInternalFormat = function (format) {
  18091. var internalFormat = this._gl.RGBA;
  18092. switch (format) {
  18093. case Engine.TEXTUREFORMAT_ALPHA:
  18094. internalFormat = this._gl.ALPHA;
  18095. break;
  18096. case Engine.TEXTUREFORMAT_LUMINANCE:
  18097. internalFormat = this._gl.LUMINANCE;
  18098. break;
  18099. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  18100. internalFormat = this._gl.LUMINANCE_ALPHA;
  18101. break;
  18102. case Engine.TEXTUREFORMAT_RED:
  18103. internalFormat = this._gl.RED;
  18104. break;
  18105. case Engine.TEXTUREFORMAT_RG:
  18106. internalFormat = this._gl.RG;
  18107. break;
  18108. case Engine.TEXTUREFORMAT_RGB:
  18109. internalFormat = this._gl.RGB;
  18110. break;
  18111. case Engine.TEXTUREFORMAT_RGBA:
  18112. internalFormat = this._gl.RGBA;
  18113. break;
  18114. }
  18115. if (this._webGLVersion > 1) {
  18116. switch (format) {
  18117. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18118. internalFormat = this._gl.RED_INTEGER;
  18119. break;
  18120. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18121. internalFormat = this._gl.RG_INTEGER;
  18122. break;
  18123. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18124. internalFormat = this._gl.RGB_INTEGER;
  18125. break;
  18126. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18127. internalFormat = this._gl.RGBA_INTEGER;
  18128. break;
  18129. }
  18130. }
  18131. return internalFormat;
  18132. };
  18133. /** @hidden */
  18134. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  18135. if (this._webGLVersion === 1) {
  18136. if (format !== undefined) {
  18137. switch (format) {
  18138. case Engine.TEXTUREFORMAT_ALPHA:
  18139. return this._gl.ALPHA;
  18140. case Engine.TEXTUREFORMAT_LUMINANCE:
  18141. return this._gl.LUMINANCE;
  18142. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  18143. return this._gl.LUMINANCE_ALPHA;
  18144. }
  18145. }
  18146. return this._gl.RGBA;
  18147. }
  18148. switch (type) {
  18149. case Engine.TEXTURETYPE_BYTE:
  18150. switch (format) {
  18151. case Engine.TEXTUREFORMAT_RED:
  18152. return this._gl.R8_SNORM;
  18153. case Engine.TEXTUREFORMAT_RG:
  18154. return this._gl.RG8_SNORM;
  18155. case Engine.TEXTUREFORMAT_RGB:
  18156. return this._gl.RGB8_SNORM;
  18157. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18158. return this._gl.R8I;
  18159. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18160. return this._gl.RG8I;
  18161. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18162. return this._gl.RGB8I;
  18163. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18164. return this._gl.RGBA8I;
  18165. default:
  18166. return this._gl.RGBA8_SNORM;
  18167. }
  18168. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  18169. switch (format) {
  18170. case Engine.TEXTUREFORMAT_RED:
  18171. return this._gl.R8;
  18172. case Engine.TEXTUREFORMAT_RG:
  18173. return this._gl.RG8;
  18174. case Engine.TEXTUREFORMAT_RGB:
  18175. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  18176. case Engine.TEXTUREFORMAT_RGBA:
  18177. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  18178. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18179. return this._gl.R8UI;
  18180. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18181. return this._gl.RG8UI;
  18182. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18183. return this._gl.RGB8UI;
  18184. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18185. return this._gl.RGBA8UI;
  18186. default:
  18187. return this._gl.RGBA8;
  18188. }
  18189. case Engine.TEXTURETYPE_SHORT:
  18190. switch (format) {
  18191. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18192. return this._gl.R16I;
  18193. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18194. return this._gl.RG16I;
  18195. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18196. return this._gl.RGB16I;
  18197. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18198. return this._gl.RGBA16I;
  18199. default:
  18200. return this._gl.RGBA16I;
  18201. }
  18202. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  18203. switch (format) {
  18204. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18205. return this._gl.R16UI;
  18206. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18207. return this._gl.RG16UI;
  18208. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18209. return this._gl.RGB16UI;
  18210. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18211. return this._gl.RGBA16UI;
  18212. default:
  18213. return this._gl.RGBA16UI;
  18214. }
  18215. case Engine.TEXTURETYPE_INT:
  18216. switch (format) {
  18217. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18218. return this._gl.R32I;
  18219. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18220. return this._gl.RG32I;
  18221. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18222. return this._gl.RGB32I;
  18223. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18224. return this._gl.RGBA32I;
  18225. default:
  18226. return this._gl.RGBA32I;
  18227. }
  18228. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  18229. switch (format) {
  18230. case Engine.TEXTUREFORMAT_RED_INTEGER:
  18231. return this._gl.R32UI;
  18232. case Engine.TEXTUREFORMAT_RG_INTEGER:
  18233. return this._gl.RG32UI;
  18234. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  18235. return this._gl.RGB32UI;
  18236. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18237. return this._gl.RGBA32UI;
  18238. default:
  18239. return this._gl.RGBA32UI;
  18240. }
  18241. case Engine.TEXTURETYPE_FLOAT:
  18242. switch (format) {
  18243. case Engine.TEXTUREFORMAT_RED:
  18244. return this._gl.R32F; // By default. Other possibility is R16F.
  18245. case Engine.TEXTUREFORMAT_RG:
  18246. return this._gl.RG32F; // By default. Other possibility is RG16F.
  18247. case Engine.TEXTUREFORMAT_RGB:
  18248. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  18249. case Engine.TEXTUREFORMAT_RGBA:
  18250. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  18251. default:
  18252. return this._gl.RGBA32F;
  18253. }
  18254. case Engine.TEXTURETYPE_HALF_FLOAT:
  18255. switch (format) {
  18256. case Engine.TEXTUREFORMAT_RED:
  18257. return this._gl.R16F;
  18258. case Engine.TEXTUREFORMAT_RG:
  18259. return this._gl.RG16F;
  18260. case Engine.TEXTUREFORMAT_RGB:
  18261. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  18262. case Engine.TEXTUREFORMAT_RGBA:
  18263. return this._gl.RGBA16F;
  18264. default:
  18265. return this._gl.RGBA16F;
  18266. }
  18267. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  18268. return this._gl.RGB565;
  18269. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  18270. return this._gl.R11F_G11F_B10F;
  18271. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  18272. return this._gl.RGB9_E5;
  18273. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  18274. return this._gl.RGBA4;
  18275. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  18276. return this._gl.RGB5_A1;
  18277. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  18278. switch (format) {
  18279. case Engine.TEXTUREFORMAT_RGBA:
  18280. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  18281. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18282. return this._gl.RGB10_A2UI;
  18283. default:
  18284. return this._gl.RGB10_A2;
  18285. }
  18286. }
  18287. return this._gl.RGBA8;
  18288. };
  18289. /** @hidden */
  18290. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  18291. if (type === Engine.TEXTURETYPE_FLOAT) {
  18292. return this._gl.RGBA32F;
  18293. }
  18294. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  18295. return this._gl.RGBA16F;
  18296. }
  18297. return this._gl.RGBA8;
  18298. };
  18299. /** @hidden */
  18300. Engine.prototype._loadFile = function (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) {
  18301. var _this = this;
  18302. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError);
  18303. this._activeRequests.push(request);
  18304. request.onCompleteObservable.add(function (request) {
  18305. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  18306. });
  18307. return request;
  18308. };
  18309. /** @hidden */
  18310. Engine.prototype._loadFileAsync = function (url, offlineProvider, useArrayBuffer) {
  18311. var _this = this;
  18312. return new Promise(function (resolve, reject) {
  18313. _this._loadFile(url, function (data) {
  18314. resolve(data);
  18315. }, undefined, offlineProvider, useArrayBuffer, function (request, exception) {
  18316. reject(exception);
  18317. });
  18318. });
  18319. };
  18320. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  18321. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  18322. var onload = function (data) {
  18323. loadedFiles[index] = data;
  18324. loadedFiles._internalCount++;
  18325. if (loadedFiles._internalCount === 6) {
  18326. onfinish(loadedFiles);
  18327. }
  18328. };
  18329. var onerror = function (request, exception) {
  18330. if (onErrorCallBack && request) {
  18331. onErrorCallBack(request.status + " " + request.statusText, exception);
  18332. }
  18333. };
  18334. this._loadFile(url, onload, undefined, undefined, true, onerror);
  18335. };
  18336. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  18337. if (onError === void 0) { onError = null; }
  18338. var loadedFiles = [];
  18339. loadedFiles._internalCount = 0;
  18340. for (var index = 0; index < 6; index++) {
  18341. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  18342. }
  18343. };
  18344. // Statics
  18345. /**
  18346. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  18347. * @returns true if the engine can be created
  18348. * @ignorenaming
  18349. */
  18350. Engine.isSupported = function () {
  18351. try {
  18352. var tempcanvas = document.createElement("canvas");
  18353. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  18354. return gl != null && !!window.WebGLRenderingContext;
  18355. }
  18356. catch (e) {
  18357. return false;
  18358. }
  18359. };
  18360. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  18361. Engine.ExceptionList = [
  18362. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  18363. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18364. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18365. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18366. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18367. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  18368. ];
  18369. /** Gets the list of created engines */
  18370. Engine.Instances = new Array();
  18371. /**
  18372. * Hidden
  18373. */
  18374. Engine._TextureLoaders = [];
  18375. // Const statics
  18376. /** Defines that alpha blending is disabled */
  18377. Engine.ALPHA_DISABLE = 0;
  18378. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  18379. Engine.ALPHA_ADD = 1;
  18380. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  18381. Engine.ALPHA_COMBINE = 2;
  18382. /** Defines that alpha blending to DEST - SRC * DEST */
  18383. Engine.ALPHA_SUBTRACT = 3;
  18384. /** Defines that alpha blending to SRC * DEST */
  18385. Engine.ALPHA_MULTIPLY = 4;
  18386. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  18387. Engine.ALPHA_MAXIMIZED = 5;
  18388. /** Defines that alpha blending to SRC + DEST */
  18389. Engine.ALPHA_ONEONE = 6;
  18390. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  18391. Engine.ALPHA_PREMULTIPLIED = 7;
  18392. /**
  18393. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  18394. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  18395. */
  18396. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  18397. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  18398. Engine.ALPHA_INTERPOLATE = 9;
  18399. /**
  18400. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  18401. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  18402. */
  18403. Engine.ALPHA_SCREENMODE = 10;
  18404. /** Defines that the ressource is not delayed*/
  18405. Engine.DELAYLOADSTATE_NONE = 0;
  18406. /** Defines that the ressource was successfully delay loaded */
  18407. Engine.DELAYLOADSTATE_LOADED = 1;
  18408. /** Defines that the ressource is currently delay loading */
  18409. Engine.DELAYLOADSTATE_LOADING = 2;
  18410. /** Defines that the ressource is delayed and has not started loading */
  18411. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  18412. // Depht or Stencil test Constants.
  18413. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  18414. Engine.NEVER = 0x0200;
  18415. /** 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 */
  18416. Engine.ALWAYS = 0x0207;
  18417. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  18418. Engine.LESS = 0x0201;
  18419. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  18420. Engine.EQUAL = 0x0202;
  18421. /** 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 */
  18422. Engine.LEQUAL = 0x0203;
  18423. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  18424. Engine.GREATER = 0x0204;
  18425. /** 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 */
  18426. Engine.GEQUAL = 0x0206;
  18427. /** 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 */
  18428. Engine.NOTEQUAL = 0x0205;
  18429. // Stencil Actions Constants.
  18430. /** Passed to stencilOperation to specify that stencil value must be kept */
  18431. Engine.KEEP = 0x1E00;
  18432. /** Passed to stencilOperation to specify that stencil value must be replaced */
  18433. Engine.REPLACE = 0x1E01;
  18434. /** Passed to stencilOperation to specify that stencil value must be incremented */
  18435. Engine.INCR = 0x1E02;
  18436. /** Passed to stencilOperation to specify that stencil value must be decremented */
  18437. Engine.DECR = 0x1E03;
  18438. /** Passed to stencilOperation to specify that stencil value must be inverted */
  18439. Engine.INVERT = 0x150A;
  18440. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  18441. Engine.INCR_WRAP = 0x8507;
  18442. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  18443. Engine.DECR_WRAP = 0x8508;
  18444. /** Texture is not repeating outside of 0..1 UVs */
  18445. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  18446. /** Texture is repeating outside of 0..1 UVs */
  18447. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  18448. /** Texture is repeating and mirrored */
  18449. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  18450. /** ALPHA */
  18451. Engine.TEXTUREFORMAT_ALPHA = 0;
  18452. /** LUMINANCE */
  18453. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  18454. /** LUMINANCE_ALPHA */
  18455. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  18456. /** RGB */
  18457. Engine.TEXTUREFORMAT_RGB = 4;
  18458. /** RGBA */
  18459. Engine.TEXTUREFORMAT_RGBA = 5;
  18460. /** RED */
  18461. Engine.TEXTUREFORMAT_RED = 6;
  18462. /** RED (2nd reference) */
  18463. Engine.TEXTUREFORMAT_R = 6;
  18464. /** RG */
  18465. Engine.TEXTUREFORMAT_RG = 7;
  18466. /** RED_INTEGER */
  18467. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  18468. /** RED_INTEGER (2nd reference) */
  18469. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  18470. /** RG_INTEGER */
  18471. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  18472. /** RGB_INTEGER */
  18473. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  18474. /** RGBA_INTEGER */
  18475. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  18476. /** UNSIGNED_BYTE */
  18477. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  18478. /** UNSIGNED_BYTE (2nd reference) */
  18479. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  18480. /** FLOAT */
  18481. Engine.TEXTURETYPE_FLOAT = 1;
  18482. /** HALF_FLOAT */
  18483. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  18484. /** BYTE */
  18485. Engine.TEXTURETYPE_BYTE = 3;
  18486. /** SHORT */
  18487. Engine.TEXTURETYPE_SHORT = 4;
  18488. /** UNSIGNED_SHORT */
  18489. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  18490. /** INT */
  18491. Engine.TEXTURETYPE_INT = 6;
  18492. /** UNSIGNED_INT */
  18493. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  18494. /** UNSIGNED_SHORT_4_4_4_4 */
  18495. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  18496. /** UNSIGNED_SHORT_5_5_5_1 */
  18497. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  18498. /** UNSIGNED_SHORT_5_6_5 */
  18499. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  18500. /** UNSIGNED_INT_2_10_10_10_REV */
  18501. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  18502. /** UNSIGNED_INT_24_8 */
  18503. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  18504. /** UNSIGNED_INT_10F_11F_11F_REV */
  18505. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  18506. /** UNSIGNED_INT_5_9_9_9_REV */
  18507. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  18508. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  18509. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  18510. /** nearest is mag = nearest and min = nearest and mip = linear */
  18511. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  18512. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18513. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  18514. /** Trilinear is mag = linear and min = linear and mip = linear */
  18515. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  18516. /** nearest is mag = nearest and min = nearest and mip = linear */
  18517. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  18518. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18519. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  18520. /** Trilinear is mag = linear and min = linear and mip = linear */
  18521. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  18522. /** mag = nearest and min = nearest and mip = nearest */
  18523. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  18524. /** mag = nearest and min = linear and mip = nearest */
  18525. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  18526. /** mag = nearest and min = linear and mip = linear */
  18527. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  18528. /** mag = nearest and min = linear and mip = none */
  18529. Engine.TEXTURE_NEAREST_LINEAR = 7;
  18530. /** mag = nearest and min = nearest and mip = none */
  18531. Engine.TEXTURE_NEAREST_NEAREST = 8;
  18532. /** mag = linear and min = nearest and mip = nearest */
  18533. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  18534. /** mag = linear and min = nearest and mip = linear */
  18535. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  18536. /** mag = linear and min = linear and mip = none */
  18537. Engine.TEXTURE_LINEAR_LINEAR = 11;
  18538. /** mag = linear and min = nearest and mip = none */
  18539. Engine.TEXTURE_LINEAR_NEAREST = 12;
  18540. /** Explicit coordinates mode */
  18541. Engine.TEXTURE_EXPLICIT_MODE = 0;
  18542. /** Spherical coordinates mode */
  18543. Engine.TEXTURE_SPHERICAL_MODE = 1;
  18544. /** Planar coordinates mode */
  18545. Engine.TEXTURE_PLANAR_MODE = 2;
  18546. /** Cubic coordinates mode */
  18547. Engine.TEXTURE_CUBIC_MODE = 3;
  18548. /** Projection coordinates mode */
  18549. Engine.TEXTURE_PROJECTION_MODE = 4;
  18550. /** Skybox coordinates mode */
  18551. Engine.TEXTURE_SKYBOX_MODE = 5;
  18552. /** Inverse Cubic coordinates mode */
  18553. Engine.TEXTURE_INVCUBIC_MODE = 6;
  18554. /** Equirectangular coordinates mode */
  18555. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  18556. /** Equirectangular Fixed coordinates mode */
  18557. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  18558. /** Equirectangular Fixed Mirrored coordinates mode */
  18559. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18560. // Texture rescaling mode
  18561. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  18562. Engine.SCALEMODE_FLOOR = 1;
  18563. /** Defines that texture rescaling will look for the nearest power of 2 size */
  18564. Engine.SCALEMODE_NEAREST = 2;
  18565. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  18566. Engine.SCALEMODE_CEILING = 3;
  18567. // Updatable statics so stick with vars here
  18568. /**
  18569. * Gets or sets the epsilon value used by collision engine
  18570. */
  18571. Engine.CollisionsEpsilon = 0.001;
  18572. /**
  18573. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  18574. */
  18575. Engine.CodeRepository = "src/";
  18576. /**
  18577. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  18578. */
  18579. Engine.ShadersRepository = "src/Shaders/";
  18580. return Engine;
  18581. }());
  18582. BABYLON.Engine = Engine;
  18583. })(BABYLON || (BABYLON = {}));
  18584. //# sourceMappingURL=engine.js.map
  18585. var BABYLON;
  18586. (function (BABYLON) {
  18587. /**
  18588. * Node is the basic class for all scene objects (Mesh, Light, Camera.)
  18589. */
  18590. var Node = /** @class */ (function () {
  18591. /**
  18592. * Creates a new Node
  18593. * @param name the name and id to be given to this node
  18594. * @param scene the scene this node will be added to
  18595. * @param addToRootNodes the node will be added to scene.rootNodes
  18596. */
  18597. function Node(name, scene, addToRootNodes) {
  18598. if (scene === void 0) { scene = null; }
  18599. if (addToRootNodes === void 0) { addToRootNodes = true; }
  18600. /**
  18601. * Gets or sets a string used to store user defined state for the node
  18602. */
  18603. this.state = "";
  18604. /**
  18605. * Gets or sets an object used to store user defined information for the node
  18606. */
  18607. this.metadata = null;
  18608. /**
  18609. * Gets or sets a boolean used to define if the node must be serialized
  18610. */
  18611. this.doNotSerialize = false;
  18612. /** @hidden */
  18613. this._isDisposed = false;
  18614. /**
  18615. * Gets a list of Animations associated with the node
  18616. */
  18617. this.animations = new Array();
  18618. this._ranges = {};
  18619. this._isEnabled = true;
  18620. this._isParentEnabled = true;
  18621. this._isReady = true;
  18622. /** @hidden */
  18623. this._currentRenderId = -1;
  18624. this._parentRenderId = -1;
  18625. this._childRenderId = -1;
  18626. /** @hidden */
  18627. this._worldMatrix = BABYLON.Matrix.Identity();
  18628. /** @hidden */
  18629. this._worldMatrixDeterminant = 0;
  18630. /** @hidden */
  18631. this._sceneRootNodesIndex = -1;
  18632. this._animationPropertiesOverride = null;
  18633. /**
  18634. * An event triggered when the mesh is disposed
  18635. */
  18636. this.onDisposeObservable = new BABYLON.Observable();
  18637. // Behaviors
  18638. this._behaviors = new Array();
  18639. this.name = name;
  18640. this.id = name;
  18641. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  18642. this.uniqueId = this._scene.getUniqueId();
  18643. this._initCache();
  18644. if (addToRootNodes) {
  18645. this.addToSceneRootNodes();
  18646. }
  18647. }
  18648. /**
  18649. * Add a new node constructor
  18650. * @param type defines the type name of the node to construct
  18651. * @param constructorFunc defines the constructor function
  18652. */
  18653. Node.AddNodeConstructor = function (type, constructorFunc) {
  18654. this._NodeConstructors[type] = constructorFunc;
  18655. };
  18656. /**
  18657. * Returns a node constructor based on type name
  18658. * @param type defines the type name
  18659. * @param name defines the new node name
  18660. * @param scene defines the hosting scene
  18661. * @param options defines optional options to transmit to constructors
  18662. * @returns the new constructor or null
  18663. */
  18664. Node.Construct = function (type, name, scene, options) {
  18665. var constructorFunc = this._NodeConstructors[type];
  18666. if (!constructorFunc) {
  18667. return null;
  18668. }
  18669. return constructorFunc(name, scene, options);
  18670. };
  18671. /**
  18672. * Gets a boolean indicating if the node has been disposed
  18673. * @returns true if the node was disposed
  18674. */
  18675. Node.prototype.isDisposed = function () {
  18676. return this._isDisposed;
  18677. };
  18678. Object.defineProperty(Node.prototype, "parent", {
  18679. get: function () {
  18680. return this._parentNode;
  18681. },
  18682. /**
  18683. * Gets or sets the parent of the node
  18684. */
  18685. set: function (parent) {
  18686. if (this._parentNode === parent) {
  18687. return;
  18688. }
  18689. var previousParentNode = this._parentNode;
  18690. // Remove self from list of children of parent
  18691. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  18692. var index = this._parentNode._children.indexOf(this);
  18693. if (index !== -1) {
  18694. this._parentNode._children.splice(index, 1);
  18695. }
  18696. if (!parent) {
  18697. this.addToSceneRootNodes();
  18698. }
  18699. }
  18700. // Store new parent
  18701. this._parentNode = parent;
  18702. // Add as child to new parent
  18703. if (this._parentNode) {
  18704. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  18705. this._parentNode._children = new Array();
  18706. }
  18707. this._parentNode._children.push(this);
  18708. if (!previousParentNode) {
  18709. this.removeFromSceneRootNodes();
  18710. }
  18711. }
  18712. // Enabled state
  18713. this._syncParentEnabledState();
  18714. },
  18715. enumerable: true,
  18716. configurable: true
  18717. });
  18718. Node.prototype.addToSceneRootNodes = function () {
  18719. if (this._sceneRootNodesIndex === -1) {
  18720. this._sceneRootNodesIndex = this._scene.rootNodes.length;
  18721. this._scene.rootNodes.push(this);
  18722. }
  18723. };
  18724. Node.prototype.removeFromSceneRootNodes = function () {
  18725. if (this._sceneRootNodesIndex !== -1) {
  18726. var rootNodes = this._scene.rootNodes;
  18727. var lastIdx = rootNodes.length - 1;
  18728. rootNodes[this._sceneRootNodesIndex] = rootNodes[lastIdx];
  18729. rootNodes[this._sceneRootNodesIndex]._sceneRootNodesIndex = this._sceneRootNodesIndex;
  18730. this._scene.rootNodes.pop();
  18731. this._sceneRootNodesIndex = -1;
  18732. }
  18733. };
  18734. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  18735. /**
  18736. * Gets or sets the animation properties override
  18737. */
  18738. get: function () {
  18739. if (!this._animationPropertiesOverride) {
  18740. return this._scene.animationPropertiesOverride;
  18741. }
  18742. return this._animationPropertiesOverride;
  18743. },
  18744. set: function (value) {
  18745. this._animationPropertiesOverride = value;
  18746. },
  18747. enumerable: true,
  18748. configurable: true
  18749. });
  18750. /**
  18751. * Gets a string idenfifying the name of the class
  18752. * @returns "Node" string
  18753. */
  18754. Node.prototype.getClassName = function () {
  18755. return "Node";
  18756. };
  18757. Object.defineProperty(Node.prototype, "onDispose", {
  18758. /**
  18759. * Sets a callback that will be raised when the node will be disposed
  18760. */
  18761. set: function (callback) {
  18762. if (this._onDisposeObserver) {
  18763. this.onDisposeObservable.remove(this._onDisposeObserver);
  18764. }
  18765. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18766. },
  18767. enumerable: true,
  18768. configurable: true
  18769. });
  18770. /**
  18771. * Gets the scene of the node
  18772. * @returns a scene
  18773. */
  18774. Node.prototype.getScene = function () {
  18775. return this._scene;
  18776. };
  18777. /**
  18778. * Gets the engine of the node
  18779. * @returns a Engine
  18780. */
  18781. Node.prototype.getEngine = function () {
  18782. return this._scene.getEngine();
  18783. };
  18784. /**
  18785. * Attach a behavior to the node
  18786. * @see http://doc.babylonjs.com/features/behaviour
  18787. * @param behavior defines the behavior to attach
  18788. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  18789. * @returns the current Node
  18790. */
  18791. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  18792. var _this = this;
  18793. if (attachImmediately === void 0) { attachImmediately = false; }
  18794. var index = this._behaviors.indexOf(behavior);
  18795. if (index !== -1) {
  18796. return this;
  18797. }
  18798. behavior.init();
  18799. if (this._scene.isLoading && !attachImmediately) {
  18800. // We defer the attach when the scene will be loaded
  18801. this._scene.onDataLoadedObservable.addOnce(function () {
  18802. behavior.attach(_this);
  18803. });
  18804. }
  18805. else {
  18806. behavior.attach(this);
  18807. }
  18808. this._behaviors.push(behavior);
  18809. return this;
  18810. };
  18811. /**
  18812. * Remove an attached behavior
  18813. * @see http://doc.babylonjs.com/features/behaviour
  18814. * @param behavior defines the behavior to attach
  18815. * @returns the current Node
  18816. */
  18817. Node.prototype.removeBehavior = function (behavior) {
  18818. var index = this._behaviors.indexOf(behavior);
  18819. if (index === -1) {
  18820. return this;
  18821. }
  18822. this._behaviors[index].detach();
  18823. this._behaviors.splice(index, 1);
  18824. return this;
  18825. };
  18826. Object.defineProperty(Node.prototype, "behaviors", {
  18827. /**
  18828. * Gets the list of attached behaviors
  18829. * @see http://doc.babylonjs.com/features/behaviour
  18830. */
  18831. get: function () {
  18832. return this._behaviors;
  18833. },
  18834. enumerable: true,
  18835. configurable: true
  18836. });
  18837. /**
  18838. * Gets an attached behavior by name
  18839. * @param name defines the name of the behavior to look for
  18840. * @see http://doc.babylonjs.com/features/behaviour
  18841. * @returns null if behavior was not found else the requested behavior
  18842. */
  18843. Node.prototype.getBehaviorByName = function (name) {
  18844. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  18845. var behavior = _a[_i];
  18846. if (behavior.name === name) {
  18847. return behavior;
  18848. }
  18849. }
  18850. return null;
  18851. };
  18852. /**
  18853. * Returns the latest update of the World matrix
  18854. * @returns a Matrix
  18855. */
  18856. Node.prototype.getWorldMatrix = function () {
  18857. if (this._currentRenderId !== this._scene.getRenderId()) {
  18858. this.computeWorldMatrix();
  18859. }
  18860. return this._worldMatrix;
  18861. };
  18862. /** @hidden */
  18863. Node.prototype._getWorldMatrixDeterminant = function () {
  18864. return this._worldMatrixDeterminant;
  18865. };
  18866. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  18867. /**
  18868. * Returns directly the latest state of the mesh World matrix.
  18869. * A Matrix is returned.
  18870. */
  18871. get: function () {
  18872. return this._worldMatrix;
  18873. },
  18874. enumerable: true,
  18875. configurable: true
  18876. });
  18877. // override it in derived class if you add new variables to the cache
  18878. // and call the parent class method
  18879. /** @hidden */
  18880. Node.prototype._initCache = function () {
  18881. this._cache = {};
  18882. this._cache.parent = undefined;
  18883. };
  18884. /** @hidden */
  18885. Node.prototype.updateCache = function (force) {
  18886. if (!force && this.isSynchronized()) {
  18887. return;
  18888. }
  18889. this._cache.parent = this.parent;
  18890. this._updateCache();
  18891. };
  18892. // override it in derived class if you add new variables to the cache
  18893. // and call the parent class method if !ignoreParentClass
  18894. /** @hidden */
  18895. Node.prototype._updateCache = function (ignoreParentClass) {
  18896. };
  18897. // override it in derived class if you add new variables to the cache
  18898. /** @hidden */
  18899. Node.prototype._isSynchronized = function () {
  18900. return true;
  18901. };
  18902. /** @hidden */
  18903. Node.prototype._markSyncedWithParent = function () {
  18904. if (this._parentNode) {
  18905. this._parentRenderId = this._parentNode._childRenderId;
  18906. }
  18907. };
  18908. /** @hidden */
  18909. Node.prototype.isSynchronizedWithParent = function () {
  18910. if (!this._parentNode) {
  18911. return true;
  18912. }
  18913. if (this._parentRenderId !== this._parentNode._childRenderId) {
  18914. return false;
  18915. }
  18916. return this._parentNode.isSynchronized();
  18917. };
  18918. /** @hidden */
  18919. Node.prototype.isSynchronized = function () {
  18920. if (this._cache.parent != this._parentNode) {
  18921. this._cache.parent = this._parentNode;
  18922. return false;
  18923. }
  18924. if (this._parentNode && !this.isSynchronizedWithParent()) {
  18925. return false;
  18926. }
  18927. return this._isSynchronized();
  18928. };
  18929. /**
  18930. * Is this node ready to be used/rendered
  18931. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18932. * @return true if the node is ready
  18933. */
  18934. Node.prototype.isReady = function (completeCheck) {
  18935. if (completeCheck === void 0) { completeCheck = false; }
  18936. return this._isReady;
  18937. };
  18938. /**
  18939. * Is this node enabled?
  18940. * 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
  18941. * @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
  18942. * @return whether this node (and its parent) is enabled
  18943. */
  18944. Node.prototype.isEnabled = function (checkAncestors) {
  18945. if (checkAncestors === void 0) { checkAncestors = true; }
  18946. if (checkAncestors === false) {
  18947. return this._isEnabled;
  18948. }
  18949. if (!this._isEnabled) {
  18950. return false;
  18951. }
  18952. return this._isParentEnabled;
  18953. };
  18954. /** @hidden */
  18955. Node.prototype._syncParentEnabledState = function () {
  18956. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  18957. if (this._children) {
  18958. this._children.forEach(function (c) {
  18959. c._syncParentEnabledState(); // Force children to update accordingly
  18960. });
  18961. }
  18962. };
  18963. /**
  18964. * Set the enabled state of this node
  18965. * @param value defines the new enabled state
  18966. */
  18967. Node.prototype.setEnabled = function (value) {
  18968. this._isEnabled = value;
  18969. this._syncParentEnabledState();
  18970. };
  18971. /**
  18972. * Is this node a descendant of the given node?
  18973. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18974. * @param ancestor defines the parent node to inspect
  18975. * @returns a boolean indicating if this node is a descendant of the given node
  18976. */
  18977. Node.prototype.isDescendantOf = function (ancestor) {
  18978. if (this.parent) {
  18979. if (this.parent === ancestor) {
  18980. return true;
  18981. }
  18982. return this.parent.isDescendantOf(ancestor);
  18983. }
  18984. return false;
  18985. };
  18986. /** @hidden */
  18987. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18988. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18989. if (!this._children) {
  18990. return;
  18991. }
  18992. for (var index = 0; index < this._children.length; index++) {
  18993. var item = this._children[index];
  18994. if (!predicate || predicate(item)) {
  18995. results.push(item);
  18996. }
  18997. if (!directDescendantsOnly) {
  18998. item._getDescendants(results, false, predicate);
  18999. }
  19000. }
  19001. };
  19002. /**
  19003. * Will return all nodes that have this node as ascendant
  19004. * @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
  19005. * @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
  19006. * @return all children nodes of all types
  19007. */
  19008. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  19009. var results = new Array();
  19010. this._getDescendants(results, directDescendantsOnly, predicate);
  19011. return results;
  19012. };
  19013. /**
  19014. * Get all child-meshes of this node
  19015. * @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
  19016. * @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
  19017. * @returns an array of AbstractMesh
  19018. */
  19019. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  19020. var results = [];
  19021. this._getDescendants(results, directDescendantsOnly, function (node) {
  19022. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  19023. });
  19024. return results;
  19025. };
  19026. /**
  19027. * Get all child-transformNodes of this node
  19028. * @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
  19029. * @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
  19030. * @returns an array of TransformNode
  19031. */
  19032. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  19033. var results = [];
  19034. this._getDescendants(results, directDescendantsOnly, function (node) {
  19035. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  19036. });
  19037. return results;
  19038. };
  19039. /**
  19040. * Get all direct children of this node
  19041. * @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
  19042. * @returns an array of Node
  19043. */
  19044. Node.prototype.getChildren = function (predicate) {
  19045. return this.getDescendants(true, predicate);
  19046. };
  19047. /** @hidden */
  19048. Node.prototype._setReady = function (state) {
  19049. if (state === this._isReady) {
  19050. return;
  19051. }
  19052. if (!state) {
  19053. this._isReady = false;
  19054. return;
  19055. }
  19056. if (this.onReady) {
  19057. this.onReady(this);
  19058. }
  19059. this._isReady = true;
  19060. };
  19061. /**
  19062. * Get an animation by name
  19063. * @param name defines the name of the animation to look for
  19064. * @returns null if not found else the requested animation
  19065. */
  19066. Node.prototype.getAnimationByName = function (name) {
  19067. for (var i = 0; i < this.animations.length; i++) {
  19068. var animation = this.animations[i];
  19069. if (animation.name === name) {
  19070. return animation;
  19071. }
  19072. }
  19073. return null;
  19074. };
  19075. /**
  19076. * Creates an animation range for this node
  19077. * @param name defines the name of the range
  19078. * @param from defines the starting key
  19079. * @param to defines the end key
  19080. */
  19081. Node.prototype.createAnimationRange = function (name, from, to) {
  19082. // check name not already in use
  19083. if (!this._ranges[name]) {
  19084. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  19085. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  19086. if (this.animations[i]) {
  19087. this.animations[i].createRange(name, from, to);
  19088. }
  19089. }
  19090. }
  19091. };
  19092. /**
  19093. * Delete a specific animation range
  19094. * @param name defines the name of the range to delete
  19095. * @param deleteFrames defines if animation frames from the range must be deleted as well
  19096. */
  19097. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  19098. if (deleteFrames === void 0) { deleteFrames = true; }
  19099. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  19100. if (this.animations[i]) {
  19101. this.animations[i].deleteRange(name, deleteFrames);
  19102. }
  19103. }
  19104. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  19105. };
  19106. /**
  19107. * Get an animation range by name
  19108. * @param name defines the name of the animation range to look for
  19109. * @returns null if not found else the requested animation range
  19110. */
  19111. Node.prototype.getAnimationRange = function (name) {
  19112. return this._ranges[name];
  19113. };
  19114. /**
  19115. * Will start the animation sequence
  19116. * @param name defines the range frames for animation sequence
  19117. * @param loop defines if the animation should loop (false by default)
  19118. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  19119. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  19120. * @returns the object created for this animation. If range does not exist, it will return null
  19121. */
  19122. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  19123. var range = this.getAnimationRange(name);
  19124. if (!range) {
  19125. return null;
  19126. }
  19127. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  19128. };
  19129. /**
  19130. * Serialize animation ranges into a JSON compatible object
  19131. * @returns serialization object
  19132. */
  19133. Node.prototype.serializeAnimationRanges = function () {
  19134. var serializationRanges = [];
  19135. for (var name in this._ranges) {
  19136. var localRange = this._ranges[name];
  19137. if (!localRange) {
  19138. continue;
  19139. }
  19140. var range = {};
  19141. range.name = name;
  19142. range.from = localRange.from;
  19143. range.to = localRange.to;
  19144. serializationRanges.push(range);
  19145. }
  19146. return serializationRanges;
  19147. };
  19148. /**
  19149. * Computes the world matrix of the node
  19150. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  19151. * @returns the world matrix
  19152. */
  19153. Node.prototype.computeWorldMatrix = function (force) {
  19154. if (!this._worldMatrix) {
  19155. this._worldMatrix = BABYLON.Matrix.Identity();
  19156. }
  19157. return this._worldMatrix;
  19158. };
  19159. /**
  19160. * Releases resources associated with this node.
  19161. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19162. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19163. */
  19164. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19165. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19166. if (!doNotRecurse) {
  19167. var nodes = this.getDescendants(true);
  19168. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  19169. var node = nodes_1[_i];
  19170. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  19171. }
  19172. }
  19173. else {
  19174. var transformNodes = this.getChildTransformNodes(true);
  19175. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  19176. var transformNode = transformNodes_1[_a];
  19177. transformNode.parent = null;
  19178. transformNode.computeWorldMatrix(true);
  19179. }
  19180. }
  19181. if (!this.parent) {
  19182. this.removeFromSceneRootNodes();
  19183. }
  19184. else {
  19185. this.parent = null;
  19186. }
  19187. // Callback
  19188. this.onDisposeObservable.notifyObservers(this);
  19189. this.onDisposeObservable.clear();
  19190. // Behaviors
  19191. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  19192. var behavior = _c[_b];
  19193. behavior.detach();
  19194. }
  19195. this._behaviors = [];
  19196. this._isDisposed = true;
  19197. };
  19198. /**
  19199. * Parse animation range data from a serialization object and store them into a given node
  19200. * @param node defines where to store the animation ranges
  19201. * @param parsedNode defines the serialization object to read data from
  19202. * @param scene defines the hosting scene
  19203. */
  19204. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  19205. if (parsedNode.ranges) {
  19206. for (var index = 0; index < parsedNode.ranges.length; index++) {
  19207. var data = parsedNode.ranges[index];
  19208. node.createAnimationRange(data.name, data.from, data.to);
  19209. }
  19210. }
  19211. };
  19212. Node._NodeConstructors = {};
  19213. __decorate([
  19214. BABYLON.serialize()
  19215. ], Node.prototype, "name", void 0);
  19216. __decorate([
  19217. BABYLON.serialize()
  19218. ], Node.prototype, "id", void 0);
  19219. __decorate([
  19220. BABYLON.serialize()
  19221. ], Node.prototype, "uniqueId", void 0);
  19222. __decorate([
  19223. BABYLON.serialize()
  19224. ], Node.prototype, "state", void 0);
  19225. __decorate([
  19226. BABYLON.serialize()
  19227. ], Node.prototype, "metadata", void 0);
  19228. return Node;
  19229. }());
  19230. BABYLON.Node = Node;
  19231. })(BABYLON || (BABYLON = {}));
  19232. //# sourceMappingURL=node.js.map
  19233. var BABYLON;
  19234. (function (BABYLON) {
  19235. /**
  19236. * Class used to store bounding sphere information
  19237. */
  19238. var BoundingSphere = /** @class */ (function () {
  19239. /**
  19240. * Creates a new bounding sphere
  19241. * @param min defines the minimum vector (in local space)
  19242. * @param max defines the maximum vector (in local space)
  19243. * @param worldMatrix defines the new world matrix
  19244. */
  19245. function BoundingSphere(min, max, worldMatrix) {
  19246. /**
  19247. * Gets the center of the bounding sphere in local space
  19248. */
  19249. this.center = BABYLON.Vector3.Zero();
  19250. /**
  19251. * Gets the center of the bounding sphere in world space
  19252. */
  19253. this.centerWorld = BABYLON.Vector3.Zero();
  19254. /**
  19255. * Gets the minimum vector in local space
  19256. */
  19257. this.minimum = BABYLON.Vector3.Zero();
  19258. /**
  19259. * Gets the maximum vector in local space
  19260. */
  19261. this.maximum = BABYLON.Vector3.Zero();
  19262. this.reConstruct(min, max, worldMatrix);
  19263. }
  19264. /**
  19265. * Recreates the entire bounding sphere from scratch as if we call the constructor in place
  19266. * @param min defines the new minimum vector (in local space)
  19267. * @param max defines the new maximum vector (in local space)
  19268. * @param worldMatrix defines the new world matrix
  19269. */
  19270. BoundingSphere.prototype.reConstruct = function (min, max, worldMatrix) {
  19271. this.minimum.copyFrom(min);
  19272. this.maximum.copyFrom(max);
  19273. var distance = BABYLON.Vector3.Distance(min, max);
  19274. max.addToRef(min, this.center).scaleInPlace(0.5);
  19275. this.radius = distance * 0.5;
  19276. this._update(worldMatrix || BABYLON.Matrix.IdentityReadOnly);
  19277. };
  19278. /**
  19279. * Scale the current bounding sphere by applying a scale factor
  19280. * @param factor defines the scale factor to apply
  19281. * @returns the current bounding box
  19282. */
  19283. BoundingSphere.prototype.scale = function (factor) {
  19284. var newRadius = this.radius * factor;
  19285. var tmpVectors = BoundingSphere.TmpVector3;
  19286. var tempRadiusVector = tmpVectors[0].setAll(newRadius);
  19287. var min = this.center.subtractToRef(tempRadiusVector, tmpVectors[1]);
  19288. var max = this.center.addToRef(tempRadiusVector, tmpVectors[2]);
  19289. this.reConstruct(min, max, this._worldMatrix);
  19290. return this;
  19291. };
  19292. /**
  19293. * Gets the world matrix of the bounding box
  19294. * @returns a matrix
  19295. */
  19296. BoundingSphere.prototype.getWorldMatrix = function () {
  19297. return this._worldMatrix;
  19298. };
  19299. // Methods
  19300. /** @hidden */
  19301. BoundingSphere.prototype._update = function (worldMatrix) {
  19302. if (!worldMatrix.isIdentity()) {
  19303. BABYLON.Vector3.TransformCoordinatesToRef(this.center, worldMatrix, this.centerWorld);
  19304. var tempVector = BoundingSphere.TmpVector3[0];
  19305. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, worldMatrix, tempVector);
  19306. this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius;
  19307. }
  19308. else {
  19309. this.centerWorld.copyFrom(this.center);
  19310. this.radiusWorld = this.radius;
  19311. }
  19312. };
  19313. /**
  19314. * Tests if the bounding sphere is intersecting the frustum planes
  19315. * @param frustumPlanes defines the frustum planes to test
  19316. * @returns true if there is an intersection
  19317. */
  19318. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  19319. for (var i = 0; i < 6; i++) {
  19320. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld) {
  19321. return false;
  19322. }
  19323. }
  19324. return true;
  19325. };
  19326. /**
  19327. * Tests if a point is inside the bounding sphere
  19328. * @param point defines the point to test
  19329. * @returns true if the point is inside the bounding sphere
  19330. */
  19331. BoundingSphere.prototype.intersectsPoint = function (point) {
  19332. var squareDistance = BABYLON.Vector3.DistanceSquared(this.centerWorld, point);
  19333. if (this.radiusWorld * this.radiusWorld < squareDistance) {
  19334. return false;
  19335. }
  19336. return true;
  19337. };
  19338. // Statics
  19339. /**
  19340. * Checks if two sphere intersct
  19341. * @param sphere0 sphere 0
  19342. * @param sphere1 sphere 1
  19343. * @returns true if the speres intersect
  19344. */
  19345. BoundingSphere.Intersects = function (sphere0, sphere1) {
  19346. var squareDistance = BABYLON.Vector3.DistanceSquared(sphere0.centerWorld, sphere1.centerWorld);
  19347. var radiusSum = sphere0.radiusWorld + sphere1.radiusWorld;
  19348. if (radiusSum * radiusSum < squareDistance) {
  19349. return false;
  19350. }
  19351. return true;
  19352. };
  19353. BoundingSphere.TmpVector3 = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  19354. return BoundingSphere;
  19355. }());
  19356. BABYLON.BoundingSphere = BoundingSphere;
  19357. })(BABYLON || (BABYLON = {}));
  19358. //# sourceMappingURL=boundingSphere.js.map
  19359. var BABYLON;
  19360. (function (BABYLON) {
  19361. /**
  19362. * Class used to store bounding box information
  19363. */
  19364. var BoundingBox = /** @class */ (function () {
  19365. /**
  19366. * Creates a new bounding box
  19367. * @param min defines the minimum vector (in local space)
  19368. * @param max defines the maximum vector (in local space)
  19369. * @param worldMatrix defines the new world matrix
  19370. */
  19371. function BoundingBox(min, max, worldMatrix) {
  19372. /**
  19373. * Gets the 8 vectors representing the bounding box in local space
  19374. */
  19375. this.vectors = BABYLON.Tools.BuildArray(8, BABYLON.Vector3.Zero);
  19376. /**
  19377. * Gets the center of the bounding box in local space
  19378. */
  19379. this.center = BABYLON.Vector3.Zero();
  19380. /**
  19381. * Gets the center of the bounding box in world space
  19382. */
  19383. this.centerWorld = BABYLON.Vector3.Zero();
  19384. /**
  19385. * Gets the extend size in local space
  19386. */
  19387. this.extendSize = BABYLON.Vector3.Zero();
  19388. /**
  19389. * Gets the extend size in world space
  19390. */
  19391. this.extendSizeWorld = BABYLON.Vector3.Zero();
  19392. /**
  19393. * Gets the OBB (object bounding box) directions
  19394. */
  19395. this.directions = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  19396. /**
  19397. * Gets the 8 vectors representing the bounding box in world space
  19398. */
  19399. this.vectorsWorld = BABYLON.Tools.BuildArray(8, BABYLON.Vector3.Zero);
  19400. /**
  19401. * Gets the minimum vector in world space
  19402. */
  19403. this.minimumWorld = BABYLON.Vector3.Zero();
  19404. /**
  19405. * Gets the maximum vector in world space
  19406. */
  19407. this.maximumWorld = BABYLON.Vector3.Zero();
  19408. /**
  19409. * Gets the minimum vector in local space
  19410. */
  19411. this.minimum = BABYLON.Vector3.Zero();
  19412. /**
  19413. * Gets the maximum vector in local space
  19414. */
  19415. this.maximum = BABYLON.Vector3.Zero();
  19416. this.reConstruct(min, max, worldMatrix);
  19417. }
  19418. // Methods
  19419. /**
  19420. * Recreates the entire bounding box from scratch as if we call the constructor in place
  19421. * @param min defines the new minimum vector (in local space)
  19422. * @param max defines the new maximum vector (in local space)
  19423. * @param worldMatrix defines the new world matrix
  19424. */
  19425. BoundingBox.prototype.reConstruct = function (min, max, worldMatrix) {
  19426. var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
  19427. var vectors = this.vectors;
  19428. this.minimum.copyFromFloats(minX, minY, minZ);
  19429. this.maximum.copyFromFloats(maxX, maxY, maxZ);
  19430. vectors[0].copyFromFloats(minX, minY, minZ);
  19431. vectors[1].copyFromFloats(maxX, maxY, maxZ);
  19432. vectors[2].copyFromFloats(maxX, minY, minZ);
  19433. vectors[3].copyFromFloats(minX, maxY, minZ);
  19434. vectors[4].copyFromFloats(minX, minY, maxZ);
  19435. vectors[5].copyFromFloats(maxX, maxY, minZ);
  19436. vectors[6].copyFromFloats(minX, maxY, maxZ);
  19437. vectors[7].copyFromFloats(maxX, minY, maxZ);
  19438. // OBB
  19439. max.addToRef(min, this.center).scaleInPlace(0.5);
  19440. max.subtractToRef(min, this.extendSize).scaleInPlace(0.5);
  19441. this._update(worldMatrix || BABYLON.Matrix.IdentityReadOnly);
  19442. };
  19443. /**
  19444. * Scale the current bounding box by applying a scale factor
  19445. * @param factor defines the scale factor to apply
  19446. * @returns the current bounding box
  19447. */
  19448. BoundingBox.prototype.scale = function (factor) {
  19449. var tmpVectors = BoundingBox.TmpVector3;
  19450. var diff = this.maximum.subtractToRef(this.minimum, tmpVectors[0]);
  19451. var len = diff.length();
  19452. diff.normalizeFromLength(len);
  19453. var distance = len * factor;
  19454. var newRadius = diff.scaleInPlace(distance * 0.5);
  19455. var min = this.center.subtractToRef(newRadius, tmpVectors[1]);
  19456. var max = this.center.addToRef(newRadius, tmpVectors[2]);
  19457. this.reConstruct(min, max, this._worldMatrix);
  19458. return this;
  19459. };
  19460. /**
  19461. * Gets the world matrix of the bounding box
  19462. * @returns a matrix
  19463. */
  19464. BoundingBox.prototype.getWorldMatrix = function () {
  19465. return this._worldMatrix;
  19466. };
  19467. /** @hidden */
  19468. BoundingBox.prototype._update = function (world) {
  19469. var minWorld = this.minimumWorld;
  19470. var maxWorld = this.maximumWorld;
  19471. var directions = this.directions;
  19472. var vectorsWorld = this.vectorsWorld;
  19473. var vectors = this.vectors;
  19474. if (!world.isIdentity()) {
  19475. minWorld.setAll(Number.MAX_VALUE);
  19476. maxWorld.setAll(-Number.MAX_VALUE);
  19477. for (var index = 0; index < 8; ++index) {
  19478. var v = vectorsWorld[index];
  19479. BABYLON.Vector3.TransformCoordinatesToRef(vectors[index], world, v);
  19480. minWorld.minimizeInPlace(v);
  19481. maxWorld.maximizeInPlace(v);
  19482. }
  19483. // Extend
  19484. maxWorld.subtractToRef(minWorld, this.extendSizeWorld).scaleInPlace(0.5);
  19485. maxWorld.addToRef(minWorld, this.centerWorld).scaleInPlace(0.5);
  19486. }
  19487. else {
  19488. minWorld.copyFrom(this.minimum);
  19489. maxWorld.copyFrom(this.maximum);
  19490. for (var index = 0; index < 8; ++index) {
  19491. vectorsWorld[index].copyFrom(vectors[index]);
  19492. }
  19493. // Extend
  19494. this.extendSizeWorld.copyFrom(this.extendSize);
  19495. this.centerWorld.copyFrom(this.center);
  19496. }
  19497. BABYLON.Vector3.FromArrayToRef(world.m, 0, directions[0]);
  19498. BABYLON.Vector3.FromArrayToRef(world.m, 4, directions[1]);
  19499. BABYLON.Vector3.FromArrayToRef(world.m, 8, directions[2]);
  19500. this._worldMatrix = world;
  19501. };
  19502. /**
  19503. * Tests if the bounding box is intersecting the frustum planes
  19504. * @param frustumPlanes defines the frustum planes to test
  19505. * @returns true if there is an intersection
  19506. */
  19507. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  19508. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  19509. };
  19510. /**
  19511. * Tests if the bounding box is entirely inside the frustum planes
  19512. * @param frustumPlanes defines the frustum planes to test
  19513. * @returns true if there is an inclusion
  19514. */
  19515. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19516. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  19517. };
  19518. /**
  19519. * Tests if a point is inside the bounding box
  19520. * @param point defines the point to test
  19521. * @returns true if the point is inside the bounding box
  19522. */
  19523. BoundingBox.prototype.intersectsPoint = function (point) {
  19524. var min = this.minimumWorld;
  19525. var max = this.maximumWorld;
  19526. var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
  19527. var pointX = point.x, pointY = point.y, pointZ = point.z;
  19528. var delta = -BABYLON.Epsilon;
  19529. if (maxX - pointX < delta || delta > pointX - minX) {
  19530. return false;
  19531. }
  19532. if (maxY - pointY < delta || delta > pointY - minY) {
  19533. return false;
  19534. }
  19535. if (maxZ - pointZ < delta || delta > pointZ - minZ) {
  19536. return false;
  19537. }
  19538. return true;
  19539. };
  19540. /**
  19541. * Tests if the bounding box intersects with a bounding sphere
  19542. * @param sphere defines the sphere to test
  19543. * @returns true if there is an intersection
  19544. */
  19545. BoundingBox.prototype.intersectsSphere = function (sphere) {
  19546. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  19547. };
  19548. /**
  19549. * Tests if the bounding box intersects with a box defined by a min and max vectors
  19550. * @param min defines the min vector to use
  19551. * @param max defines the max vector to use
  19552. * @returns true if there is an intersection
  19553. */
  19554. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  19555. var myMin = this.minimumWorld;
  19556. var myMax = this.maximumWorld;
  19557. var myMinX = myMin.x, myMinY = myMin.y, myMinZ = myMin.z, myMaxX = myMax.x, myMaxY = myMax.y, myMaxZ = myMax.z;
  19558. var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
  19559. if (myMaxX < minX || myMinX > maxX) {
  19560. return false;
  19561. }
  19562. if (myMaxY < minY || myMinY > maxY) {
  19563. return false;
  19564. }
  19565. if (myMaxZ < minZ || myMinZ > maxZ) {
  19566. return false;
  19567. }
  19568. return true;
  19569. };
  19570. // Statics
  19571. /**
  19572. * Tests if two bounding boxes are intersections
  19573. * @param box0 defines the first box to test
  19574. * @param box1 defines the second box to test
  19575. * @returns true if there is an intersection
  19576. */
  19577. BoundingBox.Intersects = function (box0, box1) {
  19578. return box0.intersectsMinMax(box1.minimumWorld, box1.maximumWorld);
  19579. };
  19580. /**
  19581. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  19582. * @param minPoint defines the minimum vector of the bounding box
  19583. * @param maxPoint defines the maximum vector of the bounding box
  19584. * @param sphereCenter defines the sphere center
  19585. * @param sphereRadius defines the sphere radius
  19586. * @returns true if there is an intersection
  19587. */
  19588. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  19589. var vector = BoundingBox.TmpVector3[0];
  19590. BABYLON.Vector3.ClampToRef(sphereCenter, minPoint, maxPoint, vector);
  19591. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  19592. return (num <= (sphereRadius * sphereRadius));
  19593. };
  19594. /**
  19595. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  19596. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19597. * @param frustumPlanes defines the frustum planes to test
  19598. * @return true if there is an inclusion
  19599. */
  19600. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  19601. for (var p = 0; p < 6; ++p) {
  19602. var frustumPlane = frustumPlanes[p];
  19603. for (var i = 0; i < 8; ++i) {
  19604. if (frustumPlane.dotCoordinate(boundingVectors[i]) < 0) {
  19605. return false;
  19606. }
  19607. }
  19608. }
  19609. return true;
  19610. };
  19611. /**
  19612. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  19613. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19614. * @param frustumPlanes defines the frustum planes to test
  19615. * @return true if there is an intersection
  19616. */
  19617. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  19618. for (var p = 0; p < 6; ++p) {
  19619. var canReturnFalse = true;
  19620. var frustumPlane = frustumPlanes[p];
  19621. for (var i = 0; i < 8; ++i) {
  19622. if (frustumPlane.dotCoordinate(boundingVectors[i]) >= 0) {
  19623. canReturnFalse = false;
  19624. break;
  19625. }
  19626. }
  19627. if (canReturnFalse) {
  19628. return false;
  19629. }
  19630. }
  19631. return true;
  19632. };
  19633. BoundingBox.TmpVector3 = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  19634. return BoundingBox;
  19635. }());
  19636. BABYLON.BoundingBox = BoundingBox;
  19637. })(BABYLON || (BABYLON = {}));
  19638. //# sourceMappingURL=boundingBox.js.map
  19639. var BABYLON;
  19640. (function (BABYLON) {
  19641. var _result0 = { min: 0, max: 0 };
  19642. var _result1 = { min: 0, max: 0 };
  19643. var computeBoxExtents = function (axis, box, result) {
  19644. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  19645. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  19646. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  19647. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  19648. var r = r0 + r1 + r2;
  19649. result.min = p - r;
  19650. result.max = p + r;
  19651. };
  19652. var axisOverlap = function (axis, box0, box1) {
  19653. computeBoxExtents(axis, box0, _result0);
  19654. computeBoxExtents(axis, box1, _result1);
  19655. return !(_result0.min > _result1.max || _result1.min > _result0.max);
  19656. };
  19657. /**
  19658. * Info for a bounding data of a mesh
  19659. */
  19660. var BoundingInfo = /** @class */ (function () {
  19661. /**
  19662. * Constructs bounding info
  19663. * @param minimum min vector of the bounding box/sphere
  19664. * @param maximum max vector of the bounding box/sphere
  19665. * @param worldMatrix defines the new world matrix
  19666. */
  19667. function BoundingInfo(minimum, maximum, worldMatrix) {
  19668. this._isLocked = false;
  19669. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum, worldMatrix);
  19670. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum, worldMatrix);
  19671. }
  19672. /**
  19673. * Recreates the entire bounding info from scratch as if we call the constructor in place
  19674. * @param min defines the new minimum vector (in local space)
  19675. * @param max defines the new maximum vector (in local space)
  19676. * @param worldMatrix defines the new world matrix
  19677. */
  19678. BoundingInfo.prototype.reConstruct = function (min, max, worldMatrix) {
  19679. this.boundingBox.reConstruct(min, max, worldMatrix);
  19680. this.boundingSphere.reConstruct(min, max, worldMatrix);
  19681. };
  19682. Object.defineProperty(BoundingInfo.prototype, "minimum", {
  19683. /**
  19684. * min vector of the bounding box/sphere
  19685. */
  19686. get: function () {
  19687. return this.boundingBox.minimum;
  19688. },
  19689. enumerable: true,
  19690. configurable: true
  19691. });
  19692. Object.defineProperty(BoundingInfo.prototype, "maximum", {
  19693. /**
  19694. * max vector of the bounding box/sphere
  19695. */
  19696. get: function () {
  19697. return this.boundingBox.maximum;
  19698. },
  19699. enumerable: true,
  19700. configurable: true
  19701. });
  19702. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  19703. /**
  19704. * If the info is locked and won't be updated to avoid perf overhead
  19705. */
  19706. get: function () {
  19707. return this._isLocked;
  19708. },
  19709. set: function (value) {
  19710. this._isLocked = value;
  19711. },
  19712. enumerable: true,
  19713. configurable: true
  19714. });
  19715. // Methods
  19716. /**
  19717. * Updates the bounding sphere and box
  19718. * @param world world matrix to be used to update
  19719. */
  19720. BoundingInfo.prototype.update = function (world) {
  19721. if (this._isLocked) {
  19722. return;
  19723. }
  19724. this.boundingBox._update(world);
  19725. this.boundingSphere._update(world);
  19726. };
  19727. /**
  19728. * Recreate the bounding info to be centered around a specific point given a specific extend.
  19729. * @param center New center of the bounding info
  19730. * @param extend New extend of the bounding info
  19731. * @returns the current bounding info
  19732. */
  19733. BoundingInfo.prototype.centerOn = function (center, extend) {
  19734. var minimum = BoundingInfo.TmpVector3[0].copyFrom(center).subtractInPlace(extend);
  19735. var maximum = BoundingInfo.TmpVector3[1].copyFrom(center).addInPlace(extend);
  19736. this.boundingBox.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix());
  19737. this.boundingSphere.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix());
  19738. return this;
  19739. };
  19740. /**
  19741. * Scale the current bounding info by applying a scale factor
  19742. * @param factor defines the scale factor to apply
  19743. * @returns the current bounding info
  19744. */
  19745. BoundingInfo.prototype.scale = function (factor) {
  19746. this.boundingBox.scale(factor);
  19747. this.boundingSphere.scale(factor);
  19748. return this;
  19749. };
  19750. /**
  19751. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  19752. * @param frustumPlanes defines the frustum to test
  19753. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  19754. * @returns true if the bounding info is in the frustum planes
  19755. */
  19756. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  19757. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  19758. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  19759. return false;
  19760. }
  19761. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  19762. return true;
  19763. }
  19764. return this.boundingBox.isInFrustum(frustumPlanes);
  19765. };
  19766. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  19767. /**
  19768. * Gets the world distance between the min and max points of the bounding box
  19769. */
  19770. get: function () {
  19771. var boundingBox = this.boundingBox;
  19772. var diag = boundingBox.maximumWorld.subtractToRef(boundingBox.minimumWorld, BoundingInfo.TmpVector3[0]);
  19773. return diag.length();
  19774. },
  19775. enumerable: true,
  19776. configurable: true
  19777. });
  19778. /**
  19779. * Checks if a cullable object (mesh...) is in the camera frustum
  19780. * Unlike isInFrustum this cheks the full bounding box
  19781. * @param frustumPlanes Camera near/planes
  19782. * @returns true if the object is in frustum otherwise false
  19783. */
  19784. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19785. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  19786. };
  19787. /** @hidden */
  19788. BoundingInfo.prototype._checkCollision = function (collider) {
  19789. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  19790. };
  19791. /**
  19792. * Checks if a point is inside the bounding box and bounding sphere or the mesh
  19793. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19794. * @param point the point to check intersection with
  19795. * @returns if the point intersects
  19796. */
  19797. BoundingInfo.prototype.intersectsPoint = function (point) {
  19798. if (!this.boundingSphere.centerWorld) {
  19799. return false;
  19800. }
  19801. if (!this.boundingSphere.intersectsPoint(point)) {
  19802. return false;
  19803. }
  19804. if (!this.boundingBox.intersectsPoint(point)) {
  19805. return false;
  19806. }
  19807. return true;
  19808. };
  19809. /**
  19810. * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh
  19811. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19812. * @param boundingInfo the bounding info to check intersection with
  19813. * @param precise if the intersection should be done using OBB
  19814. * @returns if the bounding info intersects
  19815. */
  19816. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  19817. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  19818. return false;
  19819. }
  19820. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  19821. return false;
  19822. }
  19823. if (!precise) {
  19824. return true;
  19825. }
  19826. var box0 = this.boundingBox;
  19827. var box1 = boundingInfo.boundingBox;
  19828. if (!axisOverlap(box0.directions[0], box0, box1)) {
  19829. return false;
  19830. }
  19831. if (!axisOverlap(box0.directions[1], box0, box1)) {
  19832. return false;
  19833. }
  19834. if (!axisOverlap(box0.directions[2], box0, box1)) {
  19835. return false;
  19836. }
  19837. if (!axisOverlap(box1.directions[0], box0, box1)) {
  19838. return false;
  19839. }
  19840. if (!axisOverlap(box1.directions[1], box0, box1)) {
  19841. return false;
  19842. }
  19843. if (!axisOverlap(box1.directions[2], box0, box1)) {
  19844. return false;
  19845. }
  19846. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1)) {
  19847. return false;
  19848. }
  19849. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1)) {
  19850. return false;
  19851. }
  19852. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1)) {
  19853. return false;
  19854. }
  19855. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1)) {
  19856. return false;
  19857. }
  19858. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1)) {
  19859. return false;
  19860. }
  19861. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1)) {
  19862. return false;
  19863. }
  19864. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1)) {
  19865. return false;
  19866. }
  19867. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1)) {
  19868. return false;
  19869. }
  19870. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1)) {
  19871. return false;
  19872. }
  19873. return true;
  19874. };
  19875. BoundingInfo.TmpVector3 = BABYLON.Tools.BuildArray(2, BABYLON.Vector3.Zero);
  19876. return BoundingInfo;
  19877. }());
  19878. BABYLON.BoundingInfo = BoundingInfo;
  19879. })(BABYLON || (BABYLON = {}));
  19880. //# sourceMappingURL=boundingInfo.js.map
  19881. var BABYLON;
  19882. (function (BABYLON) {
  19883. /**
  19884. * A TransformNode is an object that is not rendered but can be used as a center of transformation. This can decrease memory usage and increase rendering speed compared to using an empty mesh as a parent and is less complicated than using a pivot matrix.
  19885. * @see https://doc.babylonjs.com/how_to/transformnode
  19886. */
  19887. var TransformNode = /** @class */ (function (_super) {
  19888. __extends(TransformNode, _super);
  19889. function TransformNode(name, scene, isPure) {
  19890. if (scene === void 0) { scene = null; }
  19891. if (isPure === void 0) { isPure = true; }
  19892. var _this = _super.call(this, name, scene) || this;
  19893. _this._forward = new BABYLON.Vector3(0, 0, 1);
  19894. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  19895. _this._up = new BABYLON.Vector3(0, 1, 0);
  19896. _this._right = new BABYLON.Vector3(1, 0, 0);
  19897. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  19898. // Properties
  19899. _this._position = BABYLON.Vector3.Zero();
  19900. _this._rotation = BABYLON.Vector3.Zero();
  19901. _this._scaling = BABYLON.Vector3.One();
  19902. _this._isDirty = false;
  19903. /**
  19904. * Set the billboard mode. Default is 0.
  19905. *
  19906. * | Value | Type | Description |
  19907. * | --- | --- | --- |
  19908. * | 0 | BILLBOARDMODE_NONE | |
  19909. * | 1 | BILLBOARDMODE_X | |
  19910. * | 2 | BILLBOARDMODE_Y | |
  19911. * | 4 | BILLBOARDMODE_Z | |
  19912. * | 7 | BILLBOARDMODE_ALL | |
  19913. *
  19914. */
  19915. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  19916. /**
  19917. * Multiplication factor on scale x/y/z when computing the world matrix. Eg. for a 1x1x1 cube setting this to 2 will make it a 2x2x2 cube
  19918. */
  19919. _this.scalingDeterminant = 1;
  19920. /**
  19921. * Sets the distance of the object to max, often used by skybox
  19922. */
  19923. _this.infiniteDistance = false;
  19924. /**
  19925. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  19926. * By default the system will update normals to compensate
  19927. */
  19928. _this.ignoreNonUniformScaling = false;
  19929. _this._localWorld = BABYLON.Matrix.Zero();
  19930. _this._absolutePosition = BABYLON.Vector3.Zero();
  19931. _this._pivotMatrix = BABYLON.Matrix.Identity();
  19932. _this._postMultiplyPivotMatrix = false;
  19933. _this._isWorldMatrixFrozen = false;
  19934. /** @hidden */
  19935. _this._indexInSceneTransformNodesArray = -1;
  19936. /**
  19937. * An event triggered after the world matrix is updated
  19938. */
  19939. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  19940. _this._nonUniformScaling = false;
  19941. if (isPure) {
  19942. _this.getScene().addTransformNode(_this);
  19943. }
  19944. return _this;
  19945. }
  19946. /**
  19947. * Gets a string identifying the name of the class
  19948. * @returns "TransformNode" string
  19949. */
  19950. TransformNode.prototype.getClassName = function () {
  19951. return "TransformNode";
  19952. };
  19953. Object.defineProperty(TransformNode.prototype, "position", {
  19954. /**
  19955. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  19956. */
  19957. get: function () {
  19958. return this._position;
  19959. },
  19960. set: function (newPosition) {
  19961. this._position = newPosition;
  19962. this._isDirty = true;
  19963. },
  19964. enumerable: true,
  19965. configurable: true
  19966. });
  19967. Object.defineProperty(TransformNode.prototype, "rotation", {
  19968. /**
  19969. * 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)).
  19970. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  19971. */
  19972. get: function () {
  19973. return this._rotation;
  19974. },
  19975. set: function (newRotation) {
  19976. this._rotation = newRotation;
  19977. this._isDirty = true;
  19978. },
  19979. enumerable: true,
  19980. configurable: true
  19981. });
  19982. Object.defineProperty(TransformNode.prototype, "scaling", {
  19983. /**
  19984. * 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)).
  19985. */
  19986. get: function () {
  19987. return this._scaling;
  19988. },
  19989. set: function (newScaling) {
  19990. this._scaling = newScaling;
  19991. this._isDirty = true;
  19992. },
  19993. enumerable: true,
  19994. configurable: true
  19995. });
  19996. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  19997. /**
  19998. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  19999. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  20000. */
  20001. get: function () {
  20002. return this._rotationQuaternion;
  20003. },
  20004. set: function (quaternion) {
  20005. this._rotationQuaternion = quaternion;
  20006. //reset the rotation vector.
  20007. if (quaternion) {
  20008. this.rotation.setAll(0.0);
  20009. }
  20010. },
  20011. enumerable: true,
  20012. configurable: true
  20013. });
  20014. Object.defineProperty(TransformNode.prototype, "forward", {
  20015. /**
  20016. * The forward direction of that transform in world space.
  20017. */
  20018. get: function () {
  20019. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  20020. },
  20021. enumerable: true,
  20022. configurable: true
  20023. });
  20024. Object.defineProperty(TransformNode.prototype, "up", {
  20025. /**
  20026. * The up direction of that transform in world space.
  20027. */
  20028. get: function () {
  20029. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  20030. },
  20031. enumerable: true,
  20032. configurable: true
  20033. });
  20034. Object.defineProperty(TransformNode.prototype, "right", {
  20035. /**
  20036. * The right direction of that transform in world space.
  20037. */
  20038. get: function () {
  20039. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  20040. },
  20041. enumerable: true,
  20042. configurable: true
  20043. });
  20044. /**
  20045. * Copies the parameter passed Matrix into the mesh Pose matrix.
  20046. * @param matrix the matrix to copy the pose from
  20047. * @returns this TransformNode.
  20048. */
  20049. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  20050. this._poseMatrix.copyFrom(matrix);
  20051. return this;
  20052. };
  20053. /**
  20054. * Returns the mesh Pose matrix.
  20055. * @returns the pose matrix
  20056. */
  20057. TransformNode.prototype.getPoseMatrix = function () {
  20058. return this._poseMatrix;
  20059. };
  20060. /** @hidden */
  20061. TransformNode.prototype._isSynchronized = function () {
  20062. if (this._isDirty) {
  20063. return false;
  20064. }
  20065. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  20066. return false;
  20067. }
  20068. if (this._cache.pivotMatrixUpdated) {
  20069. return false;
  20070. }
  20071. if (this.infiniteDistance) {
  20072. return false;
  20073. }
  20074. if (!this._cache.position.equals(this._position)) {
  20075. return false;
  20076. }
  20077. if (this._rotationQuaternion) {
  20078. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion)) {
  20079. return false;
  20080. }
  20081. }
  20082. if (!this._cache.rotation.equals(this._rotation)) {
  20083. return false;
  20084. }
  20085. if (!this._cache.scaling.equals(this._scaling)) {
  20086. return false;
  20087. }
  20088. return true;
  20089. };
  20090. /** @hidden */
  20091. TransformNode.prototype._initCache = function () {
  20092. _super.prototype._initCache.call(this);
  20093. this._cache.localMatrixUpdated = false;
  20094. this._cache.position = BABYLON.Vector3.Zero();
  20095. this._cache.scaling = BABYLON.Vector3.Zero();
  20096. this._cache.rotation = BABYLON.Vector3.Zero();
  20097. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  20098. this._cache.billboardMode = -1;
  20099. };
  20100. /**
  20101. * Flag the transform node as dirty (Forcing it to update everything)
  20102. * @param property if set to "rotation" the objects rotationQuaternion will be set to null
  20103. * @returns this transform node
  20104. */
  20105. TransformNode.prototype.markAsDirty = function (property) {
  20106. if (property === "rotation") {
  20107. this.rotationQuaternion = null;
  20108. }
  20109. this._currentRenderId = Number.MAX_VALUE;
  20110. this._isDirty = true;
  20111. return this;
  20112. };
  20113. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  20114. /**
  20115. * Returns the current mesh absolute position.
  20116. * Returns a Vector3.
  20117. */
  20118. get: function () {
  20119. return this._absolutePosition;
  20120. },
  20121. enumerable: true,
  20122. configurable: true
  20123. });
  20124. /**
  20125. * Sets a new matrix to apply before all other transformation
  20126. * @param matrix defines the transform matrix
  20127. * @returns the current TransformNode
  20128. */
  20129. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  20130. return this.setPivotMatrix(matrix, false);
  20131. };
  20132. /**
  20133. * Sets a new pivot matrix to the current node
  20134. * @param matrix defines the new pivot matrix to use
  20135. * @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
  20136. * @returns the current TransformNode
  20137. */
  20138. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  20139. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  20140. this._pivotMatrix.copyFrom(matrix);
  20141. this._cache.pivotMatrixUpdated = true;
  20142. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  20143. if (this._postMultiplyPivotMatrix) {
  20144. if (!this._pivotMatrixInverse) {
  20145. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  20146. }
  20147. else {
  20148. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  20149. }
  20150. }
  20151. return this;
  20152. };
  20153. /**
  20154. * Returns the mesh pivot matrix.
  20155. * Default : Identity.
  20156. * @returns the matrix
  20157. */
  20158. TransformNode.prototype.getPivotMatrix = function () {
  20159. return this._pivotMatrix;
  20160. };
  20161. /**
  20162. * Prevents the World matrix to be computed any longer.
  20163. * @returns the TransformNode.
  20164. */
  20165. TransformNode.prototype.freezeWorldMatrix = function () {
  20166. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  20167. this.computeWorldMatrix(true);
  20168. this._isWorldMatrixFrozen = true;
  20169. return this;
  20170. };
  20171. /**
  20172. * Allows back the World matrix computation.
  20173. * @returns the TransformNode.
  20174. */
  20175. TransformNode.prototype.unfreezeWorldMatrix = function () {
  20176. this._isWorldMatrixFrozen = false;
  20177. this.computeWorldMatrix(true);
  20178. return this;
  20179. };
  20180. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  20181. /**
  20182. * True if the World matrix has been frozen.
  20183. */
  20184. get: function () {
  20185. return this._isWorldMatrixFrozen;
  20186. },
  20187. enumerable: true,
  20188. configurable: true
  20189. });
  20190. /**
  20191. * Retuns the mesh absolute position in the World.
  20192. * @returns a Vector3.
  20193. */
  20194. TransformNode.prototype.getAbsolutePosition = function () {
  20195. this.computeWorldMatrix();
  20196. return this._absolutePosition;
  20197. };
  20198. /**
  20199. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  20200. * @param absolutePosition the absolute position to set
  20201. * @returns the TransformNode.
  20202. */
  20203. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  20204. if (!absolutePosition) {
  20205. return this;
  20206. }
  20207. var absolutePositionX;
  20208. var absolutePositionY;
  20209. var absolutePositionZ;
  20210. if (absolutePosition.x === undefined) {
  20211. if (arguments.length < 3) {
  20212. return this;
  20213. }
  20214. absolutePositionX = arguments[0];
  20215. absolutePositionY = arguments[1];
  20216. absolutePositionZ = arguments[2];
  20217. }
  20218. else {
  20219. absolutePositionX = absolutePosition.x;
  20220. absolutePositionY = absolutePosition.y;
  20221. absolutePositionZ = absolutePosition.z;
  20222. }
  20223. if (this.parent) {
  20224. var invertParentWorldMatrix = BABYLON.Tmp.Matrix[0];
  20225. this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix);
  20226. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(absolutePositionX, absolutePositionY, absolutePositionZ, invertParentWorldMatrix, this.position);
  20227. }
  20228. else {
  20229. this.position.x = absolutePositionX;
  20230. this.position.y = absolutePositionY;
  20231. this.position.z = absolutePositionZ;
  20232. }
  20233. return this;
  20234. };
  20235. /**
  20236. * Sets the mesh position in its local space.
  20237. * @param vector3 the position to set in localspace
  20238. * @returns the TransformNode.
  20239. */
  20240. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  20241. this.computeWorldMatrix();
  20242. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  20243. return this;
  20244. };
  20245. /**
  20246. * Returns the mesh position in the local space from the current World matrix values.
  20247. * @returns a new Vector3.
  20248. */
  20249. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  20250. this.computeWorldMatrix();
  20251. var invLocalWorldMatrix = BABYLON.Tmp.Matrix[0];
  20252. this._localWorld.invertToRef(invLocalWorldMatrix);
  20253. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  20254. };
  20255. /**
  20256. * Translates the mesh along the passed Vector3 in its local space.
  20257. * @param vector3 the distance to translate in localspace
  20258. * @returns the TransformNode.
  20259. */
  20260. TransformNode.prototype.locallyTranslate = function (vector3) {
  20261. this.computeWorldMatrix(true);
  20262. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  20263. return this;
  20264. };
  20265. /**
  20266. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  20267. * @param targetPoint the position (must be in same space as current mesh) to look at
  20268. * @param yawCor optional yaw (y-axis) correction in radians
  20269. * @param pitchCor optional pitch (x-axis) correction in radians
  20270. * @param rollCor optional roll (z-axis) correction in radians
  20271. * @param space the choosen space of the target
  20272. * @returns the TransformNode.
  20273. */
  20274. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  20275. if (yawCor === void 0) { yawCor = 0; }
  20276. if (pitchCor === void 0) { pitchCor = 0; }
  20277. if (rollCor === void 0) { rollCor = 0; }
  20278. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  20279. var dv = TransformNode._lookAtVectorCache;
  20280. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  20281. targetPoint.subtractToRef(pos, dv);
  20282. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  20283. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  20284. var pitch = Math.atan2(dv.y, len);
  20285. if (this.rotationQuaternion) {
  20286. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  20287. }
  20288. else {
  20289. this.rotation.x = pitch + pitchCor;
  20290. this.rotation.y = yaw + yawCor;
  20291. this.rotation.z = rollCor;
  20292. }
  20293. return this;
  20294. };
  20295. /**
  20296. * Returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  20297. * This Vector3 is expressed in the World space.
  20298. * @param localAxis axis to rotate
  20299. * @returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  20300. */
  20301. TransformNode.prototype.getDirection = function (localAxis) {
  20302. var result = BABYLON.Vector3.Zero();
  20303. this.getDirectionToRef(localAxis, result);
  20304. return result;
  20305. };
  20306. /**
  20307. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  20308. * localAxis is expressed in the mesh local space.
  20309. * result is computed in the Wordl space from the mesh World matrix.
  20310. * @param localAxis axis to rotate
  20311. * @param result the resulting transformnode
  20312. * @returns this TransformNode.
  20313. */
  20314. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  20315. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20316. return this;
  20317. };
  20318. /**
  20319. * Sets a new pivot point to the current node
  20320. * @param point defines the new pivot point to use
  20321. * @param space defines if the point is in world or local space (local by default)
  20322. * @returns the current TransformNode
  20323. */
  20324. TransformNode.prototype.setPivotPoint = function (point, space) {
  20325. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  20326. if (this.getScene().getRenderId() == 0) {
  20327. this.computeWorldMatrix(true);
  20328. }
  20329. var wm = this.getWorldMatrix();
  20330. if (space == BABYLON.Space.WORLD) {
  20331. var tmat = BABYLON.Tmp.Matrix[0];
  20332. wm.invertToRef(tmat);
  20333. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  20334. }
  20335. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  20336. };
  20337. /**
  20338. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  20339. * @returns the pivot point
  20340. */
  20341. TransformNode.prototype.getPivotPoint = function () {
  20342. var point = BABYLON.Vector3.Zero();
  20343. this.getPivotPointToRef(point);
  20344. return point;
  20345. };
  20346. /**
  20347. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  20348. * @param result the vector3 to store the result
  20349. * @returns this TransformNode.
  20350. */
  20351. TransformNode.prototype.getPivotPointToRef = function (result) {
  20352. result.x = -this._pivotMatrix.m[12];
  20353. result.y = -this._pivotMatrix.m[13];
  20354. result.z = -this._pivotMatrix.m[14];
  20355. return this;
  20356. };
  20357. /**
  20358. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  20359. * @returns a new Vector3 set with the mesh pivot point World coordinates.
  20360. */
  20361. TransformNode.prototype.getAbsolutePivotPoint = function () {
  20362. var point = BABYLON.Vector3.Zero();
  20363. this.getAbsolutePivotPointToRef(point);
  20364. return point;
  20365. };
  20366. /**
  20367. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  20368. * @param result vector3 to store the result
  20369. * @returns this TransformNode.
  20370. */
  20371. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  20372. result.x = this._pivotMatrix.m[12];
  20373. result.y = this._pivotMatrix.m[13];
  20374. result.z = this._pivotMatrix.m[14];
  20375. this.getPivotPointToRef(result);
  20376. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  20377. return this;
  20378. };
  20379. /**
  20380. * Defines the passed node as the parent of the current node.
  20381. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  20382. * @param node the node ot set as the parent
  20383. * @returns this TransformNode.
  20384. */
  20385. TransformNode.prototype.setParent = function (node) {
  20386. if (!node && !this.parent) {
  20387. return this;
  20388. }
  20389. var quatRotation = BABYLON.Tmp.Quaternion[0];
  20390. var position = BABYLON.Tmp.Vector3[0];
  20391. var scale = BABYLON.Tmp.Vector3[1];
  20392. if (!node) {
  20393. if (this.parent && this.parent.computeWorldMatrix) {
  20394. this.parent.computeWorldMatrix(true);
  20395. }
  20396. this.computeWorldMatrix(true);
  20397. this.getWorldMatrix().decompose(scale, quatRotation, position);
  20398. }
  20399. else {
  20400. var diffMatrix = BABYLON.Tmp.Matrix[0];
  20401. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  20402. this.computeWorldMatrix(true);
  20403. node.computeWorldMatrix(true);
  20404. node.getWorldMatrix().invertToRef(invParentMatrix);
  20405. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  20406. diffMatrix.decompose(scale, quatRotation, position);
  20407. }
  20408. if (this.rotationQuaternion) {
  20409. this.rotationQuaternion.copyFrom(quatRotation);
  20410. }
  20411. else {
  20412. quatRotation.toEulerAnglesToRef(this.rotation);
  20413. }
  20414. this.scaling.copyFrom(scale);
  20415. this.position.copyFrom(position);
  20416. this.parent = node;
  20417. return this;
  20418. };
  20419. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  20420. /**
  20421. * True if the scaling property of this object is non uniform eg. (1,2,1)
  20422. */
  20423. get: function () {
  20424. return this._nonUniformScaling;
  20425. },
  20426. enumerable: true,
  20427. configurable: true
  20428. });
  20429. /** @hidden */
  20430. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  20431. if (this._nonUniformScaling === value) {
  20432. return false;
  20433. }
  20434. this._nonUniformScaling = value;
  20435. return true;
  20436. };
  20437. /**
  20438. * Attach the current TransformNode to another TransformNode associated with a bone
  20439. * @param bone Bone affecting the TransformNode
  20440. * @param affectedTransformNode TransformNode associated with the bone
  20441. * @returns this object
  20442. */
  20443. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  20444. this._transformToBoneReferal = affectedTransformNode;
  20445. this.parent = bone;
  20446. if (bone.getWorldMatrix().determinant() < 0) {
  20447. this.scalingDeterminant *= -1;
  20448. }
  20449. return this;
  20450. };
  20451. /**
  20452. * Detach the transform node if its associated with a bone
  20453. * @returns this object
  20454. */
  20455. TransformNode.prototype.detachFromBone = function () {
  20456. if (!this.parent) {
  20457. return this;
  20458. }
  20459. if (this.parent.getWorldMatrix().determinant() < 0) {
  20460. this.scalingDeterminant *= -1;
  20461. }
  20462. this._transformToBoneReferal = null;
  20463. this.parent = null;
  20464. return this;
  20465. };
  20466. /**
  20467. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  20468. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20469. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20470. * The passed axis is also normalized.
  20471. * @param axis the axis to rotate around
  20472. * @param amount the amount to rotate in radians
  20473. * @param space Space to rotate in (Default: local)
  20474. * @returns the TransformNode.
  20475. */
  20476. TransformNode.prototype.rotate = function (axis, amount, space) {
  20477. axis.normalize();
  20478. if (!this.rotationQuaternion) {
  20479. this.rotationQuaternion = this.rotation.toQuaternion();
  20480. this.rotation.setAll(0);
  20481. }
  20482. var rotationQuaternion;
  20483. if (!space || space === BABYLON.Space.LOCAL) {
  20484. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20485. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  20486. }
  20487. else {
  20488. if (this.parent) {
  20489. var invertParentWorldMatrix = BABYLON.Tmp.Matrix[0];
  20490. this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix);
  20491. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  20492. }
  20493. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20494. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20495. }
  20496. return this;
  20497. };
  20498. /**
  20499. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  20500. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20501. * The passed axis is also normalized. .
  20502. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  20503. * @param point the point to rotate around
  20504. * @param axis the axis to rotate around
  20505. * @param amount the amount to rotate in radians
  20506. * @returns the TransformNode
  20507. */
  20508. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  20509. axis.normalize();
  20510. if (!this.rotationQuaternion) {
  20511. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20512. this.rotation.setAll(0);
  20513. }
  20514. var tmpVector = BABYLON.Tmp.Vector3[0];
  20515. var finalScale = BABYLON.Tmp.Vector3[1];
  20516. var finalTranslation = BABYLON.Tmp.Vector3[2];
  20517. var finalRotation = BABYLON.Tmp.Quaternion[0];
  20518. var translationMatrix = BABYLON.Tmp.Matrix[0]; // T
  20519. var translationMatrixInv = BABYLON.Tmp.Matrix[1]; // T'
  20520. var rotationMatrix = BABYLON.Tmp.Matrix[2]; // R
  20521. var finalMatrix = BABYLON.Tmp.Matrix[3]; // T' x R x T
  20522. point.subtractToRef(this.position, tmpVector);
  20523. BABYLON.Matrix.TranslationToRef(tmpVector.x, tmpVector.y, tmpVector.z, translationMatrix); // T
  20524. BABYLON.Matrix.TranslationToRef(-tmpVector.x, -tmpVector.y, -tmpVector.z, translationMatrixInv); // T'
  20525. BABYLON.Matrix.RotationAxisToRef(axis, amount, rotationMatrix); // R
  20526. translationMatrixInv.multiplyToRef(rotationMatrix, finalMatrix); // T' x R
  20527. finalMatrix.multiplyToRef(translationMatrix, finalMatrix); // T' x R x T
  20528. finalMatrix.decompose(finalScale, finalRotation, finalTranslation);
  20529. this.position.addInPlace(finalTranslation);
  20530. finalRotation.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20531. return this;
  20532. };
  20533. /**
  20534. * Translates the mesh along the axis vector for the passed distance in the given space.
  20535. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20536. * @param axis the axis to translate in
  20537. * @param distance the distance to translate
  20538. * @param space Space to rotate in (Default: local)
  20539. * @returns the TransformNode.
  20540. */
  20541. TransformNode.prototype.translate = function (axis, distance, space) {
  20542. var displacementVector = axis.scale(distance);
  20543. if (!space || space === BABYLON.Space.LOCAL) {
  20544. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  20545. this.setPositionWithLocalVector(tempV3);
  20546. }
  20547. else {
  20548. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  20549. }
  20550. return this;
  20551. };
  20552. /**
  20553. * Adds a rotation step to the mesh current rotation.
  20554. * x, y, z are Euler angles expressed in radians.
  20555. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  20556. * This means this rotation is made in the mesh local space only.
  20557. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  20558. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  20559. * ```javascript
  20560. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  20561. * ```
  20562. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  20563. * 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.
  20564. * @param x Rotation to add
  20565. * @param y Rotation to add
  20566. * @param z Rotation to add
  20567. * @returns the TransformNode.
  20568. */
  20569. TransformNode.prototype.addRotation = function (x, y, z) {
  20570. var rotationQuaternion;
  20571. if (this.rotationQuaternion) {
  20572. rotationQuaternion = this.rotationQuaternion;
  20573. }
  20574. else {
  20575. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  20576. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  20577. }
  20578. var accumulation = BABYLON.Tmp.Quaternion[0];
  20579. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  20580. rotationQuaternion.multiplyInPlace(accumulation);
  20581. if (!this.rotationQuaternion) {
  20582. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  20583. }
  20584. return this;
  20585. };
  20586. /**
  20587. * Computes the world matrix of the node
  20588. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  20589. * @returns the world matrix
  20590. */
  20591. TransformNode.prototype.computeWorldMatrix = function (force) {
  20592. if (this._isWorldMatrixFrozen) {
  20593. return this._worldMatrix;
  20594. }
  20595. if (!force && this.isSynchronized()) {
  20596. this._currentRenderId = this.getScene().getRenderId();
  20597. return this._worldMatrix;
  20598. }
  20599. this._updateCache();
  20600. this._cache.position.copyFrom(this.position);
  20601. this._cache.scaling.copyFrom(this.scaling);
  20602. this._cache.pivotMatrixUpdated = false;
  20603. this._cache.billboardMode = this.billboardMode;
  20604. this._currentRenderId = this.getScene().getRenderId();
  20605. this._childRenderId = this.getScene().getRenderId();
  20606. this._isDirty = false;
  20607. // Scaling
  20608. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  20609. // Rotation
  20610. //rotate, if quaternion is set and rotation was used
  20611. if (this.rotationQuaternion) {
  20612. var len = this.rotation.length();
  20613. if (len) {
  20614. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  20615. this.rotation.copyFromFloats(0, 0, 0);
  20616. }
  20617. }
  20618. if (this.rotationQuaternion) {
  20619. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  20620. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  20621. }
  20622. else {
  20623. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  20624. this._cache.rotation.copyFrom(this.rotation);
  20625. }
  20626. // Translation
  20627. var camera = this.getScene().activeCamera;
  20628. if (this.infiniteDistance && !this.parent && camera) {
  20629. var cameraWorldMatrix = camera.getWorldMatrix();
  20630. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  20631. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  20632. }
  20633. else {
  20634. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  20635. }
  20636. // Composing transformations
  20637. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  20638. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20639. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  20640. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  20641. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  20642. // Need to decompose each rotation here
  20643. var currentPosition = BABYLON.Tmp.Vector3[3];
  20644. if (this.parent && this.parent.getWorldMatrix) {
  20645. if (this._transformToBoneReferal) {
  20646. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20647. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  20648. }
  20649. else {
  20650. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  20651. }
  20652. }
  20653. else {
  20654. currentPosition.copyFrom(this.position);
  20655. }
  20656. currentPosition.subtractInPlace(camera.globalPosition);
  20657. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  20658. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  20659. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  20660. }
  20661. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  20662. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  20663. }
  20664. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  20665. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  20666. }
  20667. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  20668. }
  20669. else {
  20670. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  20671. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  20672. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  20673. }
  20674. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  20675. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20676. }
  20677. // Post multiply inverse of pivotMatrix
  20678. if (this._postMultiplyPivotMatrix) {
  20679. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  20680. }
  20681. // Local world
  20682. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  20683. // Parent
  20684. if (this.parent && this.parent.getWorldMatrix) {
  20685. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  20686. if (this._transformToBoneReferal) {
  20687. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20688. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  20689. }
  20690. else {
  20691. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  20692. }
  20693. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  20694. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  20695. this._worldMatrix.copyFrom(this._localWorld);
  20696. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  20697. }
  20698. else {
  20699. if (this._transformToBoneReferal) {
  20700. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20701. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  20702. }
  20703. else {
  20704. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  20705. }
  20706. }
  20707. this._markSyncedWithParent();
  20708. }
  20709. else {
  20710. this._worldMatrix.copyFrom(this._localWorld);
  20711. }
  20712. // Normal matrix
  20713. if (!this.ignoreNonUniformScaling) {
  20714. if (this.scaling.isNonUniform) {
  20715. this._updateNonUniformScalingState(true);
  20716. }
  20717. else if (this.parent && this.parent._nonUniformScaling) {
  20718. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  20719. }
  20720. else {
  20721. this._updateNonUniformScalingState(false);
  20722. }
  20723. }
  20724. else {
  20725. this._updateNonUniformScalingState(false);
  20726. }
  20727. this._afterComputeWorldMatrix();
  20728. // Absolute position
  20729. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  20730. // Callbacks
  20731. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  20732. if (!this._poseMatrix) {
  20733. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  20734. }
  20735. // Cache the determinant
  20736. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  20737. return this._worldMatrix;
  20738. };
  20739. TransformNode.prototype._afterComputeWorldMatrix = function () {
  20740. };
  20741. /**
  20742. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  20743. * @param func callback function to add
  20744. *
  20745. * @returns the TransformNode.
  20746. */
  20747. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  20748. this.onAfterWorldMatrixUpdateObservable.add(func);
  20749. return this;
  20750. };
  20751. /**
  20752. * Removes a registered callback function.
  20753. * @param func callback function to remove
  20754. * @returns the TransformNode.
  20755. */
  20756. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  20757. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  20758. return this;
  20759. };
  20760. /**
  20761. * Clone the current transform node
  20762. * @param name Name of the new clone
  20763. * @param newParent New parent for the clone
  20764. * @param doNotCloneChildren Do not clone children hierarchy
  20765. * @returns the new transform node
  20766. */
  20767. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20768. var _this = this;
  20769. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  20770. result.name = name;
  20771. result.id = name;
  20772. if (newParent) {
  20773. result.parent = newParent;
  20774. }
  20775. if (!doNotCloneChildren) {
  20776. // Children
  20777. var directDescendants = this.getDescendants(true);
  20778. for (var index = 0; index < directDescendants.length; index++) {
  20779. var child = directDescendants[index];
  20780. if (child.clone) {
  20781. child.clone(name + "." + child.name, result);
  20782. }
  20783. }
  20784. }
  20785. return result;
  20786. };
  20787. /**
  20788. * Serializes the objects information.
  20789. * @param currentSerializationObject defines the object to serialize in
  20790. * @returns the serialized object
  20791. */
  20792. TransformNode.prototype.serialize = function (currentSerializationObject) {
  20793. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  20794. serializationObject.type = this.getClassName();
  20795. // Parent
  20796. if (this.parent) {
  20797. serializationObject.parentId = this.parent.id;
  20798. }
  20799. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  20800. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20801. }
  20802. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20803. serializationObject.isEnabled = this.isEnabled();
  20804. // Parent
  20805. if (this.parent) {
  20806. serializationObject.parentId = this.parent.id;
  20807. }
  20808. return serializationObject;
  20809. };
  20810. // Statics
  20811. /**
  20812. * Returns a new TransformNode object parsed from the source provided.
  20813. * @param parsedTransformNode is the source.
  20814. * @param scene the scne the object belongs to
  20815. * @param rootUrl is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20816. * @returns a new TransformNode object parsed from the source provided.
  20817. */
  20818. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  20819. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  20820. if (BABYLON.Tags) {
  20821. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  20822. }
  20823. if (parsedTransformNode.localMatrix) {
  20824. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  20825. }
  20826. else if (parsedTransformNode.pivotMatrix) {
  20827. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  20828. }
  20829. transformNode.setEnabled(parsedTransformNode.isEnabled);
  20830. // Parent
  20831. if (parsedTransformNode.parentId) {
  20832. transformNode._waitingParentId = parsedTransformNode.parentId;
  20833. }
  20834. return transformNode;
  20835. };
  20836. /**
  20837. * Releases resources associated with this transform node.
  20838. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20839. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20840. */
  20841. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20842. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20843. // Animations
  20844. this.getScene().stopAnimation(this);
  20845. // Remove from scene
  20846. this.getScene().removeTransformNode(this);
  20847. this.onAfterWorldMatrixUpdateObservable.clear();
  20848. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20849. };
  20850. // Statics
  20851. /**
  20852. * Object will not rotate to face the camera
  20853. */
  20854. TransformNode.BILLBOARDMODE_NONE = 0;
  20855. /**
  20856. * Object will rotate to face the camera but only on the x axis
  20857. */
  20858. TransformNode.BILLBOARDMODE_X = 1;
  20859. /**
  20860. * Object will rotate to face the camera but only on the y axis
  20861. */
  20862. TransformNode.BILLBOARDMODE_Y = 2;
  20863. /**
  20864. * Object will rotate to face the camera but only on the z axis
  20865. */
  20866. TransformNode.BILLBOARDMODE_Z = 4;
  20867. /**
  20868. * Object will rotate to face the camera
  20869. */
  20870. TransformNode.BILLBOARDMODE_ALL = 7;
  20871. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  20872. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  20873. __decorate([
  20874. BABYLON.serializeAsVector3("position")
  20875. ], TransformNode.prototype, "_position", void 0);
  20876. __decorate([
  20877. BABYLON.serializeAsVector3("rotation")
  20878. ], TransformNode.prototype, "_rotation", void 0);
  20879. __decorate([
  20880. BABYLON.serializeAsQuaternion("rotationQuaternion")
  20881. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  20882. __decorate([
  20883. BABYLON.serializeAsVector3("scaling")
  20884. ], TransformNode.prototype, "_scaling", void 0);
  20885. __decorate([
  20886. BABYLON.serialize()
  20887. ], TransformNode.prototype, "billboardMode", void 0);
  20888. __decorate([
  20889. BABYLON.serialize()
  20890. ], TransformNode.prototype, "scalingDeterminant", void 0);
  20891. __decorate([
  20892. BABYLON.serialize()
  20893. ], TransformNode.prototype, "infiniteDistance", void 0);
  20894. __decorate([
  20895. BABYLON.serialize()
  20896. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  20897. return TransformNode;
  20898. }(BABYLON.Node));
  20899. BABYLON.TransformNode = TransformNode;
  20900. })(BABYLON || (BABYLON = {}));
  20901. //# sourceMappingURL=transformNode.js.map
  20902. var BABYLON;
  20903. (function (BABYLON) {
  20904. /** @hidden */
  20905. var _FacetDataStorage = /** @class */ (function () {
  20906. function _FacetDataStorage() {
  20907. this.facetNb = 0; // facet number
  20908. this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  20909. this.partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  20910. this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  20911. this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  20912. this.bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  20913. this.subDiv = {
  20914. max: 1,
  20915. X: 1,
  20916. Y: 1,
  20917. Z: 1
  20918. };
  20919. this.facetDepthSort = false; // is the facet depth sort to be computed
  20920. this.facetDepthSortEnabled = false; // is the facet depth sort initialized
  20921. }
  20922. return _FacetDataStorage;
  20923. }());
  20924. /**
  20925. * Class used to store all common mesh properties
  20926. */
  20927. var AbstractMesh = /** @class */ (function (_super) {
  20928. __extends(AbstractMesh, _super);
  20929. // Constructor
  20930. /**
  20931. * Creates a new AbstractMesh
  20932. * @param name defines the name of the mesh
  20933. * @param scene defines the hosting scene
  20934. */
  20935. function AbstractMesh(name, scene) {
  20936. if (scene === void 0) { scene = null; }
  20937. var _this = _super.call(this, name, scene, false) || this;
  20938. _this._facetData = new _FacetDataStorage();
  20939. /** Gets ot sets the culling strategy to use to find visible meshes */
  20940. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  20941. // Events
  20942. /**
  20943. * An event triggered when this mesh collides with another one
  20944. */
  20945. _this.onCollideObservable = new BABYLON.Observable();
  20946. /**
  20947. * An event triggered when the collision's position changes
  20948. */
  20949. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  20950. /**
  20951. * An event triggered when material is changed
  20952. */
  20953. _this.onMaterialChangedObservable = new BABYLON.Observable();
  20954. // Properties
  20955. /**
  20956. * Gets or sets the orientation for POV movement & rotation
  20957. */
  20958. _this.definedFacingForward = true;
  20959. _this._visibility = 1.0;
  20960. /** Gets or sets the alpha index used to sort transparent meshes
  20961. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  20962. */
  20963. _this.alphaIndex = Number.MAX_VALUE;
  20964. /**
  20965. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  20966. */
  20967. _this.isVisible = true;
  20968. /**
  20969. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  20970. */
  20971. _this.isPickable = true;
  20972. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  20973. _this.showSubMeshesBoundingBox = false;
  20974. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  20975. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  20976. */
  20977. _this.isBlocker = false;
  20978. /**
  20979. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  20980. */
  20981. _this.enablePointerMoveEvents = false;
  20982. /**
  20983. * Specifies the rendering group id for this mesh (0 by default)
  20984. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  20985. */
  20986. _this.renderingGroupId = 0;
  20987. _this._receiveShadows = false;
  20988. /** Defines color to use when rendering outline */
  20989. _this.outlineColor = BABYLON.Color3.Red();
  20990. /** Define width to use when rendering outline */
  20991. _this.outlineWidth = 0.02;
  20992. /** Defines color to use when rendering overlay */
  20993. _this.overlayColor = BABYLON.Color3.Red();
  20994. /** Defines alpha to use when rendering overlay */
  20995. _this.overlayAlpha = 0.5;
  20996. _this._hasVertexAlpha = false;
  20997. _this._useVertexColors = true;
  20998. _this._computeBonesUsingShaders = true;
  20999. _this._numBoneInfluencers = 4;
  21000. _this._applyFog = true;
  21001. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  21002. _this.useOctreeForRenderingSelection = true;
  21003. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  21004. _this.useOctreeForPicking = true;
  21005. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  21006. _this.useOctreeForCollisions = true;
  21007. _this._layerMask = 0x0FFFFFFF;
  21008. /**
  21009. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  21010. */
  21011. _this.alwaysSelectAsActiveMesh = false;
  21012. /**
  21013. * Gets or sets the current action manager
  21014. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  21015. */
  21016. _this.actionManager = null;
  21017. // Collisions
  21018. _this._checkCollisions = false;
  21019. _this._collisionMask = -1;
  21020. _this._collisionGroup = -1;
  21021. /**
  21022. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  21023. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21024. */
  21025. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  21026. /**
  21027. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  21028. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21029. */
  21030. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  21031. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  21032. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  21033. // Edges
  21034. /**
  21035. * Defines edge width used when edgesRenderer is enabled
  21036. * @see https://www.babylonjs-playground.com/#10OJSG#13
  21037. */
  21038. _this.edgesWidth = 1;
  21039. /**
  21040. * Defines edge color used when edgesRenderer is enabled
  21041. * @see https://www.babylonjs-playground.com/#10OJSG#13
  21042. */
  21043. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  21044. /** @hidden */
  21045. _this._renderId = 0;
  21046. /** @hidden */
  21047. _this._intersectionsInProgress = new Array();
  21048. /** @hidden */
  21049. _this._unIndexed = false;
  21050. /** @hidden */
  21051. _this._lightSources = new Array();
  21052. /**
  21053. * An event triggered when the mesh is rebuilt.
  21054. */
  21055. _this.onRebuildObservable = new BABYLON.Observable();
  21056. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  21057. if (collidedMesh === void 0) { collidedMesh = null; }
  21058. //TODO move this to the collision coordinator!
  21059. if (_this.getScene().workerCollisions) {
  21060. newPosition.multiplyInPlace(_this._collider._radius);
  21061. }
  21062. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  21063. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  21064. _this.position.addInPlace(_this._diffPositionForCollisions);
  21065. }
  21066. if (collidedMesh) {
  21067. _this.onCollideObservable.notifyObservers(collidedMesh);
  21068. }
  21069. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  21070. };
  21071. _this.getScene().addMesh(_this);
  21072. _this._resyncLightSources();
  21073. return _this;
  21074. }
  21075. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  21076. /**
  21077. * No billboard
  21078. */
  21079. get: function () {
  21080. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  21081. },
  21082. enumerable: true,
  21083. configurable: true
  21084. });
  21085. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  21086. /** Billboard on X axis */
  21087. get: function () {
  21088. return BABYLON.TransformNode.BILLBOARDMODE_X;
  21089. },
  21090. enumerable: true,
  21091. configurable: true
  21092. });
  21093. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  21094. /** Billboard on Y axis */
  21095. get: function () {
  21096. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  21097. },
  21098. enumerable: true,
  21099. configurable: true
  21100. });
  21101. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  21102. /** Billboard on Z axis */
  21103. get: function () {
  21104. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  21105. },
  21106. enumerable: true,
  21107. configurable: true
  21108. });
  21109. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  21110. /** Billboard on all axes */
  21111. get: function () {
  21112. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  21113. },
  21114. enumerable: true,
  21115. configurable: true
  21116. });
  21117. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  21118. /**
  21119. * Gets the number of facets in the mesh
  21120. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  21121. */
  21122. get: function () {
  21123. return this._facetData.facetNb;
  21124. },
  21125. enumerable: true,
  21126. configurable: true
  21127. });
  21128. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  21129. /**
  21130. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  21131. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  21132. */
  21133. get: function () {
  21134. return this._facetData.partitioningSubdivisions;
  21135. },
  21136. set: function (nb) {
  21137. this._facetData.partitioningSubdivisions = nb;
  21138. },
  21139. enumerable: true,
  21140. configurable: true
  21141. });
  21142. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  21143. /**
  21144. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  21145. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  21146. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  21147. */
  21148. get: function () {
  21149. return this._facetData.partitioningBBoxRatio;
  21150. },
  21151. set: function (ratio) {
  21152. this._facetData.partitioningBBoxRatio = ratio;
  21153. },
  21154. enumerable: true,
  21155. configurable: true
  21156. });
  21157. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  21158. /**
  21159. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  21160. * Works only for updatable meshes.
  21161. * Doesn't work with multi-materials
  21162. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  21163. */
  21164. get: function () {
  21165. return this._facetData.facetDepthSort;
  21166. },
  21167. set: function (sort) {
  21168. this._facetData.facetDepthSort = sort;
  21169. },
  21170. enumerable: true,
  21171. configurable: true
  21172. });
  21173. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  21174. /**
  21175. * The location (Vector3) where the facet depth sort must be computed from.
  21176. * By default, the active camera position.
  21177. * Used only when facet depth sort is enabled
  21178. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  21179. */
  21180. get: function () {
  21181. return this._facetData.facetDepthSortFrom;
  21182. },
  21183. set: function (location) {
  21184. this._facetData.facetDepthSortFrom = location;
  21185. },
  21186. enumerable: true,
  21187. configurable: true
  21188. });
  21189. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  21190. /**
  21191. * gets a boolean indicating if facetData is enabled
  21192. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  21193. */
  21194. get: function () {
  21195. return this._facetData.facetDataEnabled;
  21196. },
  21197. enumerable: true,
  21198. configurable: true
  21199. });
  21200. /** @hidden */
  21201. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  21202. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  21203. return false;
  21204. }
  21205. this._markSubMeshesAsMiscDirty();
  21206. return true;
  21207. };
  21208. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  21209. /** Set a function to call when this mesh collides with another one */
  21210. set: function (callback) {
  21211. if (this._onCollideObserver) {
  21212. this.onCollideObservable.remove(this._onCollideObserver);
  21213. }
  21214. this._onCollideObserver = this.onCollideObservable.add(callback);
  21215. },
  21216. enumerable: true,
  21217. configurable: true
  21218. });
  21219. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  21220. /** Set a function to call when the collision's position changes */
  21221. set: function (callback) {
  21222. if (this._onCollisionPositionChangeObserver) {
  21223. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  21224. }
  21225. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  21226. },
  21227. enumerable: true,
  21228. configurable: true
  21229. });
  21230. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  21231. /**
  21232. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  21233. */
  21234. get: function () {
  21235. return this._visibility;
  21236. },
  21237. /**
  21238. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  21239. */
  21240. set: function (value) {
  21241. if (this._visibility === value) {
  21242. return;
  21243. }
  21244. this._visibility = value;
  21245. this._markSubMeshesAsMiscDirty();
  21246. },
  21247. enumerable: true,
  21248. configurable: true
  21249. });
  21250. Object.defineProperty(AbstractMesh.prototype, "material", {
  21251. /** Gets or sets current material */
  21252. get: function () {
  21253. return this._material;
  21254. },
  21255. set: function (value) {
  21256. if (this._material === value) {
  21257. return;
  21258. }
  21259. // remove from material mesh map id needed
  21260. if (this._material && this._material.meshMap) {
  21261. this._material.meshMap[this.uniqueId] = undefined;
  21262. }
  21263. this._material = value;
  21264. if (value && value.meshMap) {
  21265. value.meshMap[this.uniqueId] = this;
  21266. }
  21267. if (this.onMaterialChangedObservable.hasObservers) {
  21268. this.onMaterialChangedObservable.notifyObservers(this);
  21269. }
  21270. if (!this.subMeshes) {
  21271. return;
  21272. }
  21273. this._unBindEffect();
  21274. },
  21275. enumerable: true,
  21276. configurable: true
  21277. });
  21278. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  21279. /**
  21280. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  21281. * @see http://doc.babylonjs.com/babylon101/shadows
  21282. */
  21283. get: function () {
  21284. return this._receiveShadows;
  21285. },
  21286. set: function (value) {
  21287. if (this._receiveShadows === value) {
  21288. return;
  21289. }
  21290. this._receiveShadows = value;
  21291. this._markSubMeshesAsLightDirty();
  21292. },
  21293. enumerable: true,
  21294. configurable: true
  21295. });
  21296. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  21297. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  21298. get: function () {
  21299. return this._hasVertexAlpha;
  21300. },
  21301. set: function (value) {
  21302. if (this._hasVertexAlpha === value) {
  21303. return;
  21304. }
  21305. this._hasVertexAlpha = value;
  21306. this._markSubMeshesAsAttributesDirty();
  21307. this._markSubMeshesAsMiscDirty();
  21308. },
  21309. enumerable: true,
  21310. configurable: true
  21311. });
  21312. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  21313. /** 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) */
  21314. get: function () {
  21315. return this._useVertexColors;
  21316. },
  21317. set: function (value) {
  21318. if (this._useVertexColors === value) {
  21319. return;
  21320. }
  21321. this._useVertexColors = value;
  21322. this._markSubMeshesAsAttributesDirty();
  21323. },
  21324. enumerable: true,
  21325. configurable: true
  21326. });
  21327. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  21328. /**
  21329. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  21330. */
  21331. get: function () {
  21332. return this._computeBonesUsingShaders;
  21333. },
  21334. set: function (value) {
  21335. if (this._computeBonesUsingShaders === value) {
  21336. return;
  21337. }
  21338. this._computeBonesUsingShaders = value;
  21339. this._markSubMeshesAsAttributesDirty();
  21340. },
  21341. enumerable: true,
  21342. configurable: true
  21343. });
  21344. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  21345. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  21346. get: function () {
  21347. return this._numBoneInfluencers;
  21348. },
  21349. set: function (value) {
  21350. if (this._numBoneInfluencers === value) {
  21351. return;
  21352. }
  21353. this._numBoneInfluencers = value;
  21354. this._markSubMeshesAsAttributesDirty();
  21355. },
  21356. enumerable: true,
  21357. configurable: true
  21358. });
  21359. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  21360. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  21361. get: function () {
  21362. return this._applyFog;
  21363. },
  21364. set: function (value) {
  21365. if (this._applyFog === value) {
  21366. return;
  21367. }
  21368. this._applyFog = value;
  21369. this._markSubMeshesAsMiscDirty();
  21370. },
  21371. enumerable: true,
  21372. configurable: true
  21373. });
  21374. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  21375. /**
  21376. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  21377. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  21378. */
  21379. get: function () {
  21380. return this._layerMask;
  21381. },
  21382. set: function (value) {
  21383. if (value === this._layerMask) {
  21384. return;
  21385. }
  21386. this._layerMask = value;
  21387. this._resyncLightSources();
  21388. },
  21389. enumerable: true,
  21390. configurable: true
  21391. });
  21392. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  21393. /**
  21394. * Gets or sets a collision mask used to mask collisions (default is -1).
  21395. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21396. */
  21397. get: function () {
  21398. return this._collisionMask;
  21399. },
  21400. set: function (mask) {
  21401. this._collisionMask = !isNaN(mask) ? mask : -1;
  21402. },
  21403. enumerable: true,
  21404. configurable: true
  21405. });
  21406. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  21407. /**
  21408. * Gets or sets the current collision group mask (-1 by default).
  21409. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21410. */
  21411. get: function () {
  21412. return this._collisionGroup;
  21413. },
  21414. set: function (mask) {
  21415. this._collisionGroup = !isNaN(mask) ? mask : -1;
  21416. },
  21417. enumerable: true,
  21418. configurable: true
  21419. });
  21420. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  21421. /** @hidden */
  21422. get: function () {
  21423. return null;
  21424. },
  21425. enumerable: true,
  21426. configurable: true
  21427. });
  21428. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  21429. get: function () {
  21430. return this._skeleton;
  21431. },
  21432. /**
  21433. * Gets or sets a skeleton to apply skining transformations
  21434. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  21435. */
  21436. set: function (value) {
  21437. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  21438. this._skeleton._unregisterMeshWithPoseMatrix(this);
  21439. }
  21440. if (value && value.needInitialSkinMatrix) {
  21441. value._registerMeshWithPoseMatrix(this);
  21442. }
  21443. this._skeleton = value;
  21444. if (!this._skeleton) {
  21445. this._bonesTransformMatrices = null;
  21446. }
  21447. this._markSubMeshesAsAttributesDirty();
  21448. },
  21449. enumerable: true,
  21450. configurable: true
  21451. });
  21452. /**
  21453. * Returns the string "AbstractMesh"
  21454. * @returns "AbstractMesh"
  21455. */
  21456. AbstractMesh.prototype.getClassName = function () {
  21457. return "AbstractMesh";
  21458. };
  21459. /**
  21460. * Gets a string representation of the current mesh
  21461. * @param fullDetails defines a boolean indicating if full details must be included
  21462. * @returns a string representation of the current mesh
  21463. */
  21464. AbstractMesh.prototype.toString = function (fullDetails) {
  21465. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  21466. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  21467. if (this._skeleton) {
  21468. ret += ", skeleton: " + this._skeleton.name;
  21469. }
  21470. if (fullDetails) {
  21471. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  21472. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  21473. }
  21474. return ret;
  21475. };
  21476. /** @hidden */
  21477. AbstractMesh.prototype._rebuild = function () {
  21478. this.onRebuildObservable.notifyObservers(this);
  21479. if (this._occlusionQuery) {
  21480. this._occlusionQuery = null;
  21481. }
  21482. if (!this.subMeshes) {
  21483. return;
  21484. }
  21485. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21486. var subMesh = _a[_i];
  21487. subMesh._rebuild();
  21488. }
  21489. };
  21490. /** @hidden */
  21491. AbstractMesh.prototype._resyncLightSources = function () {
  21492. this._lightSources.length = 0;
  21493. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  21494. var light = _a[_i];
  21495. if (!light.isEnabled()) {
  21496. continue;
  21497. }
  21498. if (light.canAffectMesh(this)) {
  21499. this._lightSources.push(light);
  21500. }
  21501. }
  21502. this._markSubMeshesAsLightDirty();
  21503. };
  21504. /** @hidden */
  21505. AbstractMesh.prototype._resyncLighSource = function (light) {
  21506. var isIn = light.isEnabled() && light.canAffectMesh(this);
  21507. var index = this._lightSources.indexOf(light);
  21508. if (index === -1) {
  21509. if (!isIn) {
  21510. return;
  21511. }
  21512. this._lightSources.push(light);
  21513. }
  21514. else {
  21515. if (isIn) {
  21516. return;
  21517. }
  21518. this._lightSources.splice(index, 1);
  21519. }
  21520. this._markSubMeshesAsLightDirty();
  21521. };
  21522. /** @hidden */
  21523. AbstractMesh.prototype._unBindEffect = function () {
  21524. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21525. var subMesh = _a[_i];
  21526. subMesh.setEffect(null);
  21527. }
  21528. };
  21529. /** @hidden */
  21530. AbstractMesh.prototype._removeLightSource = function (light) {
  21531. var index = this._lightSources.indexOf(light);
  21532. if (index === -1) {
  21533. return;
  21534. }
  21535. this._lightSources.splice(index, 1);
  21536. this._markSubMeshesAsLightDirty();
  21537. };
  21538. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  21539. if (!this.subMeshes) {
  21540. return;
  21541. }
  21542. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21543. var subMesh = _a[_i];
  21544. if (subMesh._materialDefines) {
  21545. func(subMesh._materialDefines);
  21546. }
  21547. }
  21548. };
  21549. /** @hidden */
  21550. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  21551. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  21552. };
  21553. /** @hidden */
  21554. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  21555. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  21556. };
  21557. /** @hidden */
  21558. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  21559. if (!this.subMeshes) {
  21560. return;
  21561. }
  21562. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21563. var subMesh = _a[_i];
  21564. var material = subMesh.getMaterial();
  21565. if (material) {
  21566. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  21567. }
  21568. }
  21569. };
  21570. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  21571. /**
  21572. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  21573. */
  21574. get: function () {
  21575. return this._scaling;
  21576. },
  21577. set: function (newScaling) {
  21578. this._scaling = newScaling;
  21579. if (this.physicsImpostor) {
  21580. this.physicsImpostor.forceUpdate();
  21581. }
  21582. },
  21583. enumerable: true,
  21584. configurable: true
  21585. });
  21586. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  21587. // Methods
  21588. /**
  21589. * Returns true if the mesh is blocked. Implemented by child classes
  21590. */
  21591. get: function () {
  21592. return false;
  21593. },
  21594. enumerable: true,
  21595. configurable: true
  21596. });
  21597. /**
  21598. * Returns the mesh itself by default. Implemented by child classes
  21599. * @param camera defines the camera to use to pick the right LOD level
  21600. * @returns the currentAbstractMesh
  21601. */
  21602. AbstractMesh.prototype.getLOD = function (camera) {
  21603. return this;
  21604. };
  21605. /**
  21606. * Returns 0 by default. Implemented by child classes
  21607. * @returns an integer
  21608. */
  21609. AbstractMesh.prototype.getTotalVertices = function () {
  21610. return 0;
  21611. };
  21612. /**
  21613. * Returns null by default. Implemented by child classes
  21614. * @returns null
  21615. */
  21616. AbstractMesh.prototype.getIndices = function () {
  21617. return null;
  21618. };
  21619. /**
  21620. * Returns the array of the requested vertex data kind. Implemented by child classes
  21621. * @param kind defines the vertex data kind to use
  21622. * @returns null
  21623. */
  21624. AbstractMesh.prototype.getVerticesData = function (kind) {
  21625. return null;
  21626. };
  21627. /**
  21628. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21629. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21630. * Note that a new underlying VertexBuffer object is created each call.
  21631. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21632. * @param kind defines vertex data kind:
  21633. * * BABYLON.VertexBuffer.PositionKind
  21634. * * BABYLON.VertexBuffer.UVKind
  21635. * * BABYLON.VertexBuffer.UV2Kind
  21636. * * BABYLON.VertexBuffer.UV3Kind
  21637. * * BABYLON.VertexBuffer.UV4Kind
  21638. * * BABYLON.VertexBuffer.UV5Kind
  21639. * * BABYLON.VertexBuffer.UV6Kind
  21640. * * BABYLON.VertexBuffer.ColorKind
  21641. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21642. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21643. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21644. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21645. * @param data defines the data source
  21646. * @param updatable defines if the data must be flagged as updatable (or static)
  21647. * @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
  21648. * @returns the current mesh
  21649. */
  21650. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21651. return this;
  21652. };
  21653. /**
  21654. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21655. * If the mesh has no geometry, it is simply returned as it is.
  21656. * @param kind defines vertex data kind:
  21657. * * BABYLON.VertexBuffer.PositionKind
  21658. * * BABYLON.VertexBuffer.UVKind
  21659. * * BABYLON.VertexBuffer.UV2Kind
  21660. * * BABYLON.VertexBuffer.UV3Kind
  21661. * * BABYLON.VertexBuffer.UV4Kind
  21662. * * BABYLON.VertexBuffer.UV5Kind
  21663. * * BABYLON.VertexBuffer.UV6Kind
  21664. * * BABYLON.VertexBuffer.ColorKind
  21665. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21666. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21667. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21668. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21669. * @param data defines the data source
  21670. * @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
  21671. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  21672. * @returns the current mesh
  21673. */
  21674. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21675. return this;
  21676. };
  21677. /**
  21678. * Sets the mesh indices,
  21679. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21680. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  21681. * @param totalVertices Defines the total number of vertices
  21682. * @returns the current mesh
  21683. */
  21684. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  21685. return this;
  21686. };
  21687. /**
  21688. * Gets a boolean indicating if specific vertex data is present
  21689. * @param kind defines the vertex data kind to use
  21690. * @returns true is data kind is present
  21691. */
  21692. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  21693. return false;
  21694. };
  21695. /**
  21696. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  21697. * @returns a BoundingInfo
  21698. */
  21699. AbstractMesh.prototype.getBoundingInfo = function () {
  21700. if (this._masterMesh) {
  21701. return this._masterMesh.getBoundingInfo();
  21702. }
  21703. if (!this._boundingInfo) {
  21704. // this._boundingInfo is being created here
  21705. this._updateBoundingInfo();
  21706. }
  21707. // cannot be null.
  21708. return this._boundingInfo;
  21709. };
  21710. /**
  21711. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  21712. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  21713. * @returns the current mesh
  21714. */
  21715. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  21716. if (includeDescendants === void 0) { includeDescendants = true; }
  21717. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  21718. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  21719. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  21720. if (maxDimension === 0) {
  21721. return this;
  21722. }
  21723. var scale = 1 / maxDimension;
  21724. this.scaling.scaleInPlace(scale);
  21725. return this;
  21726. };
  21727. /**
  21728. * Overwrite the current bounding info
  21729. * @param boundingInfo defines the new bounding info
  21730. * @returns the current mesh
  21731. */
  21732. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21733. this._boundingInfo = boundingInfo;
  21734. return this;
  21735. };
  21736. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  21737. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  21738. get: function () {
  21739. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  21740. },
  21741. enumerable: true,
  21742. configurable: true
  21743. });
  21744. /** @hidden */
  21745. AbstractMesh.prototype._preActivate = function () {
  21746. };
  21747. /** @hidden */
  21748. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21749. };
  21750. /** @hidden */
  21751. AbstractMesh.prototype._activate = function (renderId) {
  21752. this._renderId = renderId;
  21753. };
  21754. /**
  21755. * Gets the current world matrix
  21756. * @returns a Matrix
  21757. */
  21758. AbstractMesh.prototype.getWorldMatrix = function () {
  21759. if (this._masterMesh) {
  21760. return this._masterMesh.getWorldMatrix();
  21761. }
  21762. return _super.prototype.getWorldMatrix.call(this);
  21763. };
  21764. /** @hidden */
  21765. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  21766. if (this._masterMesh) {
  21767. return this._masterMesh._getWorldMatrixDeterminant();
  21768. }
  21769. return _super.prototype._getWorldMatrixDeterminant.call(this);
  21770. };
  21771. // ================================== Point of View Movement =================================
  21772. /**
  21773. * Perform relative position change from the point of view of behind the front of the mesh.
  21774. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21775. * Supports definition of mesh facing forward or backward
  21776. * @param amountRight defines the distance on the right axis
  21777. * @param amountUp defines the distance on the up axis
  21778. * @param amountForward defines the distance on the forward axis
  21779. * @returns the current mesh
  21780. */
  21781. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  21782. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  21783. return this;
  21784. };
  21785. /**
  21786. * Calculate relative position change from the point of view of behind the front of the mesh.
  21787. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21788. * Supports definition of mesh facing forward or backward
  21789. * @param amountRight defines the distance on the right axis
  21790. * @param amountUp defines the distance on the up axis
  21791. * @param amountForward defines the distance on the forward axis
  21792. * @returns the new displacement vector
  21793. */
  21794. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  21795. var rotMatrix = new BABYLON.Matrix();
  21796. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  21797. rotQuaternion.toRotationMatrix(rotMatrix);
  21798. var translationDelta = BABYLON.Vector3.Zero();
  21799. var defForwardMult = this.definedFacingForward ? -1 : 1;
  21800. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  21801. return translationDelta;
  21802. };
  21803. // ================================== Point of View Rotation =================================
  21804. /**
  21805. * Perform relative rotation change from the point of view of behind the front of the mesh.
  21806. * Supports definition of mesh facing forward or backward
  21807. * @param flipBack defines the flip
  21808. * @param twirlClockwise defines the twirl
  21809. * @param tiltRight defines the tilt
  21810. * @returns the current mesh
  21811. */
  21812. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21813. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  21814. return this;
  21815. };
  21816. /**
  21817. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  21818. * Supports definition of mesh facing forward or backward.
  21819. * @param flipBack defines the flip
  21820. * @param twirlClockwise defines the twirl
  21821. * @param tiltRight defines the tilt
  21822. * @returns the new rotation vector
  21823. */
  21824. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21825. var defForwardMult = this.definedFacingForward ? 1 : -1;
  21826. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  21827. };
  21828. /**
  21829. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  21830. * @param includeDescendants Include bounding info from descendants as well (true by default)
  21831. * @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
  21832. * @returns the new bounding vectors
  21833. */
  21834. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  21835. if (includeDescendants === void 0) { includeDescendants = true; }
  21836. if (predicate === void 0) { predicate = null; }
  21837. // Ensures that all world matrix will be recomputed.
  21838. this.getScene().incrementRenderId();
  21839. this.computeWorldMatrix(true);
  21840. var min;
  21841. var max;
  21842. var boundingInfo = this.getBoundingInfo();
  21843. if (!this.subMeshes) {
  21844. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21845. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21846. }
  21847. else {
  21848. min = boundingInfo.boundingBox.minimumWorld;
  21849. max = boundingInfo.boundingBox.maximumWorld;
  21850. }
  21851. if (includeDescendants) {
  21852. var descendants = this.getDescendants(false);
  21853. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  21854. var descendant = descendants_1[_i];
  21855. var childMesh = descendant;
  21856. childMesh.computeWorldMatrix(true);
  21857. // Filters meshes based on custom predicate function.
  21858. if (predicate && !predicate(childMesh)) {
  21859. continue;
  21860. }
  21861. //make sure we have the needed params to get mix and max
  21862. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  21863. continue;
  21864. }
  21865. var childBoundingInfo = childMesh.getBoundingInfo();
  21866. var boundingBox = childBoundingInfo.boundingBox;
  21867. var minBox = boundingBox.minimumWorld;
  21868. var maxBox = boundingBox.maximumWorld;
  21869. BABYLON.Tools.CheckExtends(minBox, min, max);
  21870. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21871. }
  21872. }
  21873. return {
  21874. min: min,
  21875. max: max
  21876. };
  21877. };
  21878. /** @hidden */
  21879. AbstractMesh.prototype._updateBoundingInfo = function () {
  21880. if (this._boundingInfo) {
  21881. this._boundingInfo.update(this.worldMatrixFromCache);
  21882. }
  21883. else {
  21884. this._boundingInfo = new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition, this.worldMatrixFromCache);
  21885. }
  21886. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21887. return this;
  21888. };
  21889. /** @hidden */
  21890. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  21891. if (!this.subMeshes) {
  21892. return this;
  21893. }
  21894. var count = this.subMeshes.length;
  21895. for (var subIndex = 0; subIndex < count; subIndex++) {
  21896. var subMesh = this.subMeshes[subIndex];
  21897. if (count > 1 || !subMesh.IsGlobal) {
  21898. subMesh.updateBoundingInfo(matrix);
  21899. }
  21900. }
  21901. return this;
  21902. };
  21903. /** @hidden */
  21904. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  21905. // Bounding info
  21906. this._updateBoundingInfo();
  21907. };
  21908. /**
  21909. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  21910. * A mesh is in the frustum if its bounding box intersects the frustum
  21911. * @param frustumPlanes defines the frustum to test
  21912. * @returns true if the mesh is in the frustum planes
  21913. */
  21914. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  21915. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  21916. };
  21917. /**
  21918. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  21919. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  21920. * @param frustumPlanes defines the frustum to test
  21921. * @returns true if the mesh is completely in the frustum planes
  21922. */
  21923. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21924. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  21925. };
  21926. /**
  21927. * True if the mesh intersects another mesh or a SolidParticle object
  21928. * @param mesh defines a target mesh or SolidParticle to test
  21929. * @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)
  21930. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  21931. * @returns true if there is an intersection
  21932. */
  21933. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  21934. if (precise === void 0) { precise = false; }
  21935. if (!this._boundingInfo || !mesh._boundingInfo) {
  21936. return false;
  21937. }
  21938. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  21939. return true;
  21940. }
  21941. if (includeDescendants) {
  21942. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  21943. var child = _a[_i];
  21944. if (child.intersectsMesh(mesh, precise, true)) {
  21945. return true;
  21946. }
  21947. }
  21948. }
  21949. return false;
  21950. };
  21951. /**
  21952. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  21953. * @param point defines the point to test
  21954. * @returns true if there is an intersection
  21955. */
  21956. AbstractMesh.prototype.intersectsPoint = function (point) {
  21957. if (!this._boundingInfo) {
  21958. return false;
  21959. }
  21960. return this._boundingInfo.intersectsPoint(point);
  21961. };
  21962. /**
  21963. * Gets the position of the current mesh in camera space
  21964. * @param camera defines the camera to use
  21965. * @returns a position
  21966. */
  21967. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  21968. if (camera === void 0) { camera = null; }
  21969. if (!camera) {
  21970. camera = this.getScene().activeCamera;
  21971. }
  21972. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  21973. };
  21974. /**
  21975. * Returns the distance from the mesh to the active camera
  21976. * @param camera defines the camera to use
  21977. * @returns the distance
  21978. */
  21979. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  21980. if (camera === void 0) { camera = null; }
  21981. if (!camera) {
  21982. camera = this.getScene().activeCamera;
  21983. }
  21984. return this.absolutePosition.subtract(camera.position).length();
  21985. };
  21986. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  21987. // Collisions
  21988. /**
  21989. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  21990. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21991. */
  21992. get: function () {
  21993. return this._checkCollisions;
  21994. },
  21995. set: function (collisionEnabled) {
  21996. this._checkCollisions = collisionEnabled;
  21997. if (this.getScene().workerCollisions) {
  21998. this.getScene().collisionCoordinator.onMeshUpdated(this);
  21999. }
  22000. },
  22001. enumerable: true,
  22002. configurable: true
  22003. });
  22004. Object.defineProperty(AbstractMesh.prototype, "collider", {
  22005. /**
  22006. * Gets Collider object used to compute collisions (not physics)
  22007. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  22008. */
  22009. get: function () {
  22010. return this._collider;
  22011. },
  22012. enumerable: true,
  22013. configurable: true
  22014. });
  22015. /**
  22016. * Move the mesh using collision engine
  22017. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  22018. * @param displacement defines the requested displacement vector
  22019. * @returns the current mesh
  22020. */
  22021. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  22022. var globalPosition = this.getAbsolutePosition();
  22023. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  22024. if (!this._collider) {
  22025. this._collider = new BABYLON.Collider();
  22026. }
  22027. this._collider._radius = this.ellipsoid;
  22028. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  22029. return this;
  22030. };
  22031. // Collisions
  22032. /** @hidden */
  22033. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  22034. this._generatePointsArray();
  22035. if (!this._positions) {
  22036. return this;
  22037. }
  22038. // Transformation
  22039. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  22040. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  22041. subMesh._lastColliderWorldVertices = [];
  22042. subMesh._trianglePlanes = [];
  22043. var start = subMesh.verticesStart;
  22044. var end = (subMesh.verticesStart + subMesh.verticesCount);
  22045. for (var i = start; i < end; i++) {
  22046. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  22047. }
  22048. }
  22049. // Collide
  22050. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  22051. if (collider.collisionFound) {
  22052. collider.collidedMesh = this;
  22053. }
  22054. return this;
  22055. };
  22056. /** @hidden */
  22057. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  22058. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  22059. var len = subMeshes.length;
  22060. for (var index = 0; index < len; index++) {
  22061. var subMesh = subMeshes.data[index];
  22062. // Bounding test
  22063. if (len > 1 && !subMesh._checkCollision(collider)) {
  22064. continue;
  22065. }
  22066. this._collideForSubMesh(subMesh, transformMatrix, collider);
  22067. }
  22068. return this;
  22069. };
  22070. /** @hidden */
  22071. AbstractMesh.prototype._checkCollision = function (collider) {
  22072. // Bounding box test
  22073. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider)) {
  22074. return this;
  22075. }
  22076. // Transformation matrix
  22077. var collisionsScalingMatrix = BABYLON.Tmp.Matrix[0];
  22078. var collisionsTransformMatrix = BABYLON.Tmp.Matrix[1];
  22079. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, collisionsScalingMatrix);
  22080. this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix);
  22081. this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix);
  22082. return this;
  22083. };
  22084. // Picking
  22085. /** @hidden */
  22086. AbstractMesh.prototype._generatePointsArray = function () {
  22087. return false;
  22088. };
  22089. /**
  22090. * Checks if the passed Ray intersects with the mesh
  22091. * @param ray defines the ray to use
  22092. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  22093. * @returns the picking info
  22094. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  22095. */
  22096. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  22097. var pickingInfo = new BABYLON.PickingInfo();
  22098. var intersectionTreshold = this.getClassName() === "LinesMesh" ? this.intersectionThreshold : 0;
  22099. var boundingInfo = this._boundingInfo;
  22100. if (!this.subMeshes || !boundingInfo || !ray.intersectsSphere(boundingInfo.boundingSphere, intersectionTreshold) || !ray.intersectsBox(boundingInfo.boundingBox, intersectionTreshold)) {
  22101. return pickingInfo;
  22102. }
  22103. if (!this._generatePointsArray()) {
  22104. return pickingInfo;
  22105. }
  22106. var intersectInfo = null;
  22107. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  22108. var len = subMeshes.length;
  22109. for (var index = 0; index < len; index++) {
  22110. var subMesh = subMeshes.data[index];
  22111. // Bounding test
  22112. if (len > 1 && !subMesh.canIntersects(ray)) {
  22113. continue;
  22114. }
  22115. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  22116. if (currentIntersectInfo) {
  22117. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22118. intersectInfo = currentIntersectInfo;
  22119. intersectInfo.subMeshId = index;
  22120. if (fastCheck) {
  22121. break;
  22122. }
  22123. }
  22124. }
  22125. }
  22126. if (intersectInfo) {
  22127. // Get picked point
  22128. var world = this.getWorldMatrix();
  22129. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  22130. var direction = ray.direction.scaleToRef(intersectInfo.distance, BABYLON.Tmp.Vector3[0]);
  22131. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  22132. var pickedPoint = worldDirection.addInPlace(worldOrigin);
  22133. // Return result
  22134. pickingInfo.hit = true;
  22135. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  22136. pickingInfo.pickedPoint = pickedPoint;
  22137. pickingInfo.pickedMesh = this;
  22138. pickingInfo.bu = intersectInfo.bu || 0;
  22139. pickingInfo.bv = intersectInfo.bv || 0;
  22140. pickingInfo.faceId = intersectInfo.faceId;
  22141. pickingInfo.subMeshId = intersectInfo.subMeshId;
  22142. return pickingInfo;
  22143. }
  22144. return pickingInfo;
  22145. };
  22146. /**
  22147. * Clones the current mesh
  22148. * @param name defines the mesh name
  22149. * @param newParent defines the new mesh parent
  22150. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  22151. * @returns the new mesh
  22152. */
  22153. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  22154. return null;
  22155. };
  22156. /**
  22157. * Disposes all the submeshes of the current meshnp
  22158. * @returns the current mesh
  22159. */
  22160. AbstractMesh.prototype.releaseSubMeshes = function () {
  22161. if (this.subMeshes) {
  22162. while (this.subMeshes.length) {
  22163. this.subMeshes[0].dispose();
  22164. }
  22165. }
  22166. else {
  22167. this.subMeshes = new Array();
  22168. }
  22169. return this;
  22170. };
  22171. /**
  22172. * Releases resources associated with this abstract mesh.
  22173. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22174. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22175. */
  22176. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22177. var _this = this;
  22178. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22179. var index;
  22180. // Smart Array Retainers.
  22181. this.getScene().freeActiveMeshes();
  22182. this.getScene().freeRenderingGroups();
  22183. // Action manager
  22184. if (this.actionManager !== undefined && this.actionManager !== null) {
  22185. this.actionManager.dispose();
  22186. this.actionManager = null;
  22187. }
  22188. // Skeleton
  22189. this._skeleton = null;
  22190. // Intersections in progress
  22191. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  22192. var other = this._intersectionsInProgress[index];
  22193. var pos = other._intersectionsInProgress.indexOf(this);
  22194. other._intersectionsInProgress.splice(pos, 1);
  22195. }
  22196. this._intersectionsInProgress = [];
  22197. // Lights
  22198. var lights = this.getScene().lights;
  22199. lights.forEach(function (light) {
  22200. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  22201. if (meshIndex !== -1) {
  22202. light.includedOnlyMeshes.splice(meshIndex, 1);
  22203. }
  22204. meshIndex = light.excludedMeshes.indexOf(_this);
  22205. if (meshIndex !== -1) {
  22206. light.excludedMeshes.splice(meshIndex, 1);
  22207. }
  22208. // Shadow generators
  22209. var generator = light.getShadowGenerator();
  22210. if (generator) {
  22211. var shadowMap = generator.getShadowMap();
  22212. if (shadowMap && shadowMap.renderList) {
  22213. meshIndex = shadowMap.renderList.indexOf(_this);
  22214. if (meshIndex !== -1) {
  22215. shadowMap.renderList.splice(meshIndex, 1);
  22216. }
  22217. }
  22218. }
  22219. });
  22220. // SubMeshes
  22221. if (this.getClassName() !== "InstancedMesh") {
  22222. this.releaseSubMeshes();
  22223. }
  22224. // Query
  22225. var engine = this.getScene().getEngine();
  22226. if (this._occlusionQuery) {
  22227. this.isOcclusionQueryInProgress = false;
  22228. engine.deleteQuery(this._occlusionQuery);
  22229. this._occlusionQuery = null;
  22230. }
  22231. // Engine
  22232. engine.wipeCaches();
  22233. // Remove from scene
  22234. this.getScene().removeMesh(this);
  22235. if (disposeMaterialAndTextures) {
  22236. if (this.material) {
  22237. this.material.dispose(false, true);
  22238. }
  22239. }
  22240. if (!doNotRecurse) {
  22241. // Particles
  22242. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  22243. if (this.getScene().particleSystems[index].emitter === this) {
  22244. this.getScene().particleSystems[index].dispose();
  22245. index--;
  22246. }
  22247. }
  22248. }
  22249. // facet data
  22250. if (this._facetData.facetDataEnabled) {
  22251. this.disableFacetData();
  22252. }
  22253. this.onAfterWorldMatrixUpdateObservable.clear();
  22254. this.onCollideObservable.clear();
  22255. this.onCollisionPositionChangeObservable.clear();
  22256. this.onRebuildObservable.clear();
  22257. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22258. };
  22259. /**
  22260. * Adds the passed mesh as a child to the current mesh
  22261. * @param mesh defines the child mesh
  22262. * @returns the current mesh
  22263. */
  22264. AbstractMesh.prototype.addChild = function (mesh) {
  22265. mesh.setParent(this);
  22266. return this;
  22267. };
  22268. /**
  22269. * Removes the passed mesh from the current mesh children list
  22270. * @param mesh defines the child mesh
  22271. * @returns the current mesh
  22272. */
  22273. AbstractMesh.prototype.removeChild = function (mesh) {
  22274. mesh.setParent(null);
  22275. return this;
  22276. };
  22277. // Facet data
  22278. /** @hidden */
  22279. AbstractMesh.prototype._initFacetData = function () {
  22280. var data = this._facetData;
  22281. if (!data.facetNormals) {
  22282. data.facetNormals = new Array();
  22283. }
  22284. if (!data.facetPositions) {
  22285. data.facetPositions = new Array();
  22286. }
  22287. if (!data.facetPartitioning) {
  22288. data.facetPartitioning = new Array();
  22289. }
  22290. data.facetNb = (this.getIndices().length / 3) | 0;
  22291. data.partitioningSubdivisions = (data.partitioningSubdivisions) ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  22292. data.partitioningBBoxRatio = (data.partitioningBBoxRatio) ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  22293. for (var f = 0; f < data.facetNb; f++) {
  22294. data.facetNormals[f] = BABYLON.Vector3.Zero();
  22295. data.facetPositions[f] = BABYLON.Vector3.Zero();
  22296. }
  22297. data.facetDataEnabled = true;
  22298. return this;
  22299. };
  22300. /**
  22301. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  22302. * This method can be called within the render loop.
  22303. * 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
  22304. * @returns the current mesh
  22305. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22306. */
  22307. AbstractMesh.prototype.updateFacetData = function () {
  22308. var data = this._facetData;
  22309. if (!data.facetDataEnabled) {
  22310. this._initFacetData();
  22311. }
  22312. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22313. var indices = this.getIndices();
  22314. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22315. var bInfo = this.getBoundingInfo();
  22316. if (data.facetDepthSort && !data.facetDepthSortEnabled) {
  22317. // init arrays, matrix and sort function on first call
  22318. data.facetDepthSortEnabled = true;
  22319. if (indices instanceof Uint16Array) {
  22320. data.depthSortedIndices = new Uint16Array(indices);
  22321. }
  22322. else if (indices instanceof Uint32Array) {
  22323. data.depthSortedIndices = new Uint32Array(indices);
  22324. }
  22325. else {
  22326. var needs32bits = false;
  22327. for (var i = 0; i < indices.length; i++) {
  22328. if (indices[i] > 65535) {
  22329. needs32bits = true;
  22330. break;
  22331. }
  22332. }
  22333. if (needs32bits) {
  22334. data.depthSortedIndices = new Uint32Array(indices);
  22335. }
  22336. else {
  22337. data.depthSortedIndices = new Uint16Array(indices);
  22338. }
  22339. }
  22340. data.facetDepthSortFunction = function (f1, f2) {
  22341. return (f2.sqDistance - f1.sqDistance);
  22342. };
  22343. if (!data.facetDepthSortFrom) {
  22344. var camera = this.getScene().activeCamera;
  22345. data.facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  22346. }
  22347. data.depthSortedFacets = [];
  22348. for (var f = 0; f < data.facetNb; f++) {
  22349. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  22350. data.depthSortedFacets.push(depthSortedFacet);
  22351. }
  22352. data.invertedMatrix = BABYLON.Matrix.Identity();
  22353. data.facetDepthSortOrigin = BABYLON.Vector3.Zero();
  22354. }
  22355. data.bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  22356. data.bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  22357. data.bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  22358. var bbSizeMax = (data.bbSize.x > data.bbSize.y) ? data.bbSize.x : data.bbSize.y;
  22359. bbSizeMax = (bbSizeMax > data.bbSize.z) ? bbSizeMax : data.bbSize.z;
  22360. data.subDiv.max = data.partitioningSubdivisions;
  22361. data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  22362. data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); // according to each bbox size per axis
  22363. data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
  22364. data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
  22365. data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
  22366. data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
  22367. // set the parameters for ComputeNormals()
  22368. data.facetParameters.facetNormals = this.getFacetLocalNormals();
  22369. data.facetParameters.facetPositions = this.getFacetLocalPositions();
  22370. data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  22371. data.facetParameters.bInfo = bInfo;
  22372. data.facetParameters.bbSize = data.bbSize;
  22373. data.facetParameters.subDiv = data.subDiv;
  22374. data.facetParameters.ratio = this.partitioningBBoxRatio;
  22375. data.facetParameters.depthSort = data.facetDepthSort;
  22376. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22377. this.computeWorldMatrix(true);
  22378. this._worldMatrix.invertToRef(data.invertedMatrix);
  22379. BABYLON.Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
  22380. data.facetParameters.distanceTo = data.facetDepthSortOrigin;
  22381. }
  22382. data.facetParameters.depthSortedFacets = data.depthSortedFacets;
  22383. BABYLON.VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
  22384. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22385. data.depthSortedFacets.sort(data.facetDepthSortFunction);
  22386. var l = (data.depthSortedIndices.length / 3) | 0;
  22387. for (var f = 0; f < l; f++) {
  22388. var sind = data.depthSortedFacets[f].ind;
  22389. data.depthSortedIndices[f * 3] = indices[sind];
  22390. data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  22391. data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  22392. }
  22393. this.updateIndices(data.depthSortedIndices);
  22394. }
  22395. return this;
  22396. };
  22397. /**
  22398. * Returns the facetLocalNormals array.
  22399. * The normals are expressed in the mesh local spac
  22400. * @returns an array of Vector3
  22401. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22402. */
  22403. AbstractMesh.prototype.getFacetLocalNormals = function () {
  22404. if (!this._facetData.facetNormals) {
  22405. this.updateFacetData();
  22406. }
  22407. return this._facetData.facetNormals;
  22408. };
  22409. /**
  22410. * Returns the facetLocalPositions array.
  22411. * The facet positions are expressed in the mesh local space
  22412. * @returns an array of Vector3
  22413. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22414. */
  22415. AbstractMesh.prototype.getFacetLocalPositions = function () {
  22416. if (!this._facetData.facetPositions) {
  22417. this.updateFacetData();
  22418. }
  22419. return this._facetData.facetPositions;
  22420. };
  22421. /**
  22422. * Returns the facetLocalPartioning array
  22423. * @returns an array of array of numbers
  22424. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22425. */
  22426. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  22427. if (!this._facetData.facetPartitioning) {
  22428. this.updateFacetData();
  22429. }
  22430. return this._facetData.facetPartitioning;
  22431. };
  22432. /**
  22433. * Returns the i-th facet position in the world system.
  22434. * This method allocates a new Vector3 per call
  22435. * @param i defines the facet index
  22436. * @returns a new Vector3
  22437. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22438. */
  22439. AbstractMesh.prototype.getFacetPosition = function (i) {
  22440. var pos = BABYLON.Vector3.Zero();
  22441. this.getFacetPositionToRef(i, pos);
  22442. return pos;
  22443. };
  22444. /**
  22445. * Sets the reference Vector3 with the i-th facet position in the world system
  22446. * @param i defines the facet index
  22447. * @param ref defines the target vector
  22448. * @returns the current mesh
  22449. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22450. */
  22451. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  22452. var localPos = (this.getFacetLocalPositions())[i];
  22453. var world = this.getWorldMatrix();
  22454. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  22455. return this;
  22456. };
  22457. /**
  22458. * Returns the i-th facet normal in the world system.
  22459. * This method allocates a new Vector3 per call
  22460. * @param i defines the facet index
  22461. * @returns a new Vector3
  22462. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22463. */
  22464. AbstractMesh.prototype.getFacetNormal = function (i) {
  22465. var norm = BABYLON.Vector3.Zero();
  22466. this.getFacetNormalToRef(i, norm);
  22467. return norm;
  22468. };
  22469. /**
  22470. * Sets the reference Vector3 with the i-th facet normal in the world system
  22471. * @param i defines the facet index
  22472. * @param ref defines the target vector
  22473. * @returns the current mesh
  22474. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22475. */
  22476. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  22477. var localNorm = (this.getFacetLocalNormals())[i];
  22478. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  22479. return this;
  22480. };
  22481. /**
  22482. * 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)
  22483. * @param x defines x coordinate
  22484. * @param y defines y coordinate
  22485. * @param z defines z coordinate
  22486. * @returns the array of facet indexes
  22487. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22488. */
  22489. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  22490. var bInfo = this.getBoundingInfo();
  22491. var data = this._facetData;
  22492. var ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
  22493. var oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
  22494. var oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
  22495. if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
  22496. return null;
  22497. }
  22498. return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
  22499. };
  22500. /**
  22501. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  22502. * @param projected sets as the (x,y,z) world projection on the facet
  22503. * @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
  22504. * @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
  22505. * @param x defines x coordinate
  22506. * @param y defines y coordinate
  22507. * @param z defines z coordinate
  22508. * @returns the face index if found (or null instead)
  22509. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22510. */
  22511. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  22512. if (checkFace === void 0) { checkFace = false; }
  22513. if (facing === void 0) { facing = true; }
  22514. var world = this.getWorldMatrix();
  22515. var invMat = BABYLON.Tmp.Matrix[5];
  22516. world.invertToRef(invMat);
  22517. var invVect = BABYLON.Tmp.Vector3[8];
  22518. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  22519. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  22520. if (projected) {
  22521. // tranform the local computed projected vector to world coordinates
  22522. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  22523. }
  22524. return closest;
  22525. };
  22526. /**
  22527. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  22528. * @param projected sets as the (x,y,z) local projection on the facet
  22529. * @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
  22530. * @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
  22531. * @param x defines x coordinate
  22532. * @param y defines y coordinate
  22533. * @param z defines z coordinate
  22534. * @returns the face index if found (or null instead)
  22535. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22536. */
  22537. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  22538. if (checkFace === void 0) { checkFace = false; }
  22539. if (facing === void 0) { facing = true; }
  22540. var closest = null;
  22541. var tmpx = 0.0;
  22542. var tmpy = 0.0;
  22543. var tmpz = 0.0;
  22544. var d = 0.0; // tmp dot facet normal * facet position
  22545. var t0 = 0.0;
  22546. var projx = 0.0;
  22547. var projy = 0.0;
  22548. var projz = 0.0;
  22549. // Get all the facets in the same partitioning block than (x, y, z)
  22550. var facetPositions = this.getFacetLocalPositions();
  22551. var facetNormals = this.getFacetLocalNormals();
  22552. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  22553. if (!facetsInBlock) {
  22554. return null;
  22555. }
  22556. // Get the closest facet to (x, y, z)
  22557. var shortest = Number.MAX_VALUE; // init distance vars
  22558. var tmpDistance = shortest;
  22559. var fib; // current facet in the block
  22560. var norm; // current facet normal
  22561. var p0; // current facet barycenter position
  22562. // loop on all the facets in the current partitioning block
  22563. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  22564. fib = facetsInBlock[idx];
  22565. norm = facetNormals[fib];
  22566. p0 = facetPositions[fib];
  22567. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  22568. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  22569. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  22570. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  22571. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  22572. projx = x + norm.x * t0;
  22573. projy = y + norm.y * t0;
  22574. projz = z + norm.z * t0;
  22575. tmpx = projx - x;
  22576. tmpy = projy - y;
  22577. tmpz = projz - z;
  22578. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  22579. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  22580. shortest = tmpDistance;
  22581. closest = fib;
  22582. if (projected) {
  22583. projected.x = projx;
  22584. projected.y = projy;
  22585. projected.z = projz;
  22586. }
  22587. }
  22588. }
  22589. }
  22590. return closest;
  22591. };
  22592. /**
  22593. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  22594. * @returns the parameters
  22595. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22596. */
  22597. AbstractMesh.prototype.getFacetDataParameters = function () {
  22598. return this._facetData.facetParameters;
  22599. };
  22600. /**
  22601. * Disables the feature FacetData and frees the related memory
  22602. * @returns the current mesh
  22603. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22604. */
  22605. AbstractMesh.prototype.disableFacetData = function () {
  22606. if (this._facetData.facetDataEnabled) {
  22607. this._facetData.facetDataEnabled = false;
  22608. this._facetData.facetPositions = new Array();
  22609. this._facetData.facetNormals = new Array();
  22610. this._facetData.facetPartitioning = new Array();
  22611. this._facetData.facetParameters = null;
  22612. this._facetData.depthSortedIndices = new Uint32Array(0);
  22613. }
  22614. return this;
  22615. };
  22616. /**
  22617. * Updates the AbstractMesh indices array
  22618. * @param indices defines the data source
  22619. * @returns the current mesh
  22620. */
  22621. AbstractMesh.prototype.updateIndices = function (indices) {
  22622. return this;
  22623. };
  22624. /**
  22625. * Creates new normals data for the mesh
  22626. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  22627. * @returns the current mesh
  22628. */
  22629. AbstractMesh.prototype.createNormals = function (updatable) {
  22630. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22631. var indices = this.getIndices();
  22632. var normals;
  22633. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22634. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22635. }
  22636. else {
  22637. normals = [];
  22638. }
  22639. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  22640. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  22641. return this;
  22642. };
  22643. /**
  22644. * Align the mesh with a normal
  22645. * @param normal defines the normal to use
  22646. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  22647. * @returns the current mesh
  22648. */
  22649. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  22650. if (!upDirection) {
  22651. upDirection = BABYLON.Axis.Y;
  22652. }
  22653. var axisX = BABYLON.Tmp.Vector3[0];
  22654. var axisZ = BABYLON.Tmp.Vector3[1];
  22655. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  22656. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  22657. if (this.rotationQuaternion) {
  22658. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  22659. }
  22660. else {
  22661. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  22662. }
  22663. return this;
  22664. };
  22665. /** @hidden */
  22666. AbstractMesh.prototype._checkOcclusionQuery = function () {
  22667. return false;
  22668. };
  22669. /** No occlusion */
  22670. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  22671. /** Occlusion set to optimisitic */
  22672. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  22673. /** Occlusion set to strict */
  22674. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  22675. /** Use an accurante occlusion algorithm */
  22676. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  22677. /** Use a conservative occlusion algorithm */
  22678. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  22679. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  22680. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  22681. /** Culling strategy with bounding sphere only and then frustum culling */
  22682. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  22683. return AbstractMesh;
  22684. }(BABYLON.TransformNode));
  22685. BABYLON.AbstractMesh = AbstractMesh;
  22686. })(BABYLON || (BABYLON = {}));
  22687. //# sourceMappingURL=abstractMesh.js.map
  22688. var BABYLON;
  22689. (function (BABYLON) {
  22690. /**
  22691. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  22692. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  22693. * 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.
  22694. */
  22695. var Light = /** @class */ (function (_super) {
  22696. __extends(Light, _super);
  22697. /**
  22698. * Creates a Light object in the scene.
  22699. * Documentation : http://doc.babylonjs.com/tutorials/lights
  22700. * @param name The firendly name of the light
  22701. * @param scene The scene the light belongs too
  22702. */
  22703. function Light(name, scene) {
  22704. var _this = _super.call(this, name, scene) || this;
  22705. /**
  22706. * Diffuse gives the basic color to an object.
  22707. */
  22708. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  22709. /**
  22710. * Specular produces a highlight color on an object.
  22711. * Note: This is note affecting PBR materials.
  22712. */
  22713. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  22714. /**
  22715. * Defines the falloff type for this light. This lets overrriding how punctual light are
  22716. * falling off base on range or angle.
  22717. * This can be set to any values in Light.FALLOFF_x.
  22718. *
  22719. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  22720. * other types of materials.
  22721. */
  22722. _this.falloffType = Light.FALLOFF_DEFAULT;
  22723. /**
  22724. * Strength of the light.
  22725. * Note: By default it is define in the framework own unit.
  22726. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  22727. */
  22728. _this.intensity = 1.0;
  22729. _this._range = Number.MAX_VALUE;
  22730. _this._inverseSquaredRange = 0;
  22731. /**
  22732. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  22733. * of light.
  22734. */
  22735. _this._photometricScale = 1.0;
  22736. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  22737. _this._radius = 0.00001;
  22738. /**
  22739. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  22740. * exceeding the number allowed of the materials.
  22741. */
  22742. _this.renderPriority = 0;
  22743. _this._shadowEnabled = true;
  22744. _this._excludeWithLayerMask = 0;
  22745. _this._includeOnlyWithLayerMask = 0;
  22746. _this._lightmapMode = 0;
  22747. /**
  22748. * @hidden Internal use only.
  22749. */
  22750. _this._excludedMeshesIds = new Array();
  22751. /**
  22752. * @hidden Internal use only.
  22753. */
  22754. _this._includedOnlyMeshesIds = new Array();
  22755. _this.getScene().addLight(_this);
  22756. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  22757. _this._buildUniformLayout();
  22758. _this.includedOnlyMeshes = new Array();
  22759. _this.excludedMeshes = new Array();
  22760. _this._resyncMeshes();
  22761. return _this;
  22762. }
  22763. Object.defineProperty(Light.prototype, "range", {
  22764. /**
  22765. * Defines how far from the source the light is impacting in scene units.
  22766. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22767. */
  22768. get: function () {
  22769. return this._range;
  22770. },
  22771. /**
  22772. * Defines how far from the source the light is impacting in scene units.
  22773. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22774. */
  22775. set: function (value) {
  22776. this._range = value;
  22777. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  22778. },
  22779. enumerable: true,
  22780. configurable: true
  22781. });
  22782. Object.defineProperty(Light.prototype, "intensityMode", {
  22783. /**
  22784. * Gets the photometric scale used to interpret the intensity.
  22785. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22786. */
  22787. get: function () {
  22788. return this._intensityMode;
  22789. },
  22790. /**
  22791. * Sets the photometric scale used to interpret the intensity.
  22792. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22793. */
  22794. set: function (value) {
  22795. this._intensityMode = value;
  22796. this._computePhotometricScale();
  22797. },
  22798. enumerable: true,
  22799. configurable: true
  22800. });
  22801. Object.defineProperty(Light.prototype, "radius", {
  22802. /**
  22803. * Gets the light radius used by PBR Materials to simulate soft area lights.
  22804. */
  22805. get: function () {
  22806. return this._radius;
  22807. },
  22808. /**
  22809. * sets the light radius used by PBR Materials to simulate soft area lights.
  22810. */
  22811. set: function (value) {
  22812. this._radius = value;
  22813. this._computePhotometricScale();
  22814. },
  22815. enumerable: true,
  22816. configurable: true
  22817. });
  22818. Object.defineProperty(Light.prototype, "shadowEnabled", {
  22819. /**
  22820. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22821. * the current shadow generator.
  22822. */
  22823. get: function () {
  22824. return this._shadowEnabled;
  22825. },
  22826. /**
  22827. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22828. * the current shadow generator.
  22829. */
  22830. set: function (value) {
  22831. if (this._shadowEnabled === value) {
  22832. return;
  22833. }
  22834. this._shadowEnabled = value;
  22835. this._markMeshesAsLightDirty();
  22836. },
  22837. enumerable: true,
  22838. configurable: true
  22839. });
  22840. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  22841. /**
  22842. * Gets the only meshes impacted by this light.
  22843. */
  22844. get: function () {
  22845. return this._includedOnlyMeshes;
  22846. },
  22847. /**
  22848. * Sets the only meshes impacted by this light.
  22849. */
  22850. set: function (value) {
  22851. this._includedOnlyMeshes = value;
  22852. this._hookArrayForIncludedOnly(value);
  22853. },
  22854. enumerable: true,
  22855. configurable: true
  22856. });
  22857. Object.defineProperty(Light.prototype, "excludedMeshes", {
  22858. /**
  22859. * Gets the meshes not impacted by this light.
  22860. */
  22861. get: function () {
  22862. return this._excludedMeshes;
  22863. },
  22864. /**
  22865. * Sets the meshes not impacted by this light.
  22866. */
  22867. set: function (value) {
  22868. this._excludedMeshes = value;
  22869. this._hookArrayForExcluded(value);
  22870. },
  22871. enumerable: true,
  22872. configurable: true
  22873. });
  22874. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  22875. /**
  22876. * Gets the layer id use to find what meshes are not impacted by the light.
  22877. * Inactive if 0
  22878. */
  22879. get: function () {
  22880. return this._excludeWithLayerMask;
  22881. },
  22882. /**
  22883. * Sets the layer id use to find what meshes are not impacted by the light.
  22884. * Inactive if 0
  22885. */
  22886. set: function (value) {
  22887. this._excludeWithLayerMask = value;
  22888. this._resyncMeshes();
  22889. },
  22890. enumerable: true,
  22891. configurable: true
  22892. });
  22893. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  22894. /**
  22895. * Gets the layer id use to find what meshes are impacted by the light.
  22896. * Inactive if 0
  22897. */
  22898. get: function () {
  22899. return this._includeOnlyWithLayerMask;
  22900. },
  22901. /**
  22902. * Sets the layer id use to find what meshes are impacted by the light.
  22903. * Inactive if 0
  22904. */
  22905. set: function (value) {
  22906. this._includeOnlyWithLayerMask = value;
  22907. this._resyncMeshes();
  22908. },
  22909. enumerable: true,
  22910. configurable: true
  22911. });
  22912. Object.defineProperty(Light.prototype, "lightmapMode", {
  22913. /**
  22914. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22915. */
  22916. get: function () {
  22917. return this._lightmapMode;
  22918. },
  22919. /**
  22920. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22921. */
  22922. set: function (value) {
  22923. if (this._lightmapMode === value) {
  22924. return;
  22925. }
  22926. this._lightmapMode = value;
  22927. this._markMeshesAsLightDirty();
  22928. },
  22929. enumerable: true,
  22930. configurable: true
  22931. });
  22932. /**
  22933. * Returns the string "Light".
  22934. * @returns the class name
  22935. */
  22936. Light.prototype.getClassName = function () {
  22937. return "Light";
  22938. };
  22939. /**
  22940. * Converts the light information to a readable string for debug purpose.
  22941. * @param fullDetails Supports for multiple levels of logging within scene loading
  22942. * @returns the human readable light info
  22943. */
  22944. Light.prototype.toString = function (fullDetails) {
  22945. var ret = "Name: " + this.name;
  22946. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  22947. if (this.animations) {
  22948. for (var i = 0; i < this.animations.length; i++) {
  22949. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22950. }
  22951. }
  22952. if (fullDetails) {
  22953. }
  22954. return ret;
  22955. };
  22956. /** @hidden */
  22957. Light.prototype._syncParentEnabledState = function () {
  22958. _super.prototype._syncParentEnabledState.call(this);
  22959. this._resyncMeshes();
  22960. };
  22961. /**
  22962. * Set the enabled state of this node.
  22963. * @param value - the new enabled state
  22964. */
  22965. Light.prototype.setEnabled = function (value) {
  22966. _super.prototype.setEnabled.call(this, value);
  22967. this._resyncMeshes();
  22968. };
  22969. /**
  22970. * Returns the Light associated shadow generator if any.
  22971. * @return the associated shadow generator.
  22972. */
  22973. Light.prototype.getShadowGenerator = function () {
  22974. return this._shadowGenerator;
  22975. };
  22976. /**
  22977. * Returns a Vector3, the absolute light position in the World.
  22978. * @returns the world space position of the light
  22979. */
  22980. Light.prototype.getAbsolutePosition = function () {
  22981. return BABYLON.Vector3.Zero();
  22982. };
  22983. /**
  22984. * Specifies if the light will affect the passed mesh.
  22985. * @param mesh The mesh to test against the light
  22986. * @return true the mesh is affected otherwise, false.
  22987. */
  22988. Light.prototype.canAffectMesh = function (mesh) {
  22989. if (!mesh) {
  22990. return true;
  22991. }
  22992. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22993. return false;
  22994. }
  22995. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22996. return false;
  22997. }
  22998. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22999. return false;
  23000. }
  23001. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  23002. return false;
  23003. }
  23004. return true;
  23005. };
  23006. /**
  23007. * Sort function to order lights for rendering.
  23008. * @param a First Light object to compare to second.
  23009. * @param b Second Light object to compare first.
  23010. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  23011. */
  23012. Light.CompareLightsPriority = function (a, b) {
  23013. //shadow-casting lights have priority over non-shadow-casting lights
  23014. //the renderPrioirty is a secondary sort criterion
  23015. if (a.shadowEnabled !== b.shadowEnabled) {
  23016. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  23017. }
  23018. return b.renderPriority - a.renderPriority;
  23019. };
  23020. /**
  23021. * Releases resources associated with this node.
  23022. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  23023. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  23024. */
  23025. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  23026. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  23027. if (this._shadowGenerator) {
  23028. this._shadowGenerator.dispose();
  23029. this._shadowGenerator = null;
  23030. }
  23031. // Animations
  23032. this.getScene().stopAnimation(this);
  23033. // Remove from meshes
  23034. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23035. var mesh = _a[_i];
  23036. mesh._removeLightSource(this);
  23037. }
  23038. this._uniformBuffer.dispose();
  23039. // Remove from scene
  23040. this.getScene().removeLight(this);
  23041. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  23042. };
  23043. /**
  23044. * Returns the light type ID (integer).
  23045. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  23046. */
  23047. Light.prototype.getTypeID = function () {
  23048. return 0;
  23049. };
  23050. /**
  23051. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  23052. * @returns the scaled intensity in intensity mode unit
  23053. */
  23054. Light.prototype.getScaledIntensity = function () {
  23055. return this._photometricScale * this.intensity;
  23056. };
  23057. /**
  23058. * Returns a new Light object, named "name", from the current one.
  23059. * @param name The name of the cloned light
  23060. * @returns the new created light
  23061. */
  23062. Light.prototype.clone = function (name) {
  23063. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  23064. if (!constructor) {
  23065. return null;
  23066. }
  23067. return BABYLON.SerializationHelper.Clone(constructor, this);
  23068. };
  23069. /**
  23070. * Serializes the current light into a Serialization object.
  23071. * @returns the serialized object.
  23072. */
  23073. Light.prototype.serialize = function () {
  23074. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23075. // Type
  23076. serializationObject.type = this.getTypeID();
  23077. // Parent
  23078. if (this.parent) {
  23079. serializationObject.parentId = this.parent.id;
  23080. }
  23081. // Inclusion / exclusions
  23082. if (this.excludedMeshes.length > 0) {
  23083. serializationObject.excludedMeshesIds = [];
  23084. this.excludedMeshes.forEach(function (mesh) {
  23085. serializationObject.excludedMeshesIds.push(mesh.id);
  23086. });
  23087. }
  23088. if (this.includedOnlyMeshes.length > 0) {
  23089. serializationObject.includedOnlyMeshesIds = [];
  23090. this.includedOnlyMeshes.forEach(function (mesh) {
  23091. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  23092. });
  23093. }
  23094. // Animations
  23095. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23096. serializationObject.ranges = this.serializeAnimationRanges();
  23097. return serializationObject;
  23098. };
  23099. /**
  23100. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  23101. * This new light is named "name" and added to the passed scene.
  23102. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  23103. * @param name The friendly name of the light
  23104. * @param scene The scene the new light will belong to
  23105. * @returns the constructor function
  23106. */
  23107. Light.GetConstructorFromName = function (type, name, scene) {
  23108. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  23109. if (constructorFunc) {
  23110. return constructorFunc;
  23111. }
  23112. // Default to no light for none present once.
  23113. return null;
  23114. };
  23115. /**
  23116. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  23117. * @param parsedLight The JSON representation of the light
  23118. * @param scene The scene to create the parsed light in
  23119. * @returns the created light after parsing
  23120. */
  23121. Light.Parse = function (parsedLight, scene) {
  23122. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  23123. if (!constructor) {
  23124. return null;
  23125. }
  23126. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  23127. // Inclusion / exclusions
  23128. if (parsedLight.excludedMeshesIds) {
  23129. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  23130. }
  23131. if (parsedLight.includedOnlyMeshesIds) {
  23132. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  23133. }
  23134. // Parent
  23135. if (parsedLight.parentId) {
  23136. light._waitingParentId = parsedLight.parentId;
  23137. }
  23138. // Animations
  23139. if (parsedLight.animations) {
  23140. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  23141. var parsedAnimation = parsedLight.animations[animationIndex];
  23142. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23143. }
  23144. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  23145. }
  23146. if (parsedLight.autoAnimate) {
  23147. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  23148. }
  23149. return light;
  23150. };
  23151. Light.prototype._hookArrayForExcluded = function (array) {
  23152. var _this = this;
  23153. var oldPush = array.push;
  23154. array.push = function () {
  23155. var items = [];
  23156. for (var _i = 0; _i < arguments.length; _i++) {
  23157. items[_i] = arguments[_i];
  23158. }
  23159. var result = oldPush.apply(array, items);
  23160. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  23161. var item = items_1[_a];
  23162. item._resyncLighSource(_this);
  23163. }
  23164. return result;
  23165. };
  23166. var oldSplice = array.splice;
  23167. array.splice = function (index, deleteCount) {
  23168. var deleted = oldSplice.apply(array, [index, deleteCount]);
  23169. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  23170. var item = deleted_1[_i];
  23171. item._resyncLighSource(_this);
  23172. }
  23173. return deleted;
  23174. };
  23175. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  23176. var item = array_1[_i];
  23177. item._resyncLighSource(this);
  23178. }
  23179. };
  23180. Light.prototype._hookArrayForIncludedOnly = function (array) {
  23181. var _this = this;
  23182. var oldPush = array.push;
  23183. array.push = function () {
  23184. var items = [];
  23185. for (var _i = 0; _i < arguments.length; _i++) {
  23186. items[_i] = arguments[_i];
  23187. }
  23188. var result = oldPush.apply(array, items);
  23189. _this._resyncMeshes();
  23190. return result;
  23191. };
  23192. var oldSplice = array.splice;
  23193. array.splice = function (index, deleteCount) {
  23194. var deleted = oldSplice.apply(array, [index, deleteCount]);
  23195. _this._resyncMeshes();
  23196. return deleted;
  23197. };
  23198. this._resyncMeshes();
  23199. };
  23200. Light.prototype._resyncMeshes = function () {
  23201. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23202. var mesh = _a[_i];
  23203. mesh._resyncLighSource(this);
  23204. }
  23205. };
  23206. /**
  23207. * Forces the meshes to update their light related information in their rendering used effects
  23208. * @hidden Internal Use Only
  23209. */
  23210. Light.prototype._markMeshesAsLightDirty = function () {
  23211. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23212. var mesh = _a[_i];
  23213. if (mesh._lightSources.indexOf(this) !== -1) {
  23214. mesh._markSubMeshesAsLightDirty();
  23215. }
  23216. }
  23217. };
  23218. /**
  23219. * Recomputes the cached photometric scale if needed.
  23220. */
  23221. Light.prototype._computePhotometricScale = function () {
  23222. this._photometricScale = this._getPhotometricScale();
  23223. this.getScene().resetCachedMaterial();
  23224. };
  23225. /**
  23226. * Returns the Photometric Scale according to the light type and intensity mode.
  23227. */
  23228. Light.prototype._getPhotometricScale = function () {
  23229. var photometricScale = 0.0;
  23230. var lightTypeID = this.getTypeID();
  23231. //get photometric mode
  23232. var photometricMode = this.intensityMode;
  23233. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  23234. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  23235. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  23236. }
  23237. else {
  23238. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  23239. }
  23240. }
  23241. //compute photometric scale
  23242. switch (lightTypeID) {
  23243. case Light.LIGHTTYPEID_POINTLIGHT:
  23244. case Light.LIGHTTYPEID_SPOTLIGHT:
  23245. switch (photometricMode) {
  23246. case Light.INTENSITYMODE_LUMINOUSPOWER:
  23247. photometricScale = 1.0 / (4.0 * Math.PI);
  23248. break;
  23249. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  23250. photometricScale = 1.0;
  23251. break;
  23252. case Light.INTENSITYMODE_LUMINANCE:
  23253. photometricScale = this.radius * this.radius;
  23254. break;
  23255. }
  23256. break;
  23257. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  23258. switch (photometricMode) {
  23259. case Light.INTENSITYMODE_ILLUMINANCE:
  23260. photometricScale = 1.0;
  23261. break;
  23262. case Light.INTENSITYMODE_LUMINANCE:
  23263. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  23264. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  23265. var apexAngleRadians = this.radius;
  23266. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  23267. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  23268. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  23269. photometricScale = solidAngle;
  23270. break;
  23271. }
  23272. break;
  23273. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  23274. // No fall off in hemisperic light.
  23275. photometricScale = 1.0;
  23276. break;
  23277. }
  23278. return photometricScale;
  23279. };
  23280. /**
  23281. * Reorder the light in the scene according to their defined priority.
  23282. * @hidden Internal Use Only
  23283. */
  23284. Light.prototype._reorderLightsInScene = function () {
  23285. var scene = this.getScene();
  23286. if (this._renderPriority != 0) {
  23287. scene.requireLightSorting = true;
  23288. }
  23289. this.getScene().sortLightsByPriority();
  23290. };
  23291. /**
  23292. * Falloff Default: light is falling off following the material specification:
  23293. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  23294. */
  23295. Light.FALLOFF_DEFAULT = 0;
  23296. /**
  23297. * Falloff Physical: light is falling off following the inverse squared distance law.
  23298. */
  23299. Light.FALLOFF_PHYSICAL = 1;
  23300. /**
  23301. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  23302. * to enhance interoperability with other engines.
  23303. */
  23304. Light.FALLOFF_GLTF = 2;
  23305. /**
  23306. * Falloff Standard: light is falling off like in the standard material
  23307. * to enhance interoperability with other materials.
  23308. */
  23309. Light.FALLOFF_STANDARD = 3;
  23310. //lightmapMode Consts
  23311. /**
  23312. * If every light affecting the material is in this lightmapMode,
  23313. * material.lightmapTexture adds or multiplies
  23314. * (depends on material.useLightmapAsShadowmap)
  23315. * after every other light calculations.
  23316. */
  23317. Light.LIGHTMAP_DEFAULT = 0;
  23318. /**
  23319. * material.lightmapTexture as only diffuse lighting from this light
  23320. * adds only specular lighting from this light
  23321. * adds dynamic shadows
  23322. */
  23323. Light.LIGHTMAP_SPECULAR = 1;
  23324. /**
  23325. * material.lightmapTexture as only lighting
  23326. * no light calculation from this light
  23327. * only adds dynamic shadows from this light
  23328. */
  23329. Light.LIGHTMAP_SHADOWSONLY = 2;
  23330. // Intensity Mode Consts
  23331. /**
  23332. * Each light type uses the default quantity according to its type:
  23333. * point/spot lights use luminous intensity
  23334. * directional lights use illuminance
  23335. */
  23336. Light.INTENSITYMODE_AUTOMATIC = 0;
  23337. /**
  23338. * lumen (lm)
  23339. */
  23340. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  23341. /**
  23342. * candela (lm/sr)
  23343. */
  23344. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  23345. /**
  23346. * lux (lm/m^2)
  23347. */
  23348. Light.INTENSITYMODE_ILLUMINANCE = 3;
  23349. /**
  23350. * nit (cd/m^2)
  23351. */
  23352. Light.INTENSITYMODE_LUMINANCE = 4;
  23353. // Light types ids const.
  23354. /**
  23355. * Light type const id of the point light.
  23356. */
  23357. Light.LIGHTTYPEID_POINTLIGHT = 0;
  23358. /**
  23359. * Light type const id of the directional light.
  23360. */
  23361. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  23362. /**
  23363. * Light type const id of the spot light.
  23364. */
  23365. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  23366. /**
  23367. * Light type const id of the hemispheric light.
  23368. */
  23369. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  23370. __decorate([
  23371. BABYLON.serializeAsColor3()
  23372. ], Light.prototype, "diffuse", void 0);
  23373. __decorate([
  23374. BABYLON.serializeAsColor3()
  23375. ], Light.prototype, "specular", void 0);
  23376. __decorate([
  23377. BABYLON.serialize()
  23378. ], Light.prototype, "falloffType", void 0);
  23379. __decorate([
  23380. BABYLON.serialize()
  23381. ], Light.prototype, "intensity", void 0);
  23382. __decorate([
  23383. BABYLON.serialize()
  23384. ], Light.prototype, "range", null);
  23385. __decorate([
  23386. BABYLON.serialize()
  23387. ], Light.prototype, "intensityMode", null);
  23388. __decorate([
  23389. BABYLON.serialize()
  23390. ], Light.prototype, "radius", null);
  23391. __decorate([
  23392. BABYLON.serialize()
  23393. ], Light.prototype, "_renderPriority", void 0);
  23394. __decorate([
  23395. BABYLON.expandToProperty("_reorderLightsInScene")
  23396. ], Light.prototype, "renderPriority", void 0);
  23397. __decorate([
  23398. BABYLON.serialize("shadowEnabled")
  23399. ], Light.prototype, "_shadowEnabled", void 0);
  23400. __decorate([
  23401. BABYLON.serialize("excludeWithLayerMask")
  23402. ], Light.prototype, "_excludeWithLayerMask", void 0);
  23403. __decorate([
  23404. BABYLON.serialize("includeOnlyWithLayerMask")
  23405. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  23406. __decorate([
  23407. BABYLON.serialize("lightmapMode")
  23408. ], Light.prototype, "_lightmapMode", void 0);
  23409. return Light;
  23410. }(BABYLON.Node));
  23411. BABYLON.Light = Light;
  23412. })(BABYLON || (BABYLON = {}));
  23413. //# sourceMappingURL=light.js.map
  23414. var BABYLON;
  23415. (function (BABYLON) {
  23416. /**
  23417. * This is the base class of all the camera used in the application.
  23418. * @see http://doc.babylonjs.com/features/cameras
  23419. */
  23420. var Camera = /** @class */ (function (_super) {
  23421. __extends(Camera, _super);
  23422. /**
  23423. * Instantiates a new camera object.
  23424. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  23425. * @see http://doc.babylonjs.com/features/cameras
  23426. * @param name Defines the name of the camera in the scene
  23427. * @param position Defines the position of the camera
  23428. * @param scene Defines the scene the camera belongs too
  23429. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  23430. */
  23431. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  23432. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  23433. var _this = _super.call(this, name, scene) || this;
  23434. /**
  23435. * The vector the camera should consider as up.
  23436. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  23437. */
  23438. _this.upVector = BABYLON.Vector3.Up();
  23439. /**
  23440. * Define the current limit on the left side for an orthographic camera
  23441. * In scene unit
  23442. */
  23443. _this.orthoLeft = null;
  23444. /**
  23445. * Define the current limit on the right side for an orthographic camera
  23446. * In scene unit
  23447. */
  23448. _this.orthoRight = null;
  23449. /**
  23450. * Define the current limit on the bottom side for an orthographic camera
  23451. * In scene unit
  23452. */
  23453. _this.orthoBottom = null;
  23454. /**
  23455. * Define the current limit on the top side for an orthographic camera
  23456. * In scene unit
  23457. */
  23458. _this.orthoTop = null;
  23459. /**
  23460. * Field Of View is set in Radians. (default is 0.8)
  23461. */
  23462. _this.fov = 0.8;
  23463. /**
  23464. * Define the minimum distance the camera can see from.
  23465. * This is important to note that the depth buffer are not infinite and the closer it starts
  23466. * the more your scene might encounter depth fighting issue.
  23467. */
  23468. _this.minZ = 1;
  23469. /**
  23470. * Define the maximum distance the camera can see to.
  23471. * This is important to note that the depth buffer are not infinite and the further it end
  23472. * the more your scene might encounter depth fighting issue.
  23473. */
  23474. _this.maxZ = 10000.0;
  23475. /**
  23476. * Define the default inertia of the camera.
  23477. * This helps giving a smooth feeling to the camera movement.
  23478. */
  23479. _this.inertia = 0.9;
  23480. /**
  23481. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  23482. */
  23483. _this.mode = Camera.PERSPECTIVE_CAMERA;
  23484. /**
  23485. * Define wether the camera is intermediate.
  23486. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  23487. */
  23488. _this.isIntermediate = false;
  23489. /**
  23490. * Define the viewport of the camera.
  23491. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  23492. */
  23493. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  23494. /**
  23495. * Restricts the camera to viewing objects with the same layerMask.
  23496. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  23497. */
  23498. _this.layerMask = 0x0FFFFFFF;
  23499. /**
  23500. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  23501. */
  23502. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  23503. /**
  23504. * Rig mode of the camera.
  23505. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  23506. * This is normally controlled byt the camera themselves as internal use.
  23507. */
  23508. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  23509. /**
  23510. * Defines the list of custom render target which are rendered to and then used as the input to this camera's render. Eg. display another camera view on a TV in the main scene
  23511. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  23512. * else in the scene.
  23513. */
  23514. _this.customRenderTargets = new Array();
  23515. /**
  23516. * When set, the camera will render to this render target instead of the default canvas
  23517. */
  23518. _this.outputRenderTarget = null;
  23519. /**
  23520. * Observable triggered when the camera view matrix has changed.
  23521. */
  23522. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  23523. /**
  23524. * Observable triggered when the camera Projection matrix has changed.
  23525. */
  23526. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  23527. /**
  23528. * Observable triggered when the inputs have been processed.
  23529. */
  23530. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  23531. /**
  23532. * Observable triggered when reset has been called and applied to the camera.
  23533. */
  23534. _this.onRestoreStateObservable = new BABYLON.Observable();
  23535. /** @hidden */
  23536. _this._rigCameras = new Array();
  23537. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  23538. /** @hidden */
  23539. _this._skipRendering = false;
  23540. /** @hidden */
  23541. _this._projectionMatrix = new BABYLON.Matrix();
  23542. /** @hidden */
  23543. _this._postProcesses = new Array();
  23544. /** @hidden */
  23545. _this._activeMeshes = new BABYLON.SmartArray(256);
  23546. _this._globalPosition = BABYLON.Vector3.Zero();
  23547. /** hidden */
  23548. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  23549. _this._doNotComputeProjectionMatrix = false;
  23550. _this._transformMatrix = BABYLON.Matrix.Zero();
  23551. _this._refreshFrustumPlanes = true;
  23552. _this.getScene().addCamera(_this);
  23553. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  23554. _this.getScene().activeCamera = _this;
  23555. }
  23556. _this.position = position;
  23557. return _this;
  23558. }
  23559. /**
  23560. * Store current camera state (fov, position, etc..)
  23561. * @returns the camera
  23562. */
  23563. Camera.prototype.storeState = function () {
  23564. this._stateStored = true;
  23565. this._storedFov = this.fov;
  23566. return this;
  23567. };
  23568. /**
  23569. * Restores the camera state values if it has been stored. You must call storeState() first
  23570. */
  23571. Camera.prototype._restoreStateValues = function () {
  23572. if (!this._stateStored) {
  23573. return false;
  23574. }
  23575. this.fov = this._storedFov;
  23576. return true;
  23577. };
  23578. /**
  23579. * Restored camera state. You must call storeState() first.
  23580. * @returns true if restored and false otherwise
  23581. */
  23582. Camera.prototype.restoreState = function () {
  23583. if (this._restoreStateValues()) {
  23584. this.onRestoreStateObservable.notifyObservers(this);
  23585. return true;
  23586. }
  23587. return false;
  23588. };
  23589. /**
  23590. * Gets the class name of the camera.
  23591. * @returns the class name
  23592. */
  23593. Camera.prototype.getClassName = function () {
  23594. return "Camera";
  23595. };
  23596. /**
  23597. * Gets a string representation of the camera usefull for debug purpose.
  23598. * @param fullDetails Defines that a more verboe level of logging is required
  23599. * @returns the string representation
  23600. */
  23601. Camera.prototype.toString = function (fullDetails) {
  23602. var ret = "Name: " + this.name;
  23603. ret += ", type: " + this.getClassName();
  23604. if (this.animations) {
  23605. for (var i = 0; i < this.animations.length; i++) {
  23606. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23607. }
  23608. }
  23609. if (fullDetails) {
  23610. }
  23611. return ret;
  23612. };
  23613. Object.defineProperty(Camera.prototype, "globalPosition", {
  23614. /**
  23615. * Gets the current world space position of the camera.
  23616. */
  23617. get: function () {
  23618. return this._globalPosition;
  23619. },
  23620. enumerable: true,
  23621. configurable: true
  23622. });
  23623. /**
  23624. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  23625. * @returns the active meshe list
  23626. */
  23627. Camera.prototype.getActiveMeshes = function () {
  23628. return this._activeMeshes;
  23629. };
  23630. /**
  23631. * Check wether a mesh is part of the current active mesh list of the camera
  23632. * @param mesh Defines the mesh to check
  23633. * @returns true if active, false otherwise
  23634. */
  23635. Camera.prototype.isActiveMesh = function (mesh) {
  23636. return (this._activeMeshes.indexOf(mesh) !== -1);
  23637. };
  23638. /**
  23639. * Is this camera ready to be used/rendered
  23640. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  23641. * @return true if the camera is ready
  23642. */
  23643. Camera.prototype.isReady = function (completeCheck) {
  23644. if (completeCheck === void 0) { completeCheck = false; }
  23645. if (completeCheck) {
  23646. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  23647. var pp = _a[_i];
  23648. if (pp && !pp.isReady()) {
  23649. return false;
  23650. }
  23651. }
  23652. }
  23653. return _super.prototype.isReady.call(this, completeCheck);
  23654. };
  23655. /** @hidden */
  23656. Camera.prototype._initCache = function () {
  23657. _super.prototype._initCache.call(this);
  23658. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23659. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23660. this._cache.mode = undefined;
  23661. this._cache.minZ = undefined;
  23662. this._cache.maxZ = undefined;
  23663. this._cache.fov = undefined;
  23664. this._cache.fovMode = undefined;
  23665. this._cache.aspectRatio = undefined;
  23666. this._cache.orthoLeft = undefined;
  23667. this._cache.orthoRight = undefined;
  23668. this._cache.orthoBottom = undefined;
  23669. this._cache.orthoTop = undefined;
  23670. this._cache.renderWidth = undefined;
  23671. this._cache.renderHeight = undefined;
  23672. };
  23673. /** @hidden */
  23674. Camera.prototype._updateCache = function (ignoreParentClass) {
  23675. if (!ignoreParentClass) {
  23676. _super.prototype._updateCache.call(this);
  23677. }
  23678. this._cache.position.copyFrom(this.position);
  23679. this._cache.upVector.copyFrom(this.upVector);
  23680. };
  23681. /** @hidden */
  23682. Camera.prototype._isSynchronized = function () {
  23683. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  23684. };
  23685. /** @hidden */
  23686. Camera.prototype._isSynchronizedViewMatrix = function () {
  23687. if (!_super.prototype._isSynchronized.call(this)) {
  23688. return false;
  23689. }
  23690. return this._cache.position.equals(this.position)
  23691. && this._cache.upVector.equals(this.upVector)
  23692. && this.isSynchronizedWithParent();
  23693. };
  23694. /** @hidden */
  23695. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  23696. var check = this._cache.mode === this.mode
  23697. && this._cache.minZ === this.minZ
  23698. && this._cache.maxZ === this.maxZ;
  23699. if (!check) {
  23700. return false;
  23701. }
  23702. var engine = this.getEngine();
  23703. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23704. check = this._cache.fov === this.fov
  23705. && this._cache.fovMode === this.fovMode
  23706. && this._cache.aspectRatio === engine.getAspectRatio(this);
  23707. }
  23708. else {
  23709. check = this._cache.orthoLeft === this.orthoLeft
  23710. && this._cache.orthoRight === this.orthoRight
  23711. && this._cache.orthoBottom === this.orthoBottom
  23712. && this._cache.orthoTop === this.orthoTop
  23713. && this._cache.renderWidth === engine.getRenderWidth()
  23714. && this._cache.renderHeight === engine.getRenderHeight();
  23715. }
  23716. return check;
  23717. };
  23718. /**
  23719. * Attach the input controls to a specific dom element to get the input from.
  23720. * @param element Defines the element the controls should be listened from
  23721. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  23722. */
  23723. Camera.prototype.attachControl = function (element, noPreventDefault) {
  23724. };
  23725. /**
  23726. * Detach the current controls from the specified dom element.
  23727. * @param element Defines the element to stop listening the inputs from
  23728. */
  23729. Camera.prototype.detachControl = function (element) {
  23730. };
  23731. /**
  23732. * Update the camera state according to the different inputs gathered during the frame.
  23733. */
  23734. Camera.prototype.update = function () {
  23735. this._checkInputs();
  23736. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23737. this._updateRigCameras();
  23738. }
  23739. };
  23740. /** @hidden */
  23741. Camera.prototype._checkInputs = function () {
  23742. this.onAfterCheckInputsObservable.notifyObservers(this);
  23743. };
  23744. Object.defineProperty(Camera.prototype, "rigCameras", {
  23745. /** @hidden */
  23746. get: function () {
  23747. return this._rigCameras;
  23748. },
  23749. enumerable: true,
  23750. configurable: true
  23751. });
  23752. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  23753. /**
  23754. * Gets the post process used by the rig cameras
  23755. */
  23756. get: function () {
  23757. return this._rigPostProcess;
  23758. },
  23759. enumerable: true,
  23760. configurable: true
  23761. });
  23762. /**
  23763. * Internal, gets the first post proces.
  23764. * @returns the first post process to be run on this camera.
  23765. */
  23766. Camera.prototype._getFirstPostProcess = function () {
  23767. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  23768. if (this._postProcesses[ppIndex] !== null) {
  23769. return this._postProcesses[ppIndex];
  23770. }
  23771. }
  23772. return null;
  23773. };
  23774. Camera.prototype._cascadePostProcessesToRigCams = function () {
  23775. // invalidate framebuffer
  23776. var firstPostProcess = this._getFirstPostProcess();
  23777. if (firstPostProcess) {
  23778. firstPostProcess.markTextureDirty();
  23779. }
  23780. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  23781. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  23782. var cam = this._rigCameras[i];
  23783. var rigPostProcess = cam._rigPostProcess;
  23784. // for VR rig, there does not have to be a post process
  23785. if (rigPostProcess) {
  23786. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  23787. if (isPass) {
  23788. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  23789. cam.isIntermediate = this._postProcesses.length === 0;
  23790. }
  23791. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  23792. rigPostProcess.markTextureDirty();
  23793. }
  23794. else {
  23795. cam._postProcesses = this._postProcesses.slice(0);
  23796. }
  23797. }
  23798. };
  23799. /**
  23800. * Attach a post process to the camera.
  23801. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23802. * @param postProcess The post process to attach to the camera
  23803. * @param insertAt The position of the post process in case several of them are in use in the scene
  23804. * @returns the position the post process has been inserted at
  23805. */
  23806. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  23807. if (insertAt === void 0) { insertAt = null; }
  23808. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  23809. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  23810. return 0;
  23811. }
  23812. if (insertAt == null || insertAt < 0) {
  23813. this._postProcesses.push(postProcess);
  23814. }
  23815. else if (this._postProcesses[insertAt] === null) {
  23816. this._postProcesses[insertAt] = postProcess;
  23817. }
  23818. else {
  23819. this._postProcesses.splice(insertAt, 0, postProcess);
  23820. }
  23821. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23822. return this._postProcesses.indexOf(postProcess);
  23823. };
  23824. /**
  23825. * Detach a post process to the camera.
  23826. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23827. * @param postProcess The post process to detach from the camera
  23828. */
  23829. Camera.prototype.detachPostProcess = function (postProcess) {
  23830. var idx = this._postProcesses.indexOf(postProcess);
  23831. if (idx !== -1) {
  23832. this._postProcesses[idx] = null;
  23833. }
  23834. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23835. };
  23836. /**
  23837. * Gets the current world matrix of the camera
  23838. */
  23839. Camera.prototype.getWorldMatrix = function () {
  23840. if (this._isSynchronizedViewMatrix()) {
  23841. return this._worldMatrix;
  23842. }
  23843. // Getting the the view matrix will also compute the world matrix.
  23844. this.getViewMatrix();
  23845. return this._worldMatrix;
  23846. };
  23847. /** @hidden */
  23848. Camera.prototype._getViewMatrix = function () {
  23849. return BABYLON.Matrix.Identity();
  23850. };
  23851. /**
  23852. * Gets the current view matrix of the camera.
  23853. * @param force forces the camera to recompute the matrix without looking at the cached state
  23854. * @returns the view matrix
  23855. */
  23856. Camera.prototype.getViewMatrix = function (force) {
  23857. if (!force && this._isSynchronizedViewMatrix()) {
  23858. return this._computedViewMatrix;
  23859. }
  23860. this.updateCache();
  23861. this._computedViewMatrix = this._getViewMatrix();
  23862. this._currentRenderId = this.getScene().getRenderId();
  23863. this._childRenderId = this._currentRenderId;
  23864. this._refreshFrustumPlanes = true;
  23865. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  23866. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  23867. }
  23868. this.onViewMatrixChangedObservable.notifyObservers(this);
  23869. this._computedViewMatrix.invertToRef(this._worldMatrix);
  23870. return this._computedViewMatrix;
  23871. };
  23872. /**
  23873. * Freeze the projection matrix.
  23874. * It will prevent the cache check of the camera projection compute and can speed up perf
  23875. * if no parameter of the camera are meant to change
  23876. * @param projection Defines manually a projection if necessary
  23877. */
  23878. Camera.prototype.freezeProjectionMatrix = function (projection) {
  23879. this._doNotComputeProjectionMatrix = true;
  23880. if (projection !== undefined) {
  23881. this._projectionMatrix = projection;
  23882. }
  23883. };
  23884. /**
  23885. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  23886. */
  23887. Camera.prototype.unfreezeProjectionMatrix = function () {
  23888. this._doNotComputeProjectionMatrix = false;
  23889. };
  23890. /**
  23891. * Gets the current projection matrix of the camera.
  23892. * @param force forces the camera to recompute the matrix without looking at the cached state
  23893. * @returns the projection matrix
  23894. */
  23895. Camera.prototype.getProjectionMatrix = function (force) {
  23896. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  23897. return this._projectionMatrix;
  23898. }
  23899. // Cache
  23900. this._cache.mode = this.mode;
  23901. this._cache.minZ = this.minZ;
  23902. this._cache.maxZ = this.maxZ;
  23903. // Matrix
  23904. this._refreshFrustumPlanes = true;
  23905. var engine = this.getEngine();
  23906. var scene = this.getScene();
  23907. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23908. this._cache.fov = this.fov;
  23909. this._cache.fovMode = this.fovMode;
  23910. this._cache.aspectRatio = engine.getAspectRatio(this);
  23911. if (this.minZ <= 0) {
  23912. this.minZ = 0.1;
  23913. }
  23914. if (scene.useRightHandedSystem) {
  23915. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23916. }
  23917. else {
  23918. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23919. }
  23920. }
  23921. else {
  23922. var halfWidth = engine.getRenderWidth() / 2.0;
  23923. var halfHeight = engine.getRenderHeight() / 2.0;
  23924. if (scene.useRightHandedSystem) {
  23925. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23926. }
  23927. else {
  23928. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23929. }
  23930. this._cache.orthoLeft = this.orthoLeft;
  23931. this._cache.orthoRight = this.orthoRight;
  23932. this._cache.orthoBottom = this.orthoBottom;
  23933. this._cache.orthoTop = this.orthoTop;
  23934. this._cache.renderWidth = engine.getRenderWidth();
  23935. this._cache.renderHeight = engine.getRenderHeight();
  23936. }
  23937. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  23938. return this._projectionMatrix;
  23939. };
  23940. /**
  23941. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  23942. * @returns a Matrix
  23943. */
  23944. Camera.prototype.getTransformationMatrix = function () {
  23945. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23946. return this._transformMatrix;
  23947. };
  23948. Camera.prototype._updateFrustumPlanes = function () {
  23949. if (!this._refreshFrustumPlanes) {
  23950. return;
  23951. }
  23952. this.getTransformationMatrix();
  23953. if (!this._frustumPlanes) {
  23954. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23955. }
  23956. else {
  23957. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23958. }
  23959. this._refreshFrustumPlanes = false;
  23960. };
  23961. /**
  23962. * Checks if a cullable object (mesh...) is in the camera frustum
  23963. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  23964. * @param target The object to check
  23965. * @returns true if the object is in frustum otherwise false
  23966. */
  23967. Camera.prototype.isInFrustum = function (target) {
  23968. this._updateFrustumPlanes();
  23969. return target.isInFrustum(this._frustumPlanes);
  23970. };
  23971. /**
  23972. * Checks if a cullable object (mesh...) is in the camera frustum
  23973. * Unlike isInFrustum this cheks the full bounding box
  23974. * @param target The object to check
  23975. * @returns true if the object is in frustum otherwise false
  23976. */
  23977. Camera.prototype.isCompletelyInFrustum = function (target) {
  23978. this._updateFrustumPlanes();
  23979. return target.isCompletelyInFrustum(this._frustumPlanes);
  23980. };
  23981. /**
  23982. * Gets a ray in the forward direction from the camera.
  23983. * @param length Defines the length of the ray to create
  23984. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  23985. * @param origin Defines the start point of the ray which defaults to the camera position
  23986. * @returns the forward ray
  23987. */
  23988. Camera.prototype.getForwardRay = function (length, transform, origin) {
  23989. if (length === void 0) { length = 100; }
  23990. if (!transform) {
  23991. transform = this.getWorldMatrix();
  23992. }
  23993. if (!origin) {
  23994. origin = this.position;
  23995. }
  23996. var forward = this._scene.useRightHandedSystem ? new BABYLON.Vector3(0, 0, -1) : new BABYLON.Vector3(0, 0, 1);
  23997. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  23998. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  23999. return new BABYLON.Ray(origin, direction, length);
  24000. };
  24001. /**
  24002. * Releases resources associated with this node.
  24003. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  24004. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  24005. */
  24006. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  24007. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  24008. // Observables
  24009. this.onViewMatrixChangedObservable.clear();
  24010. this.onProjectionMatrixChangedObservable.clear();
  24011. this.onAfterCheckInputsObservable.clear();
  24012. this.onRestoreStateObservable.clear();
  24013. // Inputs
  24014. if (this.inputs) {
  24015. this.inputs.clear();
  24016. }
  24017. // Animations
  24018. this.getScene().stopAnimation(this);
  24019. // Remove from scene
  24020. this.getScene().removeCamera(this);
  24021. while (this._rigCameras.length > 0) {
  24022. var camera = this._rigCameras.pop();
  24023. if (camera) {
  24024. camera.dispose();
  24025. }
  24026. }
  24027. // Postprocesses
  24028. if (this._rigPostProcess) {
  24029. this._rigPostProcess.dispose(this);
  24030. this._rigPostProcess = null;
  24031. this._postProcesses = [];
  24032. }
  24033. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  24034. this._rigPostProcess = null;
  24035. this._postProcesses = [];
  24036. }
  24037. else {
  24038. var i = this._postProcesses.length;
  24039. while (--i >= 0) {
  24040. var postProcess = this._postProcesses[i];
  24041. if (postProcess) {
  24042. postProcess.dispose(this);
  24043. }
  24044. }
  24045. }
  24046. // Render targets
  24047. var i = this.customRenderTargets.length;
  24048. while (--i >= 0) {
  24049. this.customRenderTargets[i].dispose();
  24050. }
  24051. this.customRenderTargets = [];
  24052. // Active Meshes
  24053. this._activeMeshes.dispose();
  24054. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  24055. };
  24056. Object.defineProperty(Camera.prototype, "leftCamera", {
  24057. /**
  24058. * Gets the left camera of a rig setup in case of Rigged Camera
  24059. */
  24060. get: function () {
  24061. if (this._rigCameras.length < 1) {
  24062. return null;
  24063. }
  24064. return this._rigCameras[0];
  24065. },
  24066. enumerable: true,
  24067. configurable: true
  24068. });
  24069. Object.defineProperty(Camera.prototype, "rightCamera", {
  24070. /**
  24071. * Gets the right camera of a rig setup in case of Rigged Camera
  24072. */
  24073. get: function () {
  24074. if (this._rigCameras.length < 2) {
  24075. return null;
  24076. }
  24077. return this._rigCameras[1];
  24078. },
  24079. enumerable: true,
  24080. configurable: true
  24081. });
  24082. /**
  24083. * Gets the left camera target of a rig setup in case of Rigged Camera
  24084. * @returns the target position
  24085. */
  24086. Camera.prototype.getLeftTarget = function () {
  24087. if (this._rigCameras.length < 1) {
  24088. return null;
  24089. }
  24090. return this._rigCameras[0].getTarget();
  24091. };
  24092. /**
  24093. * Gets the right camera target of a rig setup in case of Rigged Camera
  24094. * @returns the target position
  24095. */
  24096. Camera.prototype.getRightTarget = function () {
  24097. if (this._rigCameras.length < 2) {
  24098. return null;
  24099. }
  24100. return this._rigCameras[1].getTarget();
  24101. };
  24102. /**
  24103. * @hidden
  24104. */
  24105. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  24106. if (this.cameraRigMode === mode) {
  24107. return;
  24108. }
  24109. while (this._rigCameras.length > 0) {
  24110. var camera = this._rigCameras.pop();
  24111. if (camera) {
  24112. camera.dispose();
  24113. }
  24114. }
  24115. this.cameraRigMode = mode;
  24116. this._cameraRigParams = {};
  24117. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  24118. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  24119. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  24120. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  24121. // create the rig cameras, unless none
  24122. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  24123. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  24124. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  24125. if (leftCamera && rightCamera) {
  24126. this._rigCameras.push(leftCamera);
  24127. this._rigCameras.push(rightCamera);
  24128. }
  24129. }
  24130. switch (this.cameraRigMode) {
  24131. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  24132. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  24133. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  24134. break;
  24135. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  24136. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  24137. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  24138. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  24139. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  24140. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  24141. break;
  24142. case Camera.RIG_MODE_VR:
  24143. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  24144. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  24145. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  24146. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24147. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  24148. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  24149. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  24150. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  24151. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  24152. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24153. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  24154. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  24155. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  24156. if (metrics.compensateDistortion) {
  24157. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  24158. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  24159. }
  24160. break;
  24161. case Camera.RIG_MODE_WEBVR:
  24162. if (rigParams.vrDisplay) {
  24163. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  24164. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  24165. //Left eye
  24166. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  24167. this._rigCameras[0].setCameraRigParameter("left", true);
  24168. //leaving this for future reference
  24169. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  24170. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  24171. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  24172. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  24173. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24174. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  24175. this._rigCameras[0].parent = this;
  24176. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  24177. //Right eye
  24178. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  24179. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  24180. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  24181. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  24182. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  24183. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  24184. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  24185. this._rigCameras[1].parent = this;
  24186. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  24187. if (Camera.UseAlternateWebVRRendering) {
  24188. this._rigCameras[1]._skipRendering = true;
  24189. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  24190. }
  24191. }
  24192. break;
  24193. }
  24194. this._cascadePostProcessesToRigCams();
  24195. this.update();
  24196. };
  24197. Camera.prototype._getVRProjectionMatrix = function () {
  24198. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  24199. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  24200. return this._projectionMatrix;
  24201. };
  24202. Camera.prototype._updateCameraRotationMatrix = function () {
  24203. //Here for WebVR
  24204. };
  24205. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  24206. //Here for WebVR
  24207. };
  24208. /**
  24209. * This function MUST be overwritten by the different WebVR cameras available.
  24210. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  24211. */
  24212. Camera.prototype._getWebVRProjectionMatrix = function () {
  24213. return BABYLON.Matrix.Identity();
  24214. };
  24215. /**
  24216. * This function MUST be overwritten by the different WebVR cameras available.
  24217. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  24218. */
  24219. Camera.prototype._getWebVRViewMatrix = function () {
  24220. return BABYLON.Matrix.Identity();
  24221. };
  24222. /** @hidden */
  24223. Camera.prototype.setCameraRigParameter = function (name, value) {
  24224. if (!this._cameraRigParams) {
  24225. this._cameraRigParams = {};
  24226. }
  24227. this._cameraRigParams[name] = value;
  24228. //provisionnally:
  24229. if (name === "interaxialDistance") {
  24230. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  24231. }
  24232. };
  24233. /**
  24234. * needs to be overridden by children so sub has required properties to be copied
  24235. * @hidden
  24236. */
  24237. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  24238. return null;
  24239. };
  24240. /**
  24241. * May need to be overridden by children
  24242. * @hidden
  24243. */
  24244. Camera.prototype._updateRigCameras = function () {
  24245. for (var i = 0; i < this._rigCameras.length; i++) {
  24246. this._rigCameras[i].minZ = this.minZ;
  24247. this._rigCameras[i].maxZ = this.maxZ;
  24248. this._rigCameras[i].fov = this.fov;
  24249. }
  24250. // only update viewport when ANAGLYPH
  24251. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  24252. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  24253. }
  24254. };
  24255. /** @hidden */
  24256. Camera.prototype._setupInputs = function () {
  24257. };
  24258. /**
  24259. * Serialiaze the camera setup to a json represention
  24260. * @returns the JSON representation
  24261. */
  24262. Camera.prototype.serialize = function () {
  24263. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24264. // Type
  24265. serializationObject.type = this.getClassName();
  24266. // Parent
  24267. if (this.parent) {
  24268. serializationObject.parentId = this.parent.id;
  24269. }
  24270. if (this.inputs) {
  24271. this.inputs.serialize(serializationObject);
  24272. }
  24273. // Animations
  24274. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24275. serializationObject.ranges = this.serializeAnimationRanges();
  24276. return serializationObject;
  24277. };
  24278. /**
  24279. * Clones the current camera.
  24280. * @param name The cloned camera name
  24281. * @returns the cloned camera
  24282. */
  24283. Camera.prototype.clone = function (name) {
  24284. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  24285. };
  24286. /**
  24287. * Gets the direction of the camera relative to a given local axis.
  24288. * @param localAxis Defines the reference axis to provide a relative direction.
  24289. * @return the direction
  24290. */
  24291. Camera.prototype.getDirection = function (localAxis) {
  24292. var result = BABYLON.Vector3.Zero();
  24293. this.getDirectionToRef(localAxis, result);
  24294. return result;
  24295. };
  24296. /**
  24297. * Gets the direction of the camera relative to a given local axis into a passed vector.
  24298. * @param localAxis Defines the reference axis to provide a relative direction.
  24299. * @param result Defines the vector to store the result in
  24300. */
  24301. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  24302. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  24303. };
  24304. /**
  24305. * Gets a camera constructor for a given camera type
  24306. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  24307. * @param name The name of the camera the result will be able to instantiate
  24308. * @param scene The scene the result will construct the camera in
  24309. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  24310. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  24311. * @returns a factory method to construc the camera
  24312. */
  24313. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  24314. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  24315. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  24316. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  24317. interaxial_distance: interaxial_distance,
  24318. isStereoscopicSideBySide: isStereoscopicSideBySide
  24319. });
  24320. if (constructorFunc) {
  24321. return constructorFunc;
  24322. }
  24323. // Default to universal camera
  24324. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  24325. };
  24326. /**
  24327. * Compute the world matrix of the camera.
  24328. * @returns the camera workd matrix
  24329. */
  24330. Camera.prototype.computeWorldMatrix = function () {
  24331. return this.getWorldMatrix();
  24332. };
  24333. /**
  24334. * Parse a JSON and creates the camera from the parsed information
  24335. * @param parsedCamera The JSON to parse
  24336. * @param scene The scene to instantiate the camera in
  24337. * @returns the newly constructed camera
  24338. */
  24339. Camera.Parse = function (parsedCamera, scene) {
  24340. var type = parsedCamera.type;
  24341. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  24342. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  24343. // Parent
  24344. if (parsedCamera.parentId) {
  24345. camera._waitingParentId = parsedCamera.parentId;
  24346. }
  24347. //If camera has an input manager, let it parse inputs settings
  24348. if (camera.inputs) {
  24349. camera.inputs.parse(parsedCamera);
  24350. camera._setupInputs();
  24351. }
  24352. if (camera.setPosition) { // need to force position
  24353. camera.position.copyFromFloats(0, 0, 0);
  24354. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  24355. }
  24356. // Target
  24357. if (parsedCamera.target) {
  24358. if (camera.setTarget) {
  24359. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  24360. }
  24361. }
  24362. // Apply 3d rig, when found
  24363. if (parsedCamera.cameraRigMode) {
  24364. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  24365. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  24366. }
  24367. // Animations
  24368. if (parsedCamera.animations) {
  24369. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  24370. var parsedAnimation = parsedCamera.animations[animationIndex];
  24371. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24372. }
  24373. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  24374. }
  24375. if (parsedCamera.autoAnimate) {
  24376. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  24377. }
  24378. return camera;
  24379. };
  24380. /**
  24381. * This is the default projection mode used by the cameras.
  24382. * It helps recreating a feeling of perspective and better appreciate depth.
  24383. * This is the best way to simulate real life cameras.
  24384. */
  24385. Camera.PERSPECTIVE_CAMERA = 0;
  24386. /**
  24387. * This helps creating camera with an orthographic mode.
  24388. * 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.
  24389. */
  24390. Camera.ORTHOGRAPHIC_CAMERA = 1;
  24391. /**
  24392. * This is the default FOV mode for perspective cameras.
  24393. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  24394. */
  24395. Camera.FOVMODE_VERTICAL_FIXED = 0;
  24396. /**
  24397. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  24398. */
  24399. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  24400. /**
  24401. * This specifies ther is no need for a camera rig.
  24402. * Basically only one eye is rendered corresponding to the camera.
  24403. */
  24404. Camera.RIG_MODE_NONE = 0;
  24405. /**
  24406. * Simulates a camera Rig with one blue eye and one red eye.
  24407. * This can be use with 3d blue and red glasses.
  24408. */
  24409. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  24410. /**
  24411. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  24412. */
  24413. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  24414. /**
  24415. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  24416. */
  24417. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  24418. /**
  24419. * Defines that both eyes of the camera will be rendered over under each other.
  24420. */
  24421. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  24422. /**
  24423. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  24424. */
  24425. Camera.RIG_MODE_VR = 20;
  24426. /**
  24427. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  24428. */
  24429. Camera.RIG_MODE_WEBVR = 21;
  24430. /**
  24431. * Custom rig mode allowing rig cameras to be populated manually with any number of cameras
  24432. */
  24433. Camera.RIG_MODE_CUSTOM = 22;
  24434. /**
  24435. * Defines if by default attaching controls should prevent the default javascript event to continue.
  24436. */
  24437. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  24438. /**
  24439. * @hidden
  24440. * Might be removed once multiview will be a thing
  24441. */
  24442. Camera.UseAlternateWebVRRendering = false;
  24443. __decorate([
  24444. BABYLON.serializeAsVector3()
  24445. ], Camera.prototype, "position", void 0);
  24446. __decorate([
  24447. BABYLON.serializeAsVector3()
  24448. ], Camera.prototype, "upVector", void 0);
  24449. __decorate([
  24450. BABYLON.serialize()
  24451. ], Camera.prototype, "orthoLeft", void 0);
  24452. __decorate([
  24453. BABYLON.serialize()
  24454. ], Camera.prototype, "orthoRight", void 0);
  24455. __decorate([
  24456. BABYLON.serialize()
  24457. ], Camera.prototype, "orthoBottom", void 0);
  24458. __decorate([
  24459. BABYLON.serialize()
  24460. ], Camera.prototype, "orthoTop", void 0);
  24461. __decorate([
  24462. BABYLON.serialize()
  24463. ], Camera.prototype, "fov", void 0);
  24464. __decorate([
  24465. BABYLON.serialize()
  24466. ], Camera.prototype, "minZ", void 0);
  24467. __decorate([
  24468. BABYLON.serialize()
  24469. ], Camera.prototype, "maxZ", void 0);
  24470. __decorate([
  24471. BABYLON.serialize()
  24472. ], Camera.prototype, "inertia", void 0);
  24473. __decorate([
  24474. BABYLON.serialize()
  24475. ], Camera.prototype, "mode", void 0);
  24476. __decorate([
  24477. BABYLON.serialize()
  24478. ], Camera.prototype, "layerMask", void 0);
  24479. __decorate([
  24480. BABYLON.serialize()
  24481. ], Camera.prototype, "fovMode", void 0);
  24482. __decorate([
  24483. BABYLON.serialize()
  24484. ], Camera.prototype, "cameraRigMode", void 0);
  24485. __decorate([
  24486. BABYLON.serialize()
  24487. ], Camera.prototype, "interaxialDistance", void 0);
  24488. __decorate([
  24489. BABYLON.serialize()
  24490. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  24491. return Camera;
  24492. }(BABYLON.Node));
  24493. BABYLON.Camera = Camera;
  24494. })(BABYLON || (BABYLON = {}));
  24495. //# sourceMappingURL=camera.js.map
  24496. var BABYLON;
  24497. (function (BABYLON) {
  24498. /**
  24499. * This is the manager responsible of all the rendering for meshes sprites and particles.
  24500. * It is enable to manage the different groups as well as the different necessary sort functions.
  24501. * This should not be used directly aside of the few static configurations
  24502. */
  24503. var RenderingManager = /** @class */ (function () {
  24504. /**
  24505. * Instantiates a new rendering group for a particular scene
  24506. * @param scene Defines the scene the groups belongs to
  24507. */
  24508. function RenderingManager(scene) {
  24509. /**
  24510. * @hidden
  24511. */
  24512. this._useSceneAutoClearSetup = false;
  24513. this._renderingGroups = new Array();
  24514. this._autoClearDepthStencil = {};
  24515. this._customOpaqueSortCompareFn = {};
  24516. this._customAlphaTestSortCompareFn = {};
  24517. this._customTransparentSortCompareFn = {};
  24518. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  24519. this._scene = scene;
  24520. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  24521. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  24522. }
  24523. }
  24524. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  24525. if (depth === void 0) { depth = true; }
  24526. if (stencil === void 0) { stencil = true; }
  24527. if (this._depthStencilBufferAlreadyCleaned) {
  24528. return;
  24529. }
  24530. this._scene.getEngine().clear(null, false, depth, stencil);
  24531. this._depthStencilBufferAlreadyCleaned = true;
  24532. };
  24533. /**
  24534. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  24535. * @hidden
  24536. */
  24537. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  24538. // Update the observable context (not null as it only goes away on dispose)
  24539. var info = this._renderingGroupInfo;
  24540. info.scene = this._scene;
  24541. info.camera = this._scene.activeCamera;
  24542. // Dispatch sprites
  24543. if (this._scene.spriteManagers && renderSprites) {
  24544. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  24545. var manager = this._scene.spriteManagers[index];
  24546. this.dispatchSprites(manager);
  24547. }
  24548. }
  24549. // Render
  24550. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24551. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  24552. var renderingGroup = this._renderingGroups[index];
  24553. if (!renderingGroup) {
  24554. continue;
  24555. }
  24556. var renderingGroupMask = Math.pow(2, index);
  24557. info.renderingGroupId = index;
  24558. // Before Observable
  24559. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24560. // Clear depth/stencil if needed
  24561. if (RenderingManager.AUTOCLEAR) {
  24562. var autoClear = this._useSceneAutoClearSetup ?
  24563. this._scene.getAutoClearDepthStencilSetup(index) :
  24564. this._autoClearDepthStencil[index];
  24565. if (autoClear && autoClear.autoClear) {
  24566. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  24567. }
  24568. }
  24569. // Render
  24570. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  24571. var step = _a[_i];
  24572. step.action(index);
  24573. }
  24574. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  24575. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  24576. var step = _c[_b];
  24577. step.action(index);
  24578. }
  24579. // After Observable
  24580. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24581. }
  24582. };
  24583. /**
  24584. * Resets the different information of the group to prepare a new frame
  24585. * @hidden
  24586. */
  24587. RenderingManager.prototype.reset = function () {
  24588. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24589. var renderingGroup = this._renderingGroups[index];
  24590. if (renderingGroup) {
  24591. renderingGroup.prepare();
  24592. }
  24593. }
  24594. };
  24595. /**
  24596. * Dispose and release the group and its associated resources.
  24597. * @hidden
  24598. */
  24599. RenderingManager.prototype.dispose = function () {
  24600. this.freeRenderingGroups();
  24601. this._renderingGroups.length = 0;
  24602. this._renderingGroupInfo = null;
  24603. };
  24604. /**
  24605. * Clear the info related to rendering groups preventing retention points during dispose.
  24606. */
  24607. RenderingManager.prototype.freeRenderingGroups = function () {
  24608. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24609. var renderingGroup = this._renderingGroups[index];
  24610. if (renderingGroup) {
  24611. renderingGroup.dispose();
  24612. }
  24613. }
  24614. };
  24615. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  24616. if (this._renderingGroups[renderingGroupId] === undefined) {
  24617. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  24618. }
  24619. };
  24620. /**
  24621. * Add a sprite manager to the rendering manager in order to render it this frame.
  24622. * @param spriteManager Define the sprite manager to render
  24623. */
  24624. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  24625. var renderingGroupId = spriteManager.renderingGroupId || 0;
  24626. this._prepareRenderingGroup(renderingGroupId);
  24627. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  24628. };
  24629. /**
  24630. * Add a particle system to the rendering manager in order to render it this frame.
  24631. * @param particleSystem Define the particle system to render
  24632. */
  24633. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  24634. var renderingGroupId = particleSystem.renderingGroupId || 0;
  24635. this._prepareRenderingGroup(renderingGroupId);
  24636. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  24637. };
  24638. /**
  24639. * Add a submesh to the manager in order to render it this frame
  24640. * @param subMesh The submesh to dispatch
  24641. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24642. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24643. */
  24644. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  24645. if (mesh === undefined) {
  24646. mesh = subMesh.getMesh();
  24647. }
  24648. var renderingGroupId = mesh.renderingGroupId || 0;
  24649. this._prepareRenderingGroup(renderingGroupId);
  24650. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  24651. };
  24652. /**
  24653. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24654. * This allowed control for front to back rendering or reversly depending of the special needs.
  24655. *
  24656. * @param renderingGroupId The rendering group id corresponding to its index
  24657. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24658. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24659. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24660. */
  24661. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24662. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24663. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24664. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24665. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  24666. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  24667. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  24668. if (this._renderingGroups[renderingGroupId]) {
  24669. var group = this._renderingGroups[renderingGroupId];
  24670. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  24671. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  24672. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  24673. }
  24674. };
  24675. /**
  24676. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24677. *
  24678. * @param renderingGroupId The rendering group id corresponding to its index
  24679. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24680. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24681. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24682. */
  24683. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24684. if (depth === void 0) { depth = true; }
  24685. if (stencil === void 0) { stencil = true; }
  24686. this._autoClearDepthStencil[renderingGroupId] = {
  24687. autoClear: autoClearDepthStencil,
  24688. depth: depth,
  24689. stencil: stencil
  24690. };
  24691. };
  24692. /**
  24693. * Gets the current auto clear configuration for one rendering group of the rendering
  24694. * manager.
  24695. * @param index the rendering group index to get the information for
  24696. * @returns The auto clear setup for the requested rendering group
  24697. */
  24698. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  24699. return this._autoClearDepthStencil[index];
  24700. };
  24701. /**
  24702. * The max id used for rendering groups (not included)
  24703. */
  24704. RenderingManager.MAX_RENDERINGGROUPS = 4;
  24705. /**
  24706. * The min id used for rendering groups (included)
  24707. */
  24708. RenderingManager.MIN_RENDERINGGROUPS = 0;
  24709. /**
  24710. * Used to globally prevent autoclearing scenes.
  24711. */
  24712. RenderingManager.AUTOCLEAR = true;
  24713. return RenderingManager;
  24714. }());
  24715. BABYLON.RenderingManager = RenderingManager;
  24716. })(BABYLON || (BABYLON = {}));
  24717. //# sourceMappingURL=renderingManager.js.map
  24718. var BABYLON;
  24719. (function (BABYLON) {
  24720. /**
  24721. * This represents the object necessary to create a rendering group.
  24722. * This is exclusively used and created by the rendering manager.
  24723. * To modify the behavior, you use the available helpers in your scene or meshes.
  24724. * @hidden
  24725. */
  24726. var RenderingGroup = /** @class */ (function () {
  24727. /**
  24728. * Creates a new rendering group.
  24729. * @param index The rendering group index
  24730. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  24731. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  24732. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  24733. */
  24734. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24735. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24736. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24737. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24738. this.index = index;
  24739. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  24740. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  24741. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  24742. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  24743. this._particleSystems = new BABYLON.SmartArray(256);
  24744. this._spriteManagers = new BABYLON.SmartArray(256);
  24745. this._edgesRenderers = new BABYLON.SmartArray(16);
  24746. this._scene = scene;
  24747. this.opaqueSortCompareFn = opaqueSortCompareFn;
  24748. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  24749. this.transparentSortCompareFn = transparentSortCompareFn;
  24750. }
  24751. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  24752. /**
  24753. * Set the opaque sort comparison function.
  24754. * If null the sub meshes will be render in the order they were created
  24755. */
  24756. set: function (value) {
  24757. this._opaqueSortCompareFn = value;
  24758. if (value) {
  24759. this._renderOpaque = this.renderOpaqueSorted;
  24760. }
  24761. else {
  24762. this._renderOpaque = RenderingGroup.renderUnsorted;
  24763. }
  24764. },
  24765. enumerable: true,
  24766. configurable: true
  24767. });
  24768. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  24769. /**
  24770. * Set the alpha test sort comparison function.
  24771. * If null the sub meshes will be render in the order they were created
  24772. */
  24773. set: function (value) {
  24774. this._alphaTestSortCompareFn = value;
  24775. if (value) {
  24776. this._renderAlphaTest = this.renderAlphaTestSorted;
  24777. }
  24778. else {
  24779. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  24780. }
  24781. },
  24782. enumerable: true,
  24783. configurable: true
  24784. });
  24785. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  24786. /**
  24787. * Set the transparent sort comparison function.
  24788. * If null the sub meshes will be render in the order they were created
  24789. */
  24790. set: function (value) {
  24791. if (value) {
  24792. this._transparentSortCompareFn = value;
  24793. }
  24794. else {
  24795. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  24796. }
  24797. this._renderTransparent = this.renderTransparentSorted;
  24798. },
  24799. enumerable: true,
  24800. configurable: true
  24801. });
  24802. /**
  24803. * Render all the sub meshes contained in the group.
  24804. * @param customRenderFunction Used to override the default render behaviour of the group.
  24805. * @returns true if rendered some submeshes.
  24806. */
  24807. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  24808. if (customRenderFunction) {
  24809. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  24810. return;
  24811. }
  24812. var engine = this._scene.getEngine();
  24813. // Depth only
  24814. if (this._depthOnlySubMeshes.length !== 0) {
  24815. engine.setColorWrite(false);
  24816. this._renderAlphaTest(this._depthOnlySubMeshes);
  24817. engine.setColorWrite(true);
  24818. }
  24819. // Opaque
  24820. if (this._opaqueSubMeshes.length !== 0) {
  24821. this._renderOpaque(this._opaqueSubMeshes);
  24822. }
  24823. // Alpha test
  24824. if (this._alphaTestSubMeshes.length !== 0) {
  24825. this._renderAlphaTest(this._alphaTestSubMeshes);
  24826. }
  24827. var stencilState = engine.getStencilBuffer();
  24828. engine.setStencilBuffer(false);
  24829. // Sprites
  24830. if (renderSprites) {
  24831. this._renderSprites();
  24832. }
  24833. // Particles
  24834. if (renderParticles) {
  24835. this._renderParticles(activeMeshes);
  24836. }
  24837. if (this.onBeforeTransparentRendering) {
  24838. this.onBeforeTransparentRendering();
  24839. }
  24840. // Transparent
  24841. if (this._transparentSubMeshes.length !== 0) {
  24842. this._renderTransparent(this._transparentSubMeshes);
  24843. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24844. }
  24845. // Set back stencil to false in case it changes before the edge renderer.
  24846. engine.setStencilBuffer(false);
  24847. // Edges
  24848. if (this._edgesRenderers.length) {
  24849. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  24850. this._edgesRenderers.data[edgesRendererIndex].render();
  24851. }
  24852. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24853. }
  24854. // Restore Stencil state.
  24855. engine.setStencilBuffer(stencilState);
  24856. };
  24857. /**
  24858. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  24859. * @param subMeshes The submeshes to render
  24860. */
  24861. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  24862. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  24863. };
  24864. /**
  24865. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  24866. * @param subMeshes The submeshes to render
  24867. */
  24868. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  24869. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  24870. };
  24871. /**
  24872. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  24873. * @param subMeshes The submeshes to render
  24874. */
  24875. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  24876. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  24877. };
  24878. /**
  24879. * Renders the submeshes in a specified order.
  24880. * @param subMeshes The submeshes to sort before render
  24881. * @param sortCompareFn The comparison function use to sort
  24882. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  24883. * @param transparent Specifies to activate blending if true
  24884. */
  24885. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  24886. var subIndex = 0;
  24887. var subMesh;
  24888. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  24889. for (; subIndex < subMeshes.length; subIndex++) {
  24890. subMesh = subMeshes.data[subIndex];
  24891. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  24892. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  24893. }
  24894. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  24895. if (sortCompareFn) {
  24896. sortedArray.sort(sortCompareFn);
  24897. }
  24898. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  24899. subMesh = sortedArray[subIndex];
  24900. if (transparent) {
  24901. var material = subMesh.getMaterial();
  24902. if (material && material.needDepthPrePass) {
  24903. var engine = material.getScene().getEngine();
  24904. engine.setColorWrite(false);
  24905. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24906. subMesh.render(false);
  24907. engine.setColorWrite(true);
  24908. }
  24909. }
  24910. subMesh.render(transparent);
  24911. }
  24912. };
  24913. /**
  24914. * Renders the submeshes in the order they were dispatched (no sort applied).
  24915. * @param subMeshes The submeshes to render
  24916. */
  24917. RenderingGroup.renderUnsorted = function (subMeshes) {
  24918. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  24919. var submesh = subMeshes.data[subIndex];
  24920. submesh.render(false);
  24921. }
  24922. };
  24923. /**
  24924. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24925. * are rendered back to front if in the same alpha index.
  24926. *
  24927. * @param a The first submesh
  24928. * @param b The second submesh
  24929. * @returns The result of the comparison
  24930. */
  24931. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  24932. // Alpha index first
  24933. if (a._alphaIndex > b._alphaIndex) {
  24934. return 1;
  24935. }
  24936. if (a._alphaIndex < b._alphaIndex) {
  24937. return -1;
  24938. }
  24939. // Then distance to camera
  24940. return RenderingGroup.backToFrontSortCompare(a, b);
  24941. };
  24942. /**
  24943. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24944. * are rendered back to front.
  24945. *
  24946. * @param a The first submesh
  24947. * @param b The second submesh
  24948. * @returns The result of the comparison
  24949. */
  24950. RenderingGroup.backToFrontSortCompare = function (a, b) {
  24951. // Then distance to camera
  24952. if (a._distanceToCamera < b._distanceToCamera) {
  24953. return 1;
  24954. }
  24955. if (a._distanceToCamera > b._distanceToCamera) {
  24956. return -1;
  24957. }
  24958. return 0;
  24959. };
  24960. /**
  24961. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24962. * are rendered front to back (prevent overdraw).
  24963. *
  24964. * @param a The first submesh
  24965. * @param b The second submesh
  24966. * @returns The result of the comparison
  24967. */
  24968. RenderingGroup.frontToBackSortCompare = function (a, b) {
  24969. // Then distance to camera
  24970. if (a._distanceToCamera < b._distanceToCamera) {
  24971. return -1;
  24972. }
  24973. if (a._distanceToCamera > b._distanceToCamera) {
  24974. return 1;
  24975. }
  24976. return 0;
  24977. };
  24978. /**
  24979. * Resets the different lists of submeshes to prepare a new frame.
  24980. */
  24981. RenderingGroup.prototype.prepare = function () {
  24982. this._opaqueSubMeshes.reset();
  24983. this._transparentSubMeshes.reset();
  24984. this._alphaTestSubMeshes.reset();
  24985. this._depthOnlySubMeshes.reset();
  24986. this._particleSystems.reset();
  24987. this._spriteManagers.reset();
  24988. this._edgesRenderers.reset();
  24989. };
  24990. RenderingGroup.prototype.dispose = function () {
  24991. this._opaqueSubMeshes.dispose();
  24992. this._transparentSubMeshes.dispose();
  24993. this._alphaTestSubMeshes.dispose();
  24994. this._depthOnlySubMeshes.dispose();
  24995. this._particleSystems.dispose();
  24996. this._spriteManagers.dispose();
  24997. this._edgesRenderers.dispose();
  24998. };
  24999. /**
  25000. * Inserts the submesh in its correct queue depending on its material.
  25001. * @param subMesh The submesh to dispatch
  25002. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  25003. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  25004. */
  25005. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  25006. // Get mesh and materials if not provided
  25007. if (mesh === undefined) {
  25008. mesh = subMesh.getMesh();
  25009. }
  25010. if (material === undefined) {
  25011. material = subMesh.getMaterial();
  25012. }
  25013. if (material === null || material === undefined) {
  25014. return;
  25015. }
  25016. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  25017. this._transparentSubMeshes.push(subMesh);
  25018. }
  25019. else if (material.needAlphaTesting()) { // Alpha test
  25020. if (material.needDepthPrePass) {
  25021. this._depthOnlySubMeshes.push(subMesh);
  25022. }
  25023. this._alphaTestSubMeshes.push(subMesh);
  25024. }
  25025. else {
  25026. if (material.needDepthPrePass) {
  25027. this._depthOnlySubMeshes.push(subMesh);
  25028. }
  25029. this._opaqueSubMeshes.push(subMesh); // Opaque
  25030. }
  25031. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  25032. this._edgesRenderers.push(mesh._edgesRenderer);
  25033. }
  25034. };
  25035. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  25036. this._spriteManagers.push(spriteManager);
  25037. };
  25038. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  25039. this._particleSystems.push(particleSystem);
  25040. };
  25041. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  25042. if (this._particleSystems.length === 0) {
  25043. return;
  25044. }
  25045. // Particles
  25046. var activeCamera = this._scene.activeCamera;
  25047. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  25048. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  25049. var particleSystem = this._particleSystems.data[particleIndex];
  25050. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  25051. continue;
  25052. }
  25053. var emitter = particleSystem.emitter;
  25054. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  25055. this._scene._activeParticles.addCount(particleSystem.render(), false);
  25056. }
  25057. }
  25058. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  25059. };
  25060. RenderingGroup.prototype._renderSprites = function () {
  25061. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  25062. return;
  25063. }
  25064. // Sprites
  25065. var activeCamera = this._scene.activeCamera;
  25066. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  25067. for (var id = 0; id < this._spriteManagers.length; id++) {
  25068. var spriteManager = this._spriteManagers.data[id];
  25069. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  25070. spriteManager.render();
  25071. }
  25072. }
  25073. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  25074. };
  25075. return RenderingGroup;
  25076. }());
  25077. BABYLON.RenderingGroup = RenderingGroup;
  25078. })(BABYLON || (BABYLON = {}));
  25079. //# sourceMappingURL=renderingGroup.js.map
  25080. var BABYLON;
  25081. (function (BABYLON) {
  25082. /**
  25083. * Groups all the scene component constants in one place to ease maintenance.
  25084. * @hidden
  25085. */
  25086. var SceneComponentConstants = /** @class */ (function () {
  25087. function SceneComponentConstants() {
  25088. }
  25089. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  25090. SceneComponentConstants.NAME_LAYER = "Layer";
  25091. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  25092. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  25093. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  25094. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  25095. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  25096. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  25097. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  25098. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  25099. SceneComponentConstants.NAME_SPRITE = "Sprite";
  25100. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  25101. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  25102. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  25103. SceneComponentConstants.NAME_OCTREE = "Octree";
  25104. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  25105. SceneComponentConstants.NAME_AUDIO = "Audio";
  25106. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  25107. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  25108. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  25109. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  25110. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  25111. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  25112. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  25113. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  25114. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  25115. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  25116. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  25117. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  25118. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  25119. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  25120. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  25121. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  25122. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  25123. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  25124. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  25125. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  25126. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  25127. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  25128. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  25129. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  25130. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  25131. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  25132. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  25133. return SceneComponentConstants;
  25134. }());
  25135. BABYLON.SceneComponentConstants = SceneComponentConstants;
  25136. /**
  25137. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  25138. * @hidden
  25139. */
  25140. var Stage = /** @class */ (function (_super) {
  25141. __extends(Stage, _super);
  25142. /**
  25143. * Hide ctor from the rest of the world.
  25144. * @param items The items to add.
  25145. */
  25146. function Stage(items) {
  25147. return _super.apply(this, items) || this;
  25148. }
  25149. /**
  25150. * Creates a new Stage.
  25151. * @returns A new instance of a Stage
  25152. */
  25153. Stage.Create = function () {
  25154. return Object.create(Stage.prototype);
  25155. };
  25156. /**
  25157. * Registers a step in an ordered way in the targeted stage.
  25158. * @param index Defines the position to register the step in
  25159. * @param component Defines the component attached to the step
  25160. * @param action Defines the action to launch during the step
  25161. */
  25162. Stage.prototype.registerStep = function (index, component, action) {
  25163. var i = 0;
  25164. var maxIndex = Number.MAX_VALUE;
  25165. for (; i < this.length; i++) {
  25166. var step = this[i];
  25167. maxIndex = step.index;
  25168. if (index < maxIndex) {
  25169. break;
  25170. }
  25171. }
  25172. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  25173. };
  25174. /**
  25175. * Clears all the steps from the stage.
  25176. */
  25177. Stage.prototype.clear = function () {
  25178. this.length = 0;
  25179. };
  25180. return Stage;
  25181. }(Array));
  25182. BABYLON.Stage = Stage;
  25183. })(BABYLON || (BABYLON = {}));
  25184. //# sourceMappingURL=sceneComponent.js.map
  25185. var BABYLON;
  25186. (function (BABYLON) {
  25187. /**
  25188. * Base class of the scene acting as a container for the different elements composing a scene.
  25189. * This class is dynamically extended by the different components of the scene increasing
  25190. * flexibility and reducing coupling
  25191. */
  25192. var AbstractScene = /** @class */ (function () {
  25193. function AbstractScene() {
  25194. /**
  25195. * Gets the list of root nodes (ie. nodes with no parent)
  25196. */
  25197. this.rootNodes = new Array();
  25198. /** All of the cameras added to this scene
  25199. * @see http://doc.babylonjs.com/babylon101/cameras
  25200. */
  25201. this.cameras = new Array();
  25202. /**
  25203. * All of the lights added to this scene
  25204. * @see http://doc.babylonjs.com/babylon101/lights
  25205. */
  25206. this.lights = new Array();
  25207. /**
  25208. * All of the (abstract) meshes added to this scene
  25209. */
  25210. this.meshes = new Array();
  25211. /**
  25212. * The list of skeletons added to the scene
  25213. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  25214. */
  25215. this.skeletons = new Array();
  25216. /**
  25217. * All of the particle systems added to this scene
  25218. * @see http://doc.babylonjs.com/babylon101/particles
  25219. */
  25220. this.particleSystems = new Array();
  25221. /**
  25222. * Gets a list of Animations associated with the scene
  25223. */
  25224. this.animations = [];
  25225. /**
  25226. * All of the animation groups added to this scene
  25227. * @see http://doc.babylonjs.com/how_to/group
  25228. */
  25229. this.animationGroups = new Array();
  25230. /**
  25231. * All of the multi-materials added to this scene
  25232. * @see http://doc.babylonjs.com/how_to/multi_materials
  25233. */
  25234. this.multiMaterials = new Array();
  25235. /**
  25236. * All of the materials added to this scene
  25237. * In the context of a Scene, it is not supposed to be modified manually.
  25238. * Any addition or removal should be done using the addMaterial and removeMAterial Scene methods.
  25239. * Note also that the order of the Material wihin the array is not significant and might change.
  25240. * @see http://doc.babylonjs.com/babylon101/materials
  25241. */
  25242. this.materials = new Array();
  25243. /**
  25244. * The list of morph target managers added to the scene
  25245. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  25246. */
  25247. this.morphTargetManagers = new Array();
  25248. /**
  25249. * The list of geometries used in the scene.
  25250. */
  25251. this.geometries = new Array();
  25252. /**
  25253. * All of the tranform nodes added to this scene
  25254. * In the context of a Scene, it is not supposed to be modified manually.
  25255. * Any addition or removal should be done using the addTransformNode and removeTransformNode Scene methods.
  25256. * Note also that the order of the TransformNode wihin the array is not significant and might change.
  25257. * @see http://doc.babylonjs.com/how_to/transformnode
  25258. */
  25259. this.transformNodes = new Array();
  25260. /**
  25261. * ActionManagers available on the scene.
  25262. */
  25263. this.actionManagers = new Array();
  25264. /**
  25265. * Textures to keep.
  25266. */
  25267. this.textures = new Array();
  25268. }
  25269. /**
  25270. * Adds a parser in the list of available ones
  25271. * @param name Defines the name of the parser
  25272. * @param parser Defines the parser to add
  25273. */
  25274. AbstractScene.AddParser = function (name, parser) {
  25275. this._BabylonFileParsers[name] = parser;
  25276. };
  25277. /**
  25278. * Gets a general parser from the list of avaialble ones
  25279. * @param name Defines the name of the parser
  25280. * @returns the requested parser or null
  25281. */
  25282. AbstractScene.GetParser = function (name) {
  25283. if (this._BabylonFileParsers[name]) {
  25284. return this._BabylonFileParsers[name];
  25285. }
  25286. return null;
  25287. };
  25288. /**
  25289. * Adds n individual parser in the list of available ones
  25290. * @param name Defines the name of the parser
  25291. * @param parser Defines the parser to add
  25292. */
  25293. AbstractScene.AddIndividualParser = function (name, parser) {
  25294. this._IndividualBabylonFileParsers[name] = parser;
  25295. };
  25296. /**
  25297. * Gets an individual parser from the list of avaialble ones
  25298. * @param name Defines the name of the parser
  25299. * @returns the requested parser or null
  25300. */
  25301. AbstractScene.GetIndividualParser = function (name) {
  25302. if (this._IndividualBabylonFileParsers[name]) {
  25303. return this._IndividualBabylonFileParsers[name];
  25304. }
  25305. return null;
  25306. };
  25307. /**
  25308. * Parser json data and populate both a scene and its associated container object
  25309. * @param jsonData Defines the data to parse
  25310. * @param scene Defines the scene to parse the data for
  25311. * @param container Defines the container attached to the parsing sequence
  25312. * @param rootUrl Defines the root url of the data
  25313. */
  25314. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  25315. for (var parserName in this._BabylonFileParsers) {
  25316. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  25317. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  25318. }
  25319. }
  25320. };
  25321. /**
  25322. * Stores the list of available parsers in the application.
  25323. */
  25324. AbstractScene._BabylonFileParsers = {};
  25325. /**
  25326. * Stores the list of available individual parsers in the application.
  25327. */
  25328. AbstractScene._IndividualBabylonFileParsers = {};
  25329. return AbstractScene;
  25330. }());
  25331. BABYLON.AbstractScene = AbstractScene;
  25332. })(BABYLON || (BABYLON = {}));
  25333. //# sourceMappingURL=abstractScene.js.map
  25334. var BABYLON;
  25335. (function (BABYLON) {
  25336. /** @hidden */
  25337. var ClickInfo = /** @class */ (function () {
  25338. function ClickInfo() {
  25339. this._singleClick = false;
  25340. this._doubleClick = false;
  25341. this._hasSwiped = false;
  25342. this._ignore = false;
  25343. }
  25344. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  25345. get: function () {
  25346. return this._singleClick;
  25347. },
  25348. set: function (b) {
  25349. this._singleClick = b;
  25350. },
  25351. enumerable: true,
  25352. configurable: true
  25353. });
  25354. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  25355. get: function () {
  25356. return this._doubleClick;
  25357. },
  25358. set: function (b) {
  25359. this._doubleClick = b;
  25360. },
  25361. enumerable: true,
  25362. configurable: true
  25363. });
  25364. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  25365. get: function () {
  25366. return this._hasSwiped;
  25367. },
  25368. set: function (b) {
  25369. this._hasSwiped = b;
  25370. },
  25371. enumerable: true,
  25372. configurable: true
  25373. });
  25374. Object.defineProperty(ClickInfo.prototype, "ignore", {
  25375. get: function () {
  25376. return this._ignore;
  25377. },
  25378. set: function (b) {
  25379. this._ignore = b;
  25380. },
  25381. enumerable: true,
  25382. configurable: true
  25383. });
  25384. return ClickInfo;
  25385. }());
  25386. /**
  25387. * This class is used by the onRenderingGroupObservable
  25388. */
  25389. var RenderingGroupInfo = /** @class */ (function () {
  25390. function RenderingGroupInfo() {
  25391. }
  25392. return RenderingGroupInfo;
  25393. }());
  25394. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  25395. /**
  25396. * Represents a scene to be rendered by the engine.
  25397. * @see http://doc.babylonjs.com/features/scene
  25398. */
  25399. var Scene = /** @class */ (function (_super) {
  25400. __extends(Scene, _super);
  25401. /**
  25402. * Creates a new Scene
  25403. * @param engine defines the engine to use to render this scene
  25404. */
  25405. function Scene(engine, options) {
  25406. var _this = _super.call(this) || this;
  25407. // Members
  25408. /**
  25409. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  25410. */
  25411. _this.autoClear = true;
  25412. /**
  25413. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  25414. */
  25415. _this.autoClearDepthAndStencil = true;
  25416. /**
  25417. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  25418. */
  25419. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  25420. /**
  25421. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  25422. */
  25423. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  25424. _this._forceWireframe = false;
  25425. _this._forcePointsCloud = false;
  25426. /**
  25427. * Gets or sets a boolean indicating if animations are enabled
  25428. */
  25429. _this.animationsEnabled = true;
  25430. _this._animationPropertiesOverride = null;
  25431. /**
  25432. * Gets or sets a boolean indicating if a constant deltatime has to be used
  25433. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  25434. */
  25435. _this.useConstantAnimationDeltaTime = false;
  25436. /**
  25437. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  25438. * Please note that it requires to run a ray cast through the scene on every frame
  25439. */
  25440. _this.constantlyUpdateMeshUnderPointer = false;
  25441. /**
  25442. * Defines the HTML cursor to use when hovering over interactive elements
  25443. */
  25444. _this.hoverCursor = "pointer";
  25445. /**
  25446. * Defines the HTML default cursor to use (empty by default)
  25447. */
  25448. _this.defaultCursor = "";
  25449. /**
  25450. * This is used to call preventDefault() on pointer down
  25451. * in order to block unwanted artifacts like system double clicks
  25452. */
  25453. _this.preventDefaultOnPointerDown = true;
  25454. /**
  25455. * This is used to call preventDefault() on pointer up
  25456. * in order to block unwanted artifacts like system double clicks
  25457. */
  25458. _this.preventDefaultOnPointerUp = true;
  25459. // Metadata
  25460. /**
  25461. * Gets or sets user defined metadata
  25462. */
  25463. _this.metadata = null;
  25464. /**
  25465. * Use this array to add regular expressions used to disable offline support for specific urls
  25466. */
  25467. _this.disableOfflineSupportExceptionRules = new Array();
  25468. /**
  25469. * An event triggered when the scene is disposed.
  25470. */
  25471. _this.onDisposeObservable = new BABYLON.Observable();
  25472. _this._onDisposeObserver = null;
  25473. /**
  25474. * An event triggered before rendering the scene (right after animations and physics)
  25475. */
  25476. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25477. _this._onBeforeRenderObserver = null;
  25478. /**
  25479. * An event triggered after rendering the scene
  25480. */
  25481. _this.onAfterRenderObservable = new BABYLON.Observable();
  25482. _this._onAfterRenderObserver = null;
  25483. /**
  25484. * An event triggered before animating the scene
  25485. */
  25486. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  25487. /**
  25488. * An event triggered after animations processing
  25489. */
  25490. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  25491. /**
  25492. * An event triggered before draw calls are ready to be sent
  25493. */
  25494. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  25495. /**
  25496. * An event triggered after draw calls have been sent
  25497. */
  25498. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  25499. /**
  25500. * An event triggered when the scene is ready
  25501. */
  25502. _this.onReadyObservable = new BABYLON.Observable();
  25503. /**
  25504. * An event triggered before rendering a camera
  25505. */
  25506. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  25507. _this._onBeforeCameraRenderObserver = null;
  25508. /**
  25509. * An event triggered after rendering a camera
  25510. */
  25511. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  25512. _this._onAfterCameraRenderObserver = null;
  25513. /**
  25514. * An event triggered when active meshes evaluation is about to start
  25515. */
  25516. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25517. /**
  25518. * An event triggered when active meshes evaluation is done
  25519. */
  25520. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25521. /**
  25522. * An event triggered when particles rendering is about to start
  25523. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25524. */
  25525. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  25526. /**
  25527. * An event triggered when particles rendering is done
  25528. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25529. */
  25530. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  25531. /**
  25532. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  25533. */
  25534. _this.onDataLoadedObservable = new BABYLON.Observable();
  25535. /**
  25536. * An event triggered when a camera is created
  25537. */
  25538. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  25539. /**
  25540. * An event triggered when a camera is removed
  25541. */
  25542. _this.onCameraRemovedObservable = new BABYLON.Observable();
  25543. /**
  25544. * An event triggered when a light is created
  25545. */
  25546. _this.onNewLightAddedObservable = new BABYLON.Observable();
  25547. /**
  25548. * An event triggered when a light is removed
  25549. */
  25550. _this.onLightRemovedObservable = new BABYLON.Observable();
  25551. /**
  25552. * An event triggered when a geometry is created
  25553. */
  25554. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  25555. /**
  25556. * An event triggered when a geometry is removed
  25557. */
  25558. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  25559. /**
  25560. * An event triggered when a transform node is created
  25561. */
  25562. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  25563. /**
  25564. * An event triggered when a transform node is removed
  25565. */
  25566. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  25567. /**
  25568. * An event triggered when a mesh is created
  25569. */
  25570. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  25571. /**
  25572. * An event triggered when a mesh is removed
  25573. */
  25574. _this.onMeshRemovedObservable = new BABYLON.Observable();
  25575. /**
  25576. * An event triggered when a material is created
  25577. */
  25578. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  25579. /**
  25580. * An event triggered when a material is removed
  25581. */
  25582. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  25583. /**
  25584. * An event triggered when a texture is created
  25585. */
  25586. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  25587. /**
  25588. * An event triggered when a texture is removed
  25589. */
  25590. _this.onTextureRemovedObservable = new BABYLON.Observable();
  25591. /**
  25592. * An event triggered when render targets are about to be rendered
  25593. * Can happen multiple times per frame.
  25594. */
  25595. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  25596. /**
  25597. * An event triggered when render targets were rendered.
  25598. * Can happen multiple times per frame.
  25599. */
  25600. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  25601. /**
  25602. * An event triggered before calculating deterministic simulation step
  25603. */
  25604. _this.onBeforeStepObservable = new BABYLON.Observable();
  25605. /**
  25606. * An event triggered after calculating deterministic simulation step
  25607. */
  25608. _this.onAfterStepObservable = new BABYLON.Observable();
  25609. /**
  25610. * An event triggered when the activeCamera property is updated
  25611. */
  25612. _this.onActiveCameraChanged = new BABYLON.Observable();
  25613. /**
  25614. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  25615. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25616. * 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)
  25617. */
  25618. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  25619. /**
  25620. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  25621. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25622. * 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)
  25623. */
  25624. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  25625. /**
  25626. * This Observable will when a mesh has been imported into the scene.
  25627. */
  25628. _this.onMeshImportedObservable = new BABYLON.Observable();
  25629. // Animations
  25630. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  25631. /**
  25632. * 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).
  25633. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  25634. */
  25635. _this.onPrePointerObservable = new BABYLON.Observable();
  25636. /**
  25637. * Observable event triggered each time an input event is received from the rendering canvas
  25638. */
  25639. _this.onPointerObservable = new BABYLON.Observable();
  25640. _this._meshPickProceed = false;
  25641. _this._currentPickResult = null;
  25642. _this._previousPickResult = null;
  25643. _this._totalPointersPressed = 0;
  25644. _this._doubleClickOccured = false;
  25645. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  25646. _this.cameraToUseForPointers = null;
  25647. _this._pointerX = 0;
  25648. _this._pointerY = 0;
  25649. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  25650. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  25651. _this._startingPointerTime = 0;
  25652. _this._previousStartingPointerTime = 0;
  25653. _this._pointerCaptures = {};
  25654. // Deterministic lockstep
  25655. _this._timeAccumulator = 0;
  25656. _this._currentStepId = 0;
  25657. _this._currentInternalStep = 0;
  25658. // Keyboard
  25659. /**
  25660. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  25661. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  25662. */
  25663. _this.onPreKeyboardObservable = new BABYLON.Observable();
  25664. /**
  25665. * Observable event triggered each time an keyboard event is received from the hosting window
  25666. */
  25667. _this.onKeyboardObservable = new BABYLON.Observable();
  25668. // Coordinates system
  25669. _this._useRightHandedSystem = false;
  25670. // Fog
  25671. _this._fogEnabled = true;
  25672. _this._fogMode = Scene.FOGMODE_NONE;
  25673. /**
  25674. * Gets or sets the fog color to use
  25675. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25676. * (Default is Color3(0.2, 0.2, 0.3))
  25677. */
  25678. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  25679. /**
  25680. * Gets or sets the fog density to use
  25681. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25682. * (Default is 0.1)
  25683. */
  25684. _this.fogDensity = 0.1;
  25685. /**
  25686. * Gets or sets the fog start distance to use
  25687. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25688. * (Default is 0)
  25689. */
  25690. _this.fogStart = 0;
  25691. /**
  25692. * Gets or sets the fog end distance to use
  25693. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25694. * (Default is 1000)
  25695. */
  25696. _this.fogEnd = 1000.0;
  25697. // Lights
  25698. _this._shadowsEnabled = true;
  25699. _this._lightsEnabled = true;
  25700. /** All of the active cameras added to this scene. */
  25701. _this.activeCameras = new Array();
  25702. // Textures
  25703. _this._texturesEnabled = true;
  25704. // Particles
  25705. /**
  25706. * Gets or sets a boolean indicating if particles are enabled on this scene
  25707. */
  25708. _this.particlesEnabled = true;
  25709. // Sprites
  25710. /**
  25711. * Gets or sets a boolean indicating if sprites are enabled on this scene
  25712. */
  25713. _this.spritesEnabled = true;
  25714. // Skeletons
  25715. _this._skeletonsEnabled = true;
  25716. // Lens flares
  25717. /**
  25718. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  25719. */
  25720. _this.lensFlaresEnabled = true;
  25721. // Collisions
  25722. /**
  25723. * Gets or sets a boolean indicating if collisions are enabled on this scene
  25724. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25725. */
  25726. _this.collisionsEnabled = true;
  25727. /**
  25728. * Defines the gravity applied to this scene (used only for collisions)
  25729. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25730. */
  25731. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  25732. // Postprocesses
  25733. /**
  25734. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  25735. */
  25736. _this.postProcessesEnabled = true;
  25737. /**
  25738. * The list of postprocesses added to the scene
  25739. */
  25740. _this.postProcesses = new Array();
  25741. // Customs render targets
  25742. /**
  25743. * Gets or sets a boolean indicating if render targets are enabled on this scene
  25744. */
  25745. _this.renderTargetsEnabled = true;
  25746. /**
  25747. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  25748. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  25749. */
  25750. _this.dumpNextRenderTargets = false;
  25751. /**
  25752. * The list of user defined render targets added to the scene
  25753. */
  25754. _this.customRenderTargets = new Array();
  25755. /**
  25756. * Gets the list of meshes imported to the scene through SceneLoader
  25757. */
  25758. _this.importedMeshesFiles = new Array();
  25759. // Probes
  25760. /**
  25761. * Gets or sets a boolean indicating if probes are enabled on this scene
  25762. */
  25763. _this.probesEnabled = true;
  25764. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  25765. // Procedural textures
  25766. /**
  25767. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  25768. */
  25769. _this.proceduralTexturesEnabled = true;
  25770. // Performance counters
  25771. _this._totalVertices = new BABYLON.PerfCounter();
  25772. /** @hidden */
  25773. _this._activeIndices = new BABYLON.PerfCounter();
  25774. /** @hidden */
  25775. _this._activeParticles = new BABYLON.PerfCounter();
  25776. /** @hidden */
  25777. _this._activeBones = new BABYLON.PerfCounter();
  25778. _this._animationTime = 0;
  25779. /**
  25780. * Gets or sets a general scale for animation speed
  25781. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  25782. */
  25783. _this.animationTimeScale = 1;
  25784. _this._renderId = 0;
  25785. _this._frameId = 0;
  25786. _this._executeWhenReadyTimeoutId = -1;
  25787. _this._intermediateRendering = false;
  25788. _this._viewUpdateFlag = -1;
  25789. _this._projectionUpdateFlag = -1;
  25790. _this._alternateViewUpdateFlag = -1;
  25791. _this._alternateProjectionUpdateFlag = -1;
  25792. /** @hidden */
  25793. _this._toBeDisposed = new Array(256);
  25794. _this._activeRequests = new Array();
  25795. _this._pendingData = new Array();
  25796. _this._isDisposed = false;
  25797. /**
  25798. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  25799. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  25800. */
  25801. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  25802. _this._activeMeshes = new BABYLON.SmartArray(256);
  25803. _this._processedMaterials = new BABYLON.SmartArray(256);
  25804. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  25805. /** @hidden */
  25806. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  25807. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  25808. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  25809. /** @hidden */
  25810. _this._activeAnimatables = new Array();
  25811. _this._transformMatrix = BABYLON.Matrix.Zero();
  25812. _this._useAlternateCameraConfiguration = false;
  25813. _this._alternateRendering = false;
  25814. _this._wheelEventName = "";
  25815. /**
  25816. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  25817. * This is useful if there are more lights that the maximum simulteanous authorized
  25818. */
  25819. _this.requireLightSorting = false;
  25820. /**
  25821. * @hidden
  25822. * Backing store of defined scene components.
  25823. */
  25824. _this._components = [];
  25825. /**
  25826. * @hidden
  25827. * Backing store of defined scene components.
  25828. */
  25829. _this._serializableComponents = [];
  25830. /**
  25831. * List of components to register on the next registration step.
  25832. */
  25833. _this._transientComponents = [];
  25834. /**
  25835. * @hidden
  25836. * Defines the actions happening before camera updates.
  25837. */
  25838. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  25839. /**
  25840. * @hidden
  25841. * Defines the actions happening before clear the canvas.
  25842. */
  25843. _this._beforeClearStage = BABYLON.Stage.Create();
  25844. /**
  25845. * @hidden
  25846. * Defines the actions when collecting render targets for the frame.
  25847. */
  25848. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  25849. /**
  25850. * @hidden
  25851. * Defines the actions happening for one camera in the frame.
  25852. */
  25853. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  25854. /**
  25855. * @hidden
  25856. * Defines the actions happening during the per mesh ready checks.
  25857. */
  25858. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  25859. /**
  25860. * @hidden
  25861. * Defines the actions happening before evaluate active mesh checks.
  25862. */
  25863. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  25864. /**
  25865. * @hidden
  25866. * Defines the actions happening during the evaluate sub mesh checks.
  25867. */
  25868. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  25869. /**
  25870. * @hidden
  25871. * Defines the actions happening during the active mesh stage.
  25872. */
  25873. _this._activeMeshStage = BABYLON.Stage.Create();
  25874. /**
  25875. * @hidden
  25876. * Defines the actions happening during the per camera render target step.
  25877. */
  25878. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  25879. /**
  25880. * @hidden
  25881. * Defines the actions happening just before the active camera is drawing.
  25882. */
  25883. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  25884. /**
  25885. * @hidden
  25886. * Defines the actions happening just before a rendering group is drawing.
  25887. */
  25888. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  25889. /**
  25890. * @hidden
  25891. * Defines the actions happening just before a mesh is drawing.
  25892. */
  25893. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  25894. /**
  25895. * @hidden
  25896. * Defines the actions happening just after a mesh has been drawn.
  25897. */
  25898. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  25899. /**
  25900. * @hidden
  25901. * Defines the actions happening just after a rendering group has been drawn.
  25902. */
  25903. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  25904. /**
  25905. * @hidden
  25906. * Defines the actions happening just after the active camera has been drawn.
  25907. */
  25908. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  25909. /**
  25910. * @hidden
  25911. * Defines the actions happening just after rendering all cameras and computing intersections.
  25912. */
  25913. _this._afterRenderStage = BABYLON.Stage.Create();
  25914. /**
  25915. * @hidden
  25916. * Defines the actions happening when a pointer move event happens.
  25917. */
  25918. _this._pointerMoveStage = BABYLON.Stage.Create();
  25919. /**
  25920. * @hidden
  25921. * Defines the actions happening when a pointer down event happens.
  25922. */
  25923. _this._pointerDownStage = BABYLON.Stage.Create();
  25924. /**
  25925. * @hidden
  25926. * Defines the actions happening when a pointer up event happens.
  25927. */
  25928. _this._pointerUpStage = BABYLON.Stage.Create();
  25929. /**
  25930. * an optional map from Geometry Id to Geometry index in the 'geometries' array
  25931. */
  25932. _this.geometriesById = null;
  25933. _this._defaultMeshCandidates = {
  25934. data: [],
  25935. length: 0
  25936. };
  25937. _this._defaultSubMeshCandidates = {
  25938. data: [],
  25939. length: 0
  25940. };
  25941. _this._preventFreeActiveMeshesAndRenderingGroups = false;
  25942. _this._activeMeshesFrozen = false;
  25943. /** @hidden */
  25944. _this._allowPostProcessClearColor = true;
  25945. /**
  25946. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  25947. */
  25948. _this.getDeterministicFrameTime = function () {
  25949. return 1000.0 / 60.0; // frame time in ms
  25950. };
  25951. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  25952. _this._blockMaterialDirtyMechanism = false;
  25953. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  25954. _this._engine.scenes.push(_this);
  25955. _this._uid = null;
  25956. _this._renderingManager = new BABYLON.RenderingManager(_this);
  25957. if (BABYLON.PostProcessManager) {
  25958. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  25959. }
  25960. if (BABYLON.Tools.IsWindowObjectExist()) {
  25961. _this.attachControl();
  25962. }
  25963. //collision coordinator initialization. For now legacy per default.
  25964. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  25965. // Uniform Buffer
  25966. _this._createUbo();
  25967. // Default Image processing definition
  25968. if (BABYLON.ImageProcessingConfiguration) {
  25969. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  25970. }
  25971. _this.setDefaultCandidateProviders();
  25972. if (options && options.useGeometryIdsMap === true) {
  25973. _this.geometriesById = {};
  25974. }
  25975. _this.useMaterialMeshMap = options && options.useGeometryIdsMap || false;
  25976. _this.useClonedMeshhMap = options && options.useClonedMeshhMap || false;
  25977. return _this;
  25978. }
  25979. Object.defineProperty(Scene.prototype, "environmentTexture", {
  25980. /**
  25981. * Texture used in all pbr material as the reflection texture.
  25982. * As in the majority of the scene they are the same (exception for multi room and so on),
  25983. * this is easier to reference from here than from all the materials.
  25984. */
  25985. get: function () {
  25986. return this._environmentTexture;
  25987. },
  25988. /**
  25989. * Texture used in all pbr material as the reflection texture.
  25990. * As in the majority of the scene they are the same (exception for multi room and so on),
  25991. * this is easier to set here than in all the materials.
  25992. */
  25993. set: function (value) {
  25994. if (this._environmentTexture === value) {
  25995. return;
  25996. }
  25997. this._environmentTexture = value;
  25998. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25999. },
  26000. enumerable: true,
  26001. configurable: true
  26002. });
  26003. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  26004. /**
  26005. * Default image processing configuration used either in the rendering
  26006. * Forward main pass or through the imageProcessingPostProcess if present.
  26007. * As in the majority of the scene they are the same (exception for multi camera),
  26008. * this is easier to reference from here than from all the materials and post process.
  26009. *
  26010. * No setter as we it is a shared configuration, you can set the values instead.
  26011. */
  26012. get: function () {
  26013. return this._imageProcessingConfiguration;
  26014. },
  26015. enumerable: true,
  26016. configurable: true
  26017. });
  26018. Object.defineProperty(Scene.prototype, "forceWireframe", {
  26019. get: function () {
  26020. return this._forceWireframe;
  26021. },
  26022. /**
  26023. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  26024. */
  26025. set: function (value) {
  26026. if (this._forceWireframe === value) {
  26027. return;
  26028. }
  26029. this._forceWireframe = value;
  26030. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26031. },
  26032. enumerable: true,
  26033. configurable: true
  26034. });
  26035. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  26036. get: function () {
  26037. return this._forcePointsCloud;
  26038. },
  26039. /**
  26040. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  26041. */
  26042. set: function (value) {
  26043. if (this._forcePointsCloud === value) {
  26044. return;
  26045. }
  26046. this._forcePointsCloud = value;
  26047. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26048. },
  26049. enumerable: true,
  26050. configurable: true
  26051. });
  26052. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  26053. /**
  26054. * Gets or sets the animation properties override
  26055. */
  26056. get: function () {
  26057. return this._animationPropertiesOverride;
  26058. },
  26059. set: function (value) {
  26060. this._animationPropertiesOverride = value;
  26061. },
  26062. enumerable: true,
  26063. configurable: true
  26064. });
  26065. Object.defineProperty(Scene.prototype, "onDispose", {
  26066. /** Sets a function to be executed when this scene is disposed. */
  26067. set: function (callback) {
  26068. if (this._onDisposeObserver) {
  26069. this.onDisposeObservable.remove(this._onDisposeObserver);
  26070. }
  26071. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26072. },
  26073. enumerable: true,
  26074. configurable: true
  26075. });
  26076. Object.defineProperty(Scene.prototype, "beforeRender", {
  26077. /** Sets a function to be executed before rendering this scene */
  26078. set: function (callback) {
  26079. if (this._onBeforeRenderObserver) {
  26080. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  26081. }
  26082. if (callback) {
  26083. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  26084. }
  26085. },
  26086. enumerable: true,
  26087. configurable: true
  26088. });
  26089. Object.defineProperty(Scene.prototype, "afterRender", {
  26090. /** Sets a function to be executed after rendering this scene */
  26091. set: function (callback) {
  26092. if (this._onAfterRenderObserver) {
  26093. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  26094. }
  26095. if (callback) {
  26096. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  26097. }
  26098. },
  26099. enumerable: true,
  26100. configurable: true
  26101. });
  26102. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  26103. /** Sets a function to be executed before rendering a camera*/
  26104. set: function (callback) {
  26105. if (this._onBeforeCameraRenderObserver) {
  26106. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  26107. }
  26108. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  26109. },
  26110. enumerable: true,
  26111. configurable: true
  26112. });
  26113. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  26114. /** Sets a function to be executed after rendering a camera*/
  26115. set: function (callback) {
  26116. if (this._onAfterCameraRenderObserver) {
  26117. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  26118. }
  26119. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  26120. },
  26121. enumerable: true,
  26122. configurable: true
  26123. });
  26124. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  26125. /**
  26126. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  26127. */
  26128. get: function () {
  26129. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  26130. },
  26131. enumerable: true,
  26132. configurable: true
  26133. });
  26134. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  26135. get: function () {
  26136. return this._useRightHandedSystem;
  26137. },
  26138. /**
  26139. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  26140. */
  26141. set: function (value) {
  26142. if (this._useRightHandedSystem === value) {
  26143. return;
  26144. }
  26145. this._useRightHandedSystem = value;
  26146. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26147. },
  26148. enumerable: true,
  26149. configurable: true
  26150. });
  26151. /**
  26152. * Sets the step Id used by deterministic lock step
  26153. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  26154. * @param newStepId defines the step Id
  26155. */
  26156. Scene.prototype.setStepId = function (newStepId) {
  26157. this._currentStepId = newStepId;
  26158. };
  26159. /**
  26160. * Gets the step Id used by deterministic lock step
  26161. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  26162. * @returns the step Id
  26163. */
  26164. Scene.prototype.getStepId = function () {
  26165. return this._currentStepId;
  26166. };
  26167. /**
  26168. * Gets the internal step used by deterministic lock step
  26169. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  26170. * @returns the internal step
  26171. */
  26172. Scene.prototype.getInternalStep = function () {
  26173. return this._currentInternalStep;
  26174. };
  26175. Object.defineProperty(Scene.prototype, "fogEnabled", {
  26176. get: function () {
  26177. return this._fogEnabled;
  26178. },
  26179. /**
  26180. * Gets or sets a boolean indicating if fog is enabled on this scene
  26181. * @see http://doc.babylonjs.com/babylon101/environment#fog
  26182. * (Default is true)
  26183. */
  26184. set: function (value) {
  26185. if (this._fogEnabled === value) {
  26186. return;
  26187. }
  26188. this._fogEnabled = value;
  26189. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26190. },
  26191. enumerable: true,
  26192. configurable: true
  26193. });
  26194. Object.defineProperty(Scene.prototype, "fogMode", {
  26195. get: function () {
  26196. return this._fogMode;
  26197. },
  26198. /**
  26199. * Gets or sets the fog mode to use
  26200. * @see http://doc.babylonjs.com/babylon101/environment#fog
  26201. * | mode | value |
  26202. * | --- | --- |
  26203. * | FOGMODE_NONE | 0 |
  26204. * | FOGMODE_EXP | 1 |
  26205. * | FOGMODE_EXP2 | 2 |
  26206. * | FOGMODE_LINEAR | 3 |
  26207. */
  26208. set: function (value) {
  26209. if (this._fogMode === value) {
  26210. return;
  26211. }
  26212. this._fogMode = value;
  26213. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  26214. },
  26215. enumerable: true,
  26216. configurable: true
  26217. });
  26218. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  26219. get: function () {
  26220. return this._shadowsEnabled;
  26221. },
  26222. /**
  26223. * Gets or sets a boolean indicating if shadows are enabled on this scene
  26224. */
  26225. set: function (value) {
  26226. if (this._shadowsEnabled === value) {
  26227. return;
  26228. }
  26229. this._shadowsEnabled = value;
  26230. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  26231. },
  26232. enumerable: true,
  26233. configurable: true
  26234. });
  26235. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  26236. get: function () {
  26237. return this._lightsEnabled;
  26238. },
  26239. /**
  26240. * Gets or sets a boolean indicating if lights are enabled on this scene
  26241. */
  26242. set: function (value) {
  26243. if (this._lightsEnabled === value) {
  26244. return;
  26245. }
  26246. this._lightsEnabled = value;
  26247. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  26248. },
  26249. enumerable: true,
  26250. configurable: true
  26251. });
  26252. Object.defineProperty(Scene.prototype, "activeCamera", {
  26253. /** Gets or sets the current active camera */
  26254. get: function () {
  26255. return this._activeCamera;
  26256. },
  26257. set: function (value) {
  26258. if (value === this._activeCamera) {
  26259. return;
  26260. }
  26261. this._activeCamera = value;
  26262. this.onActiveCameraChanged.notifyObservers(this);
  26263. },
  26264. enumerable: true,
  26265. configurable: true
  26266. });
  26267. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  26268. /** The default material used on meshes when no material is affected */
  26269. get: function () {
  26270. if (!this._defaultMaterial) {
  26271. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  26272. }
  26273. return this._defaultMaterial;
  26274. },
  26275. /** The default material used on meshes when no material is affected */
  26276. set: function (value) {
  26277. this._defaultMaterial = value;
  26278. },
  26279. enumerable: true,
  26280. configurable: true
  26281. });
  26282. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  26283. get: function () {
  26284. return this._texturesEnabled;
  26285. },
  26286. /**
  26287. * Gets or sets a boolean indicating if textures are enabled on this scene
  26288. */
  26289. set: function (value) {
  26290. if (this._texturesEnabled === value) {
  26291. return;
  26292. }
  26293. this._texturesEnabled = value;
  26294. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26295. },
  26296. enumerable: true,
  26297. configurable: true
  26298. });
  26299. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  26300. get: function () {
  26301. return this._skeletonsEnabled;
  26302. },
  26303. /**
  26304. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  26305. */
  26306. set: function (value) {
  26307. if (this._skeletonsEnabled === value) {
  26308. return;
  26309. }
  26310. this._skeletonsEnabled = value;
  26311. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  26312. },
  26313. enumerable: true,
  26314. configurable: true
  26315. });
  26316. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  26317. /** @hidden */
  26318. get: function () {
  26319. return this._alternateRendering;
  26320. },
  26321. enumerable: true,
  26322. configurable: true
  26323. });
  26324. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  26325. /**
  26326. * Gets the list of frustum planes (built from the active camera)
  26327. */
  26328. get: function () {
  26329. return this._frustumPlanes;
  26330. },
  26331. enumerable: true,
  26332. configurable: true
  26333. });
  26334. /**
  26335. * Registers the transient components if needed.
  26336. */
  26337. Scene.prototype._registerTransientComponents = function () {
  26338. // Register components that have been associated lately to the scene.
  26339. if (this._transientComponents.length > 0) {
  26340. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  26341. var component = _a[_i];
  26342. component.register();
  26343. }
  26344. this._transientComponents = [];
  26345. }
  26346. };
  26347. /**
  26348. * @hidden
  26349. * Add a component to the scene.
  26350. * Note that the ccomponent could be registered on th next frame if this is called after
  26351. * the register component stage.
  26352. * @param component Defines the component to add to the scene
  26353. */
  26354. Scene.prototype._addComponent = function (component) {
  26355. this._components.push(component);
  26356. this._transientComponents.push(component);
  26357. var serializableComponent = component;
  26358. if (serializableComponent.addFromContainer) {
  26359. this._serializableComponents.push(serializableComponent);
  26360. }
  26361. };
  26362. /**
  26363. * @hidden
  26364. * Gets a component from the scene.
  26365. * @param name defines the name of the component to retrieve
  26366. * @returns the component or null if not present
  26367. */
  26368. Scene.prototype._getComponent = function (name) {
  26369. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  26370. var component = _a[_i];
  26371. if (component.name === name) {
  26372. return component;
  26373. }
  26374. }
  26375. return null;
  26376. };
  26377. /**
  26378. * @hidden
  26379. */
  26380. Scene.prototype._getDefaultMeshCandidates = function () {
  26381. this._defaultMeshCandidates.data = this.meshes;
  26382. this._defaultMeshCandidates.length = this.meshes.length;
  26383. return this._defaultMeshCandidates;
  26384. };
  26385. /**
  26386. * @hidden
  26387. */
  26388. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  26389. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  26390. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  26391. return this._defaultSubMeshCandidates;
  26392. };
  26393. /**
  26394. * Sets the default candidate providers for the scene.
  26395. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  26396. * and getCollidingSubMeshCandidates to their default function
  26397. */
  26398. Scene.prototype.setDefaultCandidateProviders = function () {
  26399. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  26400. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26401. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26402. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26403. };
  26404. Object.defineProperty(Scene.prototype, "workerCollisions", {
  26405. /**
  26406. * Gets a boolean indicating if collisions are processed on a web worker
  26407. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  26408. */
  26409. get: function () {
  26410. return this._workerCollisions;
  26411. },
  26412. set: function (enabled) {
  26413. if (!BABYLON.CollisionCoordinatorLegacy) {
  26414. return;
  26415. }
  26416. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  26417. this._workerCollisions = enabled;
  26418. if (this.collisionCoordinator) {
  26419. this.collisionCoordinator.destroy();
  26420. }
  26421. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  26422. this.collisionCoordinator.init(this);
  26423. },
  26424. enumerable: true,
  26425. configurable: true
  26426. });
  26427. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  26428. /**
  26429. * Gets the mesh that is currently under the pointer
  26430. */
  26431. get: function () {
  26432. return this._pointerOverMesh;
  26433. },
  26434. enumerable: true,
  26435. configurable: true
  26436. });
  26437. Object.defineProperty(Scene.prototype, "pointerX", {
  26438. /**
  26439. * Gets the current on-screen X position of the pointer
  26440. */
  26441. get: function () {
  26442. return this._pointerX;
  26443. },
  26444. enumerable: true,
  26445. configurable: true
  26446. });
  26447. Object.defineProperty(Scene.prototype, "pointerY", {
  26448. /**
  26449. * Gets the current on-screen Y position of the pointer
  26450. */
  26451. get: function () {
  26452. return this._pointerY;
  26453. },
  26454. enumerable: true,
  26455. configurable: true
  26456. });
  26457. /**
  26458. * Gets the cached material (ie. the latest rendered one)
  26459. * @returns the cached material
  26460. */
  26461. Scene.prototype.getCachedMaterial = function () {
  26462. return this._cachedMaterial;
  26463. };
  26464. /**
  26465. * Gets the cached effect (ie. the latest rendered one)
  26466. * @returns the cached effect
  26467. */
  26468. Scene.prototype.getCachedEffect = function () {
  26469. return this._cachedEffect;
  26470. };
  26471. /**
  26472. * Gets the cached visibility state (ie. the latest rendered one)
  26473. * @returns the cached visibility state
  26474. */
  26475. Scene.prototype.getCachedVisibility = function () {
  26476. return this._cachedVisibility;
  26477. };
  26478. /**
  26479. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  26480. * @param material defines the current material
  26481. * @param effect defines the current effect
  26482. * @param visibility defines the current visibility state
  26483. * @returns true if one parameter is not cached
  26484. */
  26485. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  26486. if (visibility === void 0) { visibility = 1; }
  26487. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  26488. };
  26489. /**
  26490. * Gets the engine associated with the scene
  26491. * @returns an Engine
  26492. */
  26493. Scene.prototype.getEngine = function () {
  26494. return this._engine;
  26495. };
  26496. /**
  26497. * Gets the total number of vertices rendered per frame
  26498. * @returns the total number of vertices rendered per frame
  26499. */
  26500. Scene.prototype.getTotalVertices = function () {
  26501. return this._totalVertices.current;
  26502. };
  26503. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  26504. /**
  26505. * Gets the performance counter for total vertices
  26506. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26507. */
  26508. get: function () {
  26509. return this._totalVertices;
  26510. },
  26511. enumerable: true,
  26512. configurable: true
  26513. });
  26514. /**
  26515. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  26516. * @returns the total number of active indices rendered per frame
  26517. */
  26518. Scene.prototype.getActiveIndices = function () {
  26519. return this._activeIndices.current;
  26520. };
  26521. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  26522. /**
  26523. * Gets the performance counter for active indices
  26524. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26525. */
  26526. get: function () {
  26527. return this._activeIndices;
  26528. },
  26529. enumerable: true,
  26530. configurable: true
  26531. });
  26532. /**
  26533. * Gets the total number of active particles rendered per frame
  26534. * @returns the total number of active particles rendered per frame
  26535. */
  26536. Scene.prototype.getActiveParticles = function () {
  26537. return this._activeParticles.current;
  26538. };
  26539. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  26540. /**
  26541. * Gets the performance counter for active particles
  26542. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26543. */
  26544. get: function () {
  26545. return this._activeParticles;
  26546. },
  26547. enumerable: true,
  26548. configurable: true
  26549. });
  26550. /**
  26551. * Gets the total number of active bones rendered per frame
  26552. * @returns the total number of active bones rendered per frame
  26553. */
  26554. Scene.prototype.getActiveBones = function () {
  26555. return this._activeBones.current;
  26556. };
  26557. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  26558. /**
  26559. * Gets the performance counter for active bones
  26560. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26561. */
  26562. get: function () {
  26563. return this._activeBones;
  26564. },
  26565. enumerable: true,
  26566. configurable: true
  26567. });
  26568. /**
  26569. * Gets the array of active meshes
  26570. * @returns an array of AbstractMesh
  26571. */
  26572. Scene.prototype.getActiveMeshes = function () {
  26573. return this._activeMeshes;
  26574. };
  26575. /**
  26576. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  26577. * @returns a number
  26578. */
  26579. Scene.prototype.getAnimationRatio = function () {
  26580. return this._animationRatio !== undefined ? this._animationRatio : 1;
  26581. };
  26582. /**
  26583. * Gets an unique Id for the current render phase
  26584. * @returns a number
  26585. */
  26586. Scene.prototype.getRenderId = function () {
  26587. return this._renderId;
  26588. };
  26589. /**
  26590. * Gets an unique Id for the current frame
  26591. * @returns a number
  26592. */
  26593. Scene.prototype.getFrameId = function () {
  26594. return this._frameId;
  26595. };
  26596. /** Call this function if you want to manually increment the render Id*/
  26597. Scene.prototype.incrementRenderId = function () {
  26598. this._renderId++;
  26599. };
  26600. Scene.prototype._updatePointerPosition = function (evt) {
  26601. var canvasRect = this._engine.getRenderingCanvasClientRect();
  26602. if (!canvasRect) {
  26603. return;
  26604. }
  26605. this._pointerX = evt.clientX - canvasRect.left;
  26606. this._pointerY = evt.clientY - canvasRect.top;
  26607. this._unTranslatedPointerX = this._pointerX;
  26608. this._unTranslatedPointerY = this._pointerY;
  26609. };
  26610. Scene.prototype._createUbo = function () {
  26611. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26612. this._sceneUbo.addUniform("viewProjection", 16);
  26613. this._sceneUbo.addUniform("view", 16);
  26614. };
  26615. Scene.prototype._createAlternateUbo = function () {
  26616. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26617. this._alternateSceneUbo.addUniform("viewProjection", 16);
  26618. this._alternateSceneUbo.addUniform("view", 16);
  26619. };
  26620. // Pointers handling
  26621. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  26622. if (pointerInfo.pickInfo) {
  26623. if (!pointerInfo.pickInfo.ray) {
  26624. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  26625. }
  26626. }
  26627. };
  26628. /**
  26629. * Use this method to simulate a pointer move on a mesh
  26630. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26631. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26632. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26633. * @returns the current scene
  26634. */
  26635. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  26636. var evt = new PointerEvent("pointermove", pointerEventInit);
  26637. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  26638. return this;
  26639. }
  26640. return this._processPointerMove(pickResult, evt);
  26641. };
  26642. Scene.prototype._processPointerMove = function (pickResult, evt) {
  26643. var canvas = this._engine.getRenderingCanvas();
  26644. if (!canvas) {
  26645. return this;
  26646. }
  26647. // Restore pointer
  26648. canvas.style.cursor = this.defaultCursor;
  26649. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  26650. if (isMeshPicked) {
  26651. this.setPointerOverMesh(pickResult.pickedMesh);
  26652. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  26653. if (this._pointerOverMesh.actionManager.hoverCursor) {
  26654. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  26655. }
  26656. else {
  26657. canvas.style.cursor = this.hoverCursor;
  26658. }
  26659. }
  26660. }
  26661. else {
  26662. this.setPointerOverMesh(null);
  26663. }
  26664. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  26665. var step = _a[_i];
  26666. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  26667. }
  26668. if (pickResult) {
  26669. var type = evt.type === this._wheelEventName ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  26670. if (this.onPointerMove) {
  26671. this.onPointerMove(evt, pickResult, type);
  26672. }
  26673. if (this.onPointerObservable.hasObservers()) {
  26674. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26675. this._setRayOnPointerInfo(pi);
  26676. this.onPointerObservable.notifyObservers(pi, type);
  26677. }
  26678. }
  26679. return this;
  26680. };
  26681. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  26682. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  26683. if (pickResult) {
  26684. pi.ray = pickResult.ray;
  26685. }
  26686. this.onPrePointerObservable.notifyObservers(pi, type);
  26687. if (pi.skipOnPointerObservable) {
  26688. return true;
  26689. }
  26690. else {
  26691. return false;
  26692. }
  26693. };
  26694. /**
  26695. * Use this method to simulate a pointer down on a mesh
  26696. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26697. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26698. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26699. * @returns the current scene
  26700. */
  26701. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  26702. var evt = new PointerEvent("pointerdown", pointerEventInit);
  26703. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26704. return this;
  26705. }
  26706. return this._processPointerDown(pickResult, evt);
  26707. };
  26708. Scene.prototype._processPointerDown = function (pickResult, evt) {
  26709. var _this = this;
  26710. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  26711. this._pickedDownMesh = pickResult.pickedMesh;
  26712. var actionManager = pickResult.pickedMesh.actionManager;
  26713. if (actionManager) {
  26714. if (actionManager.hasPickTriggers) {
  26715. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26716. switch (evt.button) {
  26717. case 0:
  26718. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26719. break;
  26720. case 1:
  26721. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26722. break;
  26723. case 2:
  26724. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26725. break;
  26726. }
  26727. }
  26728. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  26729. window.setTimeout(function () {
  26730. 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);
  26731. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  26732. if (_this._totalPointersPressed !== 0 &&
  26733. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  26734. !_this._isPointerSwiping()) {
  26735. _this._startingPointerTime = 0;
  26736. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26737. }
  26738. }
  26739. }, Scene.LongPressDelay);
  26740. }
  26741. }
  26742. }
  26743. else {
  26744. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  26745. var step = _a[_i];
  26746. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26747. }
  26748. }
  26749. if (pickResult) {
  26750. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  26751. if (this.onPointerDown) {
  26752. this.onPointerDown(evt, pickResult, type);
  26753. }
  26754. if (this.onPointerObservable.hasObservers()) {
  26755. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26756. this._setRayOnPointerInfo(pi);
  26757. this.onPointerObservable.notifyObservers(pi, type);
  26758. }
  26759. }
  26760. return this;
  26761. };
  26762. /**
  26763. * Use this method to simulate a pointer up on a mesh
  26764. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26765. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26766. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26767. * @param doubleTap indicates that the pointer up event should be considered as part of a double click (false by default)
  26768. * @returns the current scene
  26769. */
  26770. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit, doubleTap) {
  26771. var evt = new PointerEvent("pointerup", pointerEventInit);
  26772. var clickInfo = new ClickInfo();
  26773. if (doubleTap) {
  26774. clickInfo.doubleClick = true;
  26775. }
  26776. else {
  26777. clickInfo.singleClick = true;
  26778. }
  26779. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26780. return this;
  26781. }
  26782. return this._processPointerUp(pickResult, evt, clickInfo);
  26783. };
  26784. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  26785. if (pickResult && pickResult && pickResult.pickedMesh) {
  26786. this._pickedUpMesh = pickResult.pickedMesh;
  26787. if (this._pickedDownMesh === this._pickedUpMesh) {
  26788. if (this.onPointerPick) {
  26789. this.onPointerPick(evt, pickResult);
  26790. }
  26791. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  26792. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  26793. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  26794. this._setRayOnPointerInfo(pi);
  26795. this.onPointerObservable.notifyObservers(pi, type_1);
  26796. }
  26797. }
  26798. if (pickResult.pickedMesh.actionManager) {
  26799. if (clickInfo.ignore) {
  26800. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26801. }
  26802. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  26803. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26804. }
  26805. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26806. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26807. }
  26808. }
  26809. }
  26810. else {
  26811. if (!clickInfo.ignore) {
  26812. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  26813. var step = _a[_i];
  26814. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26815. }
  26816. }
  26817. }
  26818. if (this._pickedDownMesh &&
  26819. this._pickedDownMesh.actionManager &&
  26820. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  26821. this._pickedDownMesh !== this._pickedUpMesh) {
  26822. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  26823. }
  26824. var type = 0;
  26825. if (this.onPointerObservable.hasObservers()) {
  26826. if (!clickInfo.ignore && !clickInfo.hasSwiped) {
  26827. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26828. type = BABYLON.PointerEventTypes.POINTERTAP;
  26829. }
  26830. else if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26831. type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  26832. }
  26833. if (type) {
  26834. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26835. this._setRayOnPointerInfo(pi);
  26836. this.onPointerObservable.notifyObservers(pi, type);
  26837. }
  26838. }
  26839. if (!clickInfo.ignore) {
  26840. type = BABYLON.PointerEventTypes.POINTERUP;
  26841. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26842. this._setRayOnPointerInfo(pi);
  26843. this.onPointerObservable.notifyObservers(pi, type);
  26844. }
  26845. }
  26846. if (this.onPointerUp && !clickInfo.ignore) {
  26847. this.onPointerUp(evt, pickResult, type);
  26848. }
  26849. return this;
  26850. };
  26851. /**
  26852. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  26853. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  26854. * @returns true if the pointer was captured
  26855. */
  26856. Scene.prototype.isPointerCaptured = function (pointerId) {
  26857. if (pointerId === void 0) { pointerId = 0; }
  26858. return this._pointerCaptures[pointerId];
  26859. };
  26860. /** @hidden */
  26861. Scene.prototype._isPointerSwiping = function () {
  26862. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  26863. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  26864. };
  26865. /**
  26866. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  26867. * @param attachUp defines if you want to attach events to pointerup
  26868. * @param attachDown defines if you want to attach events to pointerdown
  26869. * @param attachMove defines if you want to attach events to pointermove
  26870. */
  26871. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  26872. var _this = this;
  26873. if (attachUp === void 0) { attachUp = true; }
  26874. if (attachDown === void 0) { attachDown = true; }
  26875. if (attachMove === void 0) { attachMove = true; }
  26876. this._initActionManager = function (act, clickInfo) {
  26877. if (!_this._meshPickProceed) {
  26878. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26879. _this._currentPickResult = pickResult;
  26880. if (pickResult) {
  26881. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  26882. }
  26883. _this._meshPickProceed = true;
  26884. }
  26885. return act;
  26886. };
  26887. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  26888. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  26889. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  26890. btn !== _this._previousButtonPressed) {
  26891. _this._doubleClickOccured = false;
  26892. clickInfo.singleClick = true;
  26893. clickInfo.ignore = false;
  26894. cb(clickInfo, _this._currentPickResult);
  26895. }
  26896. };
  26897. this._initClickEvent = function (obs1, obs2, evt, cb) {
  26898. var clickInfo = new ClickInfo();
  26899. _this._currentPickResult = null;
  26900. var act = null;
  26901. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  26902. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  26903. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26904. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  26905. act = _this._initActionManager(act, clickInfo);
  26906. if (act) {
  26907. checkPicking = act.hasPickTriggers;
  26908. }
  26909. }
  26910. var needToIgnoreNext = false;
  26911. if (checkPicking) {
  26912. var btn = evt.button;
  26913. clickInfo.hasSwiped = _this._isPointerSwiping();
  26914. if (!clickInfo.hasSwiped) {
  26915. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  26916. if (!checkSingleClickImmediately) {
  26917. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  26918. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26919. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26920. act = _this._initActionManager(act, clickInfo);
  26921. if (act) {
  26922. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26923. }
  26924. }
  26925. }
  26926. if (checkSingleClickImmediately) {
  26927. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  26928. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  26929. btn !== _this._previousButtonPressed) {
  26930. clickInfo.singleClick = true;
  26931. cb(clickInfo, _this._currentPickResult);
  26932. needToIgnoreNext = true;
  26933. }
  26934. }
  26935. // at least one double click is required to be check and exclusive double click is enabled
  26936. else {
  26937. // wait that no double click has been raised during the double click delay
  26938. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26939. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  26940. }
  26941. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  26942. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26943. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26944. act = _this._initActionManager(act, clickInfo);
  26945. if (act) {
  26946. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26947. }
  26948. }
  26949. if (checkDoubleClick) {
  26950. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  26951. if (btn === _this._previousButtonPressed &&
  26952. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  26953. !_this._doubleClickOccured) {
  26954. // pointer has not moved for 2 clicks, it's a double click
  26955. if (!clickInfo.hasSwiped &&
  26956. !_this._isPointerSwiping()) {
  26957. _this._previousStartingPointerTime = 0;
  26958. _this._doubleClickOccured = true;
  26959. clickInfo.doubleClick = true;
  26960. clickInfo.ignore = false;
  26961. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  26962. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26963. }
  26964. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26965. cb(clickInfo, _this._currentPickResult);
  26966. }
  26967. // if the two successive clicks are too far, it's just two simple clicks
  26968. else {
  26969. _this._doubleClickOccured = false;
  26970. _this._previousStartingPointerTime = _this._startingPointerTime;
  26971. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26972. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26973. _this._previousButtonPressed = btn;
  26974. if (Scene.ExclusiveDoubleClickMode) {
  26975. if (_this._previousDelayedSimpleClickTimeout) {
  26976. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26977. }
  26978. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26979. cb(clickInfo, _this._previousPickResult);
  26980. }
  26981. else {
  26982. cb(clickInfo, _this._currentPickResult);
  26983. }
  26984. }
  26985. needToIgnoreNext = true;
  26986. }
  26987. // just the first click of the double has been raised
  26988. else {
  26989. _this._doubleClickOccured = false;
  26990. _this._previousStartingPointerTime = _this._startingPointerTime;
  26991. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26992. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26993. _this._previousButtonPressed = btn;
  26994. }
  26995. }
  26996. }
  26997. }
  26998. if (!needToIgnoreNext) {
  26999. cb(clickInfo, _this._currentPickResult);
  27000. }
  27001. };
  27002. this._onPointerMove = function (evt) {
  27003. _this._updatePointerPosition(evt);
  27004. // PreObservable support
  27005. if (_this._checkPrePointerObservable(null, evt, evt.type === _this._wheelEventName ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  27006. return;
  27007. }
  27008. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  27009. return;
  27010. }
  27011. if (!_this.pointerMovePredicate) {
  27012. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  27013. }
  27014. // Meshes
  27015. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  27016. _this._processPointerMove(pickResult, evt);
  27017. };
  27018. this._onPointerDown = function (evt) {
  27019. _this._totalPointersPressed++;
  27020. _this._pickedDownMesh = null;
  27021. _this._meshPickProceed = false;
  27022. _this._updatePointerPosition(evt);
  27023. if (_this.preventDefaultOnPointerDown && canvas) {
  27024. evt.preventDefault();
  27025. canvas.focus();
  27026. }
  27027. _this._startingPointerPosition.x = _this._pointerX;
  27028. _this._startingPointerPosition.y = _this._pointerY;
  27029. _this._startingPointerTime = Date.now();
  27030. // PreObservable support
  27031. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  27032. return;
  27033. }
  27034. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  27035. return;
  27036. }
  27037. _this._pointerCaptures[evt.pointerId] = true;
  27038. if (!_this.pointerDownPredicate) {
  27039. _this.pointerDownPredicate = function (mesh) {
  27040. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  27041. };
  27042. }
  27043. // Meshes
  27044. _this._pickedDownMesh = null;
  27045. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  27046. _this._processPointerDown(pickResult, evt);
  27047. };
  27048. this._onPointerUp = function (evt) {
  27049. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  27050. return; // So we need to test it the pointer down was pressed before.
  27051. }
  27052. _this._totalPointersPressed--;
  27053. _this._pickedUpMesh = null;
  27054. _this._meshPickProceed = false;
  27055. _this._updatePointerPosition(evt);
  27056. if (_this.preventDefaultOnPointerUp && canvas) {
  27057. evt.preventDefault();
  27058. canvas.focus();
  27059. }
  27060. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  27061. _this._pointerCaptures[evt.pointerId] = false;
  27062. // PreObservable support
  27063. if (_this.onPrePointerObservable.hasObservers()) {
  27064. if (!clickInfo.ignore) {
  27065. if (!clickInfo.hasSwiped) {
  27066. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  27067. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  27068. return;
  27069. }
  27070. }
  27071. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  27072. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  27073. return;
  27074. }
  27075. }
  27076. }
  27077. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  27078. return;
  27079. }
  27080. }
  27081. }
  27082. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  27083. return;
  27084. }
  27085. if (!_this.pointerUpPredicate) {
  27086. _this.pointerUpPredicate = function (mesh) {
  27087. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  27088. };
  27089. }
  27090. // Meshes
  27091. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  27092. _this._initActionManager(null, clickInfo);
  27093. }
  27094. if (!pickResult) {
  27095. pickResult = _this._currentPickResult;
  27096. }
  27097. _this._processPointerUp(pickResult, evt, clickInfo);
  27098. _this._previousPickResult = _this._currentPickResult;
  27099. });
  27100. };
  27101. this._onKeyDown = function (evt) {
  27102. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  27103. if (_this.onPreKeyboardObservable.hasObservers()) {
  27104. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  27105. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  27106. if (pi.skipOnPointerObservable) {
  27107. return;
  27108. }
  27109. }
  27110. if (_this.onKeyboardObservable.hasObservers()) {
  27111. var pi = new BABYLON.KeyboardInfo(type, evt);
  27112. _this.onKeyboardObservable.notifyObservers(pi, type);
  27113. }
  27114. if (_this.actionManager) {
  27115. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  27116. }
  27117. };
  27118. this._onKeyUp = function (evt) {
  27119. var type = BABYLON.KeyboardEventTypes.KEYUP;
  27120. if (_this.onPreKeyboardObservable.hasObservers()) {
  27121. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  27122. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  27123. if (pi.skipOnPointerObservable) {
  27124. return;
  27125. }
  27126. }
  27127. if (_this.onKeyboardObservable.hasObservers()) {
  27128. var pi = new BABYLON.KeyboardInfo(type, evt);
  27129. _this.onKeyboardObservable.notifyObservers(pi, type);
  27130. }
  27131. if (_this.actionManager) {
  27132. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  27133. }
  27134. };
  27135. var engine = this.getEngine();
  27136. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  27137. if (!canvas) {
  27138. return;
  27139. }
  27140. canvas.addEventListener("keydown", _this._onKeyDown, false);
  27141. canvas.addEventListener("keyup", _this._onKeyUp, false);
  27142. });
  27143. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  27144. if (!canvas) {
  27145. return;
  27146. }
  27147. canvas.removeEventListener("keydown", _this._onKeyDown);
  27148. canvas.removeEventListener("keyup", _this._onKeyUp);
  27149. });
  27150. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  27151. var canvas = this._engine.getRenderingCanvas();
  27152. if (!canvas) {
  27153. return;
  27154. }
  27155. if (attachMove) {
  27156. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  27157. // Wheel
  27158. this._wheelEventName = "onwheel" in document.createElement("div") ? "wheel" : // Modern browsers support "wheel"
  27159. document.onmousewheel !== undefined ? "mousewheel" : // Webkit and IE support at least "mousewheel"
  27160. "DOMMouseScroll"; // let's assume that remaining browsers are older Firefox
  27161. canvas.addEventListener(this._wheelEventName, this._onPointerMove, false);
  27162. }
  27163. if (attachDown) {
  27164. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  27165. }
  27166. if (attachUp) {
  27167. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  27168. }
  27169. canvas.tabIndex = 1;
  27170. };
  27171. /** Detaches all event handlers*/
  27172. Scene.prototype.detachControl = function () {
  27173. var engine = this.getEngine();
  27174. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  27175. var canvas = engine.getRenderingCanvas();
  27176. if (!canvas) {
  27177. return;
  27178. }
  27179. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  27180. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  27181. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  27182. if (this._onCanvasBlurObserver) {
  27183. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  27184. }
  27185. if (this._onCanvasFocusObserver) {
  27186. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  27187. }
  27188. // Wheel
  27189. canvas.removeEventListener(this._wheelEventName, this._onPointerMove);
  27190. // Keyboard
  27191. canvas.removeEventListener("keydown", this._onKeyDown);
  27192. canvas.removeEventListener("keyup", this._onKeyUp);
  27193. // Observables
  27194. this.onKeyboardObservable.clear();
  27195. this.onPreKeyboardObservable.clear();
  27196. this.onPointerObservable.clear();
  27197. this.onPrePointerObservable.clear();
  27198. };
  27199. /**
  27200. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  27201. * Delay loaded resources are not taking in account
  27202. * @return true if all required resources are ready
  27203. */
  27204. Scene.prototype.isReady = function () {
  27205. if (this._isDisposed) {
  27206. return false;
  27207. }
  27208. var index;
  27209. var engine = this.getEngine();
  27210. // Effects
  27211. if (!engine.areAllEffectsReady()) {
  27212. return false;
  27213. }
  27214. // Pending data
  27215. if (this._pendingData.length > 0) {
  27216. return false;
  27217. }
  27218. // Meshes
  27219. for (index = 0; index < this.meshes.length; index++) {
  27220. var mesh = this.meshes[index];
  27221. if (!mesh.isEnabled()) {
  27222. continue;
  27223. }
  27224. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  27225. continue;
  27226. }
  27227. if (!mesh.isReady(true)) {
  27228. return false;
  27229. }
  27230. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  27231. // Is Ready For Mesh
  27232. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  27233. var step = _a[_i];
  27234. if (!step.action(mesh, hardwareInstancedRendering)) {
  27235. return false;
  27236. }
  27237. }
  27238. }
  27239. // Geometries
  27240. for (index = 0; index < this.geometries.length; index++) {
  27241. var geometry = this.geometries[index];
  27242. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27243. return false;
  27244. }
  27245. }
  27246. // Post-processes
  27247. if (this.activeCameras && this.activeCameras.length > 0) {
  27248. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  27249. var camera = _c[_b];
  27250. if (!camera.isReady(true)) {
  27251. return false;
  27252. }
  27253. }
  27254. }
  27255. else if (this.activeCamera) {
  27256. if (!this.activeCamera.isReady(true)) {
  27257. return false;
  27258. }
  27259. }
  27260. // Particles
  27261. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  27262. var particleSystem = _e[_d];
  27263. if (!particleSystem.isReady()) {
  27264. return false;
  27265. }
  27266. }
  27267. return true;
  27268. };
  27269. /** Resets all cached information relative to material (including effect and visibility) */
  27270. Scene.prototype.resetCachedMaterial = function () {
  27271. this._cachedMaterial = null;
  27272. this._cachedEffect = null;
  27273. this._cachedVisibility = null;
  27274. };
  27275. /**
  27276. * Registers a function to be called before every frame render
  27277. * @param func defines the function to register
  27278. */
  27279. Scene.prototype.registerBeforeRender = function (func) {
  27280. this.onBeforeRenderObservable.add(func);
  27281. };
  27282. /**
  27283. * Unregisters a function called before every frame render
  27284. * @param func defines the function to unregister
  27285. */
  27286. Scene.prototype.unregisterBeforeRender = function (func) {
  27287. this.onBeforeRenderObservable.removeCallback(func);
  27288. };
  27289. /**
  27290. * Registers a function to be called after every frame render
  27291. * @param func defines the function to register
  27292. */
  27293. Scene.prototype.registerAfterRender = function (func) {
  27294. this.onAfterRenderObservable.add(func);
  27295. };
  27296. /**
  27297. * Unregisters a function called after every frame render
  27298. * @param func defines the function to unregister
  27299. */
  27300. Scene.prototype.unregisterAfterRender = function (func) {
  27301. this.onAfterRenderObservable.removeCallback(func);
  27302. };
  27303. Scene.prototype._executeOnceBeforeRender = function (func) {
  27304. var _this = this;
  27305. var execFunc = function () {
  27306. func();
  27307. setTimeout(function () {
  27308. _this.unregisterBeforeRender(execFunc);
  27309. });
  27310. };
  27311. this.registerBeforeRender(execFunc);
  27312. };
  27313. /**
  27314. * The provided function will run before render once and will be disposed afterwards.
  27315. * A timeout delay can be provided so that the function will be executed in N ms.
  27316. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  27317. * @param func The function to be executed.
  27318. * @param timeout optional delay in ms
  27319. */
  27320. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  27321. var _this = this;
  27322. if (timeout !== undefined) {
  27323. setTimeout(function () {
  27324. _this._executeOnceBeforeRender(func);
  27325. }, timeout);
  27326. }
  27327. else {
  27328. this._executeOnceBeforeRender(func);
  27329. }
  27330. };
  27331. /** @hidden */
  27332. Scene.prototype._addPendingData = function (data) {
  27333. this._pendingData.push(data);
  27334. };
  27335. /** @hidden */
  27336. Scene.prototype._removePendingData = function (data) {
  27337. var wasLoading = this.isLoading;
  27338. var index = this._pendingData.indexOf(data);
  27339. if (index !== -1) {
  27340. this._pendingData.splice(index, 1);
  27341. }
  27342. if (wasLoading && !this.isLoading) {
  27343. this.onDataLoadedObservable.notifyObservers(this);
  27344. }
  27345. };
  27346. /**
  27347. * Returns the number of items waiting to be loaded
  27348. * @returns the number of items waiting to be loaded
  27349. */
  27350. Scene.prototype.getWaitingItemsCount = function () {
  27351. return this._pendingData.length;
  27352. };
  27353. Object.defineProperty(Scene.prototype, "isLoading", {
  27354. /**
  27355. * Returns a boolean indicating if the scene is still loading data
  27356. */
  27357. get: function () {
  27358. return this._pendingData.length > 0;
  27359. },
  27360. enumerable: true,
  27361. configurable: true
  27362. });
  27363. /**
  27364. * Registers a function to be executed when the scene is ready
  27365. * @param {Function} func - the function to be executed
  27366. */
  27367. Scene.prototype.executeWhenReady = function (func) {
  27368. var _this = this;
  27369. this.onReadyObservable.add(func);
  27370. if (this._executeWhenReadyTimeoutId !== -1) {
  27371. return;
  27372. }
  27373. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27374. _this._checkIsReady();
  27375. }, 150);
  27376. };
  27377. /**
  27378. * Returns a promise that resolves when the scene is ready
  27379. * @returns A promise that resolves when the scene is ready
  27380. */
  27381. Scene.prototype.whenReadyAsync = function () {
  27382. var _this = this;
  27383. return new Promise(function (resolve) {
  27384. _this.executeWhenReady(function () {
  27385. resolve();
  27386. });
  27387. });
  27388. };
  27389. /** @hidden */
  27390. Scene.prototype._checkIsReady = function () {
  27391. var _this = this;
  27392. this._registerTransientComponents();
  27393. if (this.isReady()) {
  27394. this.onReadyObservable.notifyObservers(this);
  27395. this.onReadyObservable.clear();
  27396. this._executeWhenReadyTimeoutId = -1;
  27397. return;
  27398. }
  27399. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27400. _this._checkIsReady();
  27401. }, 150);
  27402. };
  27403. // Animations
  27404. /**
  27405. * Will start the animation sequence of a given target
  27406. * @param target defines the target
  27407. * @param from defines from which frame should animation start
  27408. * @param to defines until which frame should animation run.
  27409. * @param weight defines the weight to apply to the animation (1.0 by default)
  27410. * @param loop defines if the animation loops
  27411. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27412. * @param onAnimationEnd defines the function to be executed when the animation ends
  27413. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27414. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27415. * @returns the animatable object created for this animation
  27416. */
  27417. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  27418. if (weight === void 0) { weight = 1.0; }
  27419. if (speedRatio === void 0) { speedRatio = 1.0; }
  27420. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  27421. returnedAnimatable.weight = weight;
  27422. return returnedAnimatable;
  27423. };
  27424. /**
  27425. * Will start the animation sequence of a given target
  27426. * @param target defines the target
  27427. * @param from defines from which frame should animation start
  27428. * @param to defines until which frame should animation run.
  27429. * @param loop defines if the animation loops
  27430. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27431. * @param onAnimationEnd defines the function to be executed when the animation ends
  27432. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27433. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  27434. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27435. * @returns the animatable object created for this animation
  27436. */
  27437. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  27438. if (speedRatio === void 0) { speedRatio = 1.0; }
  27439. if (stopCurrent === void 0) { stopCurrent = true; }
  27440. if (from > to && speedRatio > 0) {
  27441. speedRatio *= -1;
  27442. }
  27443. if (stopCurrent) {
  27444. this.stopAnimation(target, undefined, targetMask);
  27445. }
  27446. if (!animatable) {
  27447. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  27448. }
  27449. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  27450. // Local animations
  27451. if (target.animations && shouldRunTargetAnimations) {
  27452. animatable.appendAnimations(target, target.animations);
  27453. }
  27454. // Children animations
  27455. if (target.getAnimatables) {
  27456. var animatables = target.getAnimatables();
  27457. for (var index = 0; index < animatables.length; index++) {
  27458. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  27459. }
  27460. }
  27461. animatable.reset();
  27462. return animatable;
  27463. };
  27464. /**
  27465. * Begin a new animation on a given node
  27466. * @param target defines the target where the animation will take place
  27467. * @param animations defines the list of animations to start
  27468. * @param from defines the initial value
  27469. * @param to defines the final value
  27470. * @param loop defines if you want animation to loop (off by default)
  27471. * @param speedRatio defines the speed ratio to apply to all animations
  27472. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27473. * @returns the list of created animatables
  27474. */
  27475. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27476. if (speedRatio === undefined) {
  27477. speedRatio = 1.0;
  27478. }
  27479. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  27480. return animatable;
  27481. };
  27482. /**
  27483. * Begin a new animation on a given node and its hierarchy
  27484. * @param target defines the root node where the animation will take place
  27485. * @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.
  27486. * @param animations defines the list of animations to start
  27487. * @param from defines the initial value
  27488. * @param to defines the final value
  27489. * @param loop defines if you want animation to loop (off by default)
  27490. * @param speedRatio defines the speed ratio to apply to all animations
  27491. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27492. * @returns the list of animatables created for all nodes
  27493. */
  27494. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27495. var children = target.getDescendants(directDescendantsOnly);
  27496. var result = [];
  27497. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  27498. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  27499. var child = children_1[_i];
  27500. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  27501. }
  27502. return result;
  27503. };
  27504. /**
  27505. * Gets the animatable associated with a specific target
  27506. * @param target defines the target of the animatable
  27507. * @returns the required animatable if found
  27508. */
  27509. Scene.prototype.getAnimatableByTarget = function (target) {
  27510. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27511. if (this._activeAnimatables[index].target === target) {
  27512. return this._activeAnimatables[index];
  27513. }
  27514. }
  27515. return null;
  27516. };
  27517. /**
  27518. * Gets all animatables associated with a given target
  27519. * @param target defines the target to look animatables for
  27520. * @returns an array of Animatables
  27521. */
  27522. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  27523. var result = [];
  27524. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27525. if (this._activeAnimatables[index].target === target) {
  27526. result.push(this._activeAnimatables[index]);
  27527. }
  27528. }
  27529. return result;
  27530. };
  27531. Object.defineProperty(Scene.prototype, "animatables", {
  27532. /**
  27533. * Gets all animatable attached to the scene
  27534. */
  27535. get: function () {
  27536. return this._activeAnimatables;
  27537. },
  27538. enumerable: true,
  27539. configurable: true
  27540. });
  27541. /**
  27542. * Will stop the animation of the given target
  27543. * @param target - the target
  27544. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  27545. * @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)
  27546. */
  27547. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  27548. var animatables = this.getAllAnimatablesByTarget(target);
  27549. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  27550. var animatable = animatables_1[_i];
  27551. animatable.stop(animationName, targetMask);
  27552. }
  27553. };
  27554. /**
  27555. * Stops and removes all animations that have been applied to the scene
  27556. */
  27557. Scene.prototype.stopAllAnimations = function () {
  27558. if (this._activeAnimatables) {
  27559. for (var i = 0; i < this._activeAnimatables.length; i++) {
  27560. this._activeAnimatables[i].stop();
  27561. }
  27562. this._activeAnimatables = [];
  27563. }
  27564. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  27565. var group = _a[_i];
  27566. group.stop();
  27567. }
  27568. };
  27569. Scene.prototype._animate = function () {
  27570. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  27571. return;
  27572. }
  27573. // Getting time
  27574. var now = BABYLON.Tools.Now;
  27575. if (!this._animationTimeLast) {
  27576. if (this._pendingData.length > 0) {
  27577. return;
  27578. }
  27579. this._animationTimeLast = now;
  27580. }
  27581. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  27582. this._animationTime += deltaTime;
  27583. this._animationTimeLast = now;
  27584. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27585. this._activeAnimatables[index]._animate(this._animationTime);
  27586. }
  27587. // Late animation bindings
  27588. this._processLateAnimationBindings();
  27589. };
  27590. /** @hidden */
  27591. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  27592. var target = runtimeAnimation.target;
  27593. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  27594. if (!target._lateAnimationHolders) {
  27595. target._lateAnimationHolders = {};
  27596. }
  27597. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  27598. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  27599. totalWeight: 0,
  27600. animations: [],
  27601. originalValue: originalValue
  27602. };
  27603. }
  27604. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  27605. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  27606. };
  27607. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  27608. var normalizer = 1.0;
  27609. var finalPosition = BABYLON.Tmp.Vector3[0];
  27610. var finalScaling = BABYLON.Tmp.Vector3[1];
  27611. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  27612. var startIndex = 0;
  27613. var originalAnimation = holder.animations[0];
  27614. var originalValue = holder.originalValue;
  27615. var scale = 1;
  27616. if (holder.totalWeight < 1.0) {
  27617. // We need to mix the original value in
  27618. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27619. scale = 1.0 - holder.totalWeight;
  27620. }
  27621. else {
  27622. startIndex = 1;
  27623. // We need to normalize the weights
  27624. normalizer = holder.totalWeight;
  27625. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27626. scale = originalAnimation.weight / normalizer;
  27627. if (scale == 1) {
  27628. return originalAnimation.currentValue;
  27629. }
  27630. }
  27631. finalScaling.scaleInPlace(scale);
  27632. finalPosition.scaleInPlace(scale);
  27633. finalQuaternion.scaleInPlace(scale);
  27634. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27635. var runtimeAnimation = holder.animations[animIndex];
  27636. var scale = runtimeAnimation.weight / normalizer;
  27637. var currentPosition = BABYLON.Tmp.Vector3[2];
  27638. var currentScaling = BABYLON.Tmp.Vector3[3];
  27639. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  27640. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  27641. currentScaling.scaleAndAddToRef(scale, finalScaling);
  27642. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  27643. currentPosition.scaleAndAddToRef(scale, finalPosition);
  27644. }
  27645. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  27646. return originalAnimation._workValue;
  27647. };
  27648. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  27649. var originalAnimation = holder.animations[0];
  27650. var originalValue = holder.originalValue;
  27651. if (holder.animations.length === 1) {
  27652. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  27653. return refQuaternion;
  27654. }
  27655. var normalizer = 1.0;
  27656. var quaternions;
  27657. var weights;
  27658. if (holder.totalWeight < 1.0) {
  27659. var scale = 1.0 - holder.totalWeight;
  27660. quaternions = [];
  27661. weights = [];
  27662. quaternions.push(originalValue);
  27663. weights.push(scale);
  27664. }
  27665. else {
  27666. if (holder.animations.length === 2) { // Slerp as soon as we can
  27667. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  27668. return refQuaternion;
  27669. }
  27670. quaternions = [];
  27671. weights = [];
  27672. normalizer = holder.totalWeight;
  27673. }
  27674. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  27675. var runtimeAnimation = holder.animations[animIndex];
  27676. quaternions.push(runtimeAnimation.currentValue);
  27677. weights.push(runtimeAnimation.weight / normalizer);
  27678. }
  27679. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  27680. var cumulativeAmount = 0;
  27681. var cumulativeQuaternion = null;
  27682. for (var index = 0; index < quaternions.length;) {
  27683. if (!cumulativeQuaternion) {
  27684. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  27685. cumulativeQuaternion = refQuaternion;
  27686. cumulativeAmount = weights[index] + weights[index + 1];
  27687. index += 2;
  27688. continue;
  27689. }
  27690. cumulativeAmount += weights[index];
  27691. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  27692. index++;
  27693. }
  27694. return cumulativeQuaternion;
  27695. };
  27696. Scene.prototype._processLateAnimationBindings = function () {
  27697. if (!this._registeredForLateAnimationBindings.length) {
  27698. return;
  27699. }
  27700. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  27701. var target = this._registeredForLateAnimationBindings.data[index];
  27702. for (var path in target._lateAnimationHolders) {
  27703. var holder = target._lateAnimationHolders[path];
  27704. var originalAnimation = holder.animations[0];
  27705. var originalValue = holder.originalValue;
  27706. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  27707. var finalValue = target[path];
  27708. if (matrixDecomposeMode) {
  27709. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  27710. }
  27711. else {
  27712. var quaternionMode = originalValue.w !== undefined;
  27713. if (quaternionMode) {
  27714. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  27715. }
  27716. else {
  27717. var startIndex = 0;
  27718. var normalizer = 1.0;
  27719. if (holder.totalWeight < 1.0) {
  27720. // We need to mix the original value in
  27721. if (originalValue.scale) {
  27722. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  27723. }
  27724. else {
  27725. finalValue = originalValue * (1.0 - holder.totalWeight);
  27726. }
  27727. }
  27728. else {
  27729. // We need to normalize the weights
  27730. normalizer = holder.totalWeight;
  27731. var scale_1 = originalAnimation.weight / normalizer;
  27732. if (scale_1 !== 1) {
  27733. if (originalAnimation.currentValue.scale) {
  27734. finalValue = originalAnimation.currentValue.scale(scale_1);
  27735. }
  27736. else {
  27737. finalValue = originalAnimation.currentValue * scale_1;
  27738. }
  27739. }
  27740. else {
  27741. finalValue = originalAnimation.currentValue;
  27742. }
  27743. startIndex = 1;
  27744. }
  27745. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27746. var runtimeAnimation = holder.animations[animIndex];
  27747. var scale = runtimeAnimation.weight / normalizer;
  27748. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  27749. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  27750. }
  27751. else {
  27752. finalValue += runtimeAnimation.currentValue * scale;
  27753. }
  27754. }
  27755. }
  27756. }
  27757. target[path] = finalValue;
  27758. }
  27759. target._lateAnimationHolders = {};
  27760. }
  27761. this._registeredForLateAnimationBindings.reset();
  27762. };
  27763. // Matrix
  27764. /** @hidden */
  27765. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  27766. this._useAlternateCameraConfiguration = active;
  27767. };
  27768. /**
  27769. * Gets the current view matrix
  27770. * @returns a Matrix
  27771. */
  27772. Scene.prototype.getViewMatrix = function () {
  27773. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  27774. };
  27775. /**
  27776. * Gets the current projection matrix
  27777. * @returns a Matrix
  27778. */
  27779. Scene.prototype.getProjectionMatrix = function () {
  27780. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  27781. };
  27782. /**
  27783. * Gets the current transform matrix
  27784. * @returns a Matrix made of View * Projection
  27785. */
  27786. Scene.prototype.getTransformMatrix = function () {
  27787. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  27788. };
  27789. /**
  27790. * Sets the current transform matrix
  27791. * @param view defines the View matrix to use
  27792. * @param projection defines the Projection matrix to use
  27793. */
  27794. Scene.prototype.setTransformMatrix = function (view, projection) {
  27795. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  27796. return;
  27797. }
  27798. this._viewUpdateFlag = view.updateFlag;
  27799. this._projectionUpdateFlag = projection.updateFlag;
  27800. this._viewMatrix = view;
  27801. this._projectionMatrix = projection;
  27802. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  27803. // Update frustum
  27804. if (!this._frustumPlanes) {
  27805. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  27806. }
  27807. else {
  27808. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  27809. }
  27810. if (this.activeCamera && this.activeCamera._alternateCamera) {
  27811. var otherCamera = this.activeCamera._alternateCamera;
  27812. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  27813. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  27814. }
  27815. if (this._sceneUbo.useUbo) {
  27816. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  27817. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  27818. this._sceneUbo.update();
  27819. }
  27820. };
  27821. /** @hidden */
  27822. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  27823. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  27824. return;
  27825. }
  27826. this._alternateViewUpdateFlag = view.updateFlag;
  27827. this._alternateProjectionUpdateFlag = projection.updateFlag;
  27828. this._alternateViewMatrix = view;
  27829. this._alternateProjectionMatrix = projection;
  27830. if (!this._alternateTransformMatrix) {
  27831. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  27832. }
  27833. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  27834. if (!this._alternateSceneUbo) {
  27835. this._createAlternateUbo();
  27836. }
  27837. if (this._alternateSceneUbo.useUbo) {
  27838. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  27839. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  27840. this._alternateSceneUbo.update();
  27841. }
  27842. };
  27843. /**
  27844. * Gets the uniform buffer used to store scene data
  27845. * @returns a UniformBuffer
  27846. */
  27847. Scene.prototype.getSceneUniformBuffer = function () {
  27848. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  27849. };
  27850. /**
  27851. * Gets an unique (relatively to the current scene) Id
  27852. * @returns an unique number for the scene
  27853. */
  27854. Scene.prototype.getUniqueId = function () {
  27855. var result = Scene._uniqueIdCounter;
  27856. Scene._uniqueIdCounter++;
  27857. return result;
  27858. };
  27859. /**
  27860. * Add a mesh to the list of scene's meshes
  27861. * @param newMesh defines the mesh to add
  27862. * @param recursive if all child meshes should also be added to the scene
  27863. */
  27864. Scene.prototype.addMesh = function (newMesh, recursive) {
  27865. var _this = this;
  27866. if (recursive === void 0) { recursive = false; }
  27867. this.meshes.push(newMesh);
  27868. //notify the collision coordinator
  27869. if (this.collisionCoordinator) {
  27870. this.collisionCoordinator.onMeshAdded(newMesh);
  27871. }
  27872. newMesh._resyncLightSources();
  27873. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  27874. if (recursive) {
  27875. newMesh.getChildMeshes().forEach(function (m) {
  27876. _this.addMesh(m);
  27877. });
  27878. }
  27879. };
  27880. /**
  27881. * Remove a mesh for the list of scene's meshes
  27882. * @param toRemove defines the mesh to remove
  27883. * @param recursive if all child meshes should also be removed from the scene
  27884. * @returns the index where the mesh was in the mesh list
  27885. */
  27886. Scene.prototype.removeMesh = function (toRemove, recursive) {
  27887. var _this = this;
  27888. if (recursive === void 0) { recursive = false; }
  27889. var index = this.meshes.indexOf(toRemove);
  27890. if (index !== -1) {
  27891. // Remove from the scene if mesh found
  27892. this.meshes[index] = this.meshes[this.meshes.length - 1];
  27893. this.meshes.pop();
  27894. }
  27895. this.onMeshRemovedObservable.notifyObservers(toRemove);
  27896. if (recursive) {
  27897. toRemove.getChildMeshes().forEach(function (m) {
  27898. _this.removeMesh(m);
  27899. });
  27900. }
  27901. return index;
  27902. };
  27903. /**
  27904. * Add a transform node to the list of scene's transform nodes
  27905. * @param newTransformNode defines the transform node to add
  27906. */
  27907. Scene.prototype.addTransformNode = function (newTransformNode) {
  27908. newTransformNode._indexInSceneTransformNodesArray = this.transformNodes.length;
  27909. this.transformNodes.push(newTransformNode);
  27910. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  27911. };
  27912. /**
  27913. * Remove a transform node for the list of scene's transform nodes
  27914. * @param toRemove defines the transform node to remove
  27915. * @returns the index where the transform node was in the transform node list
  27916. */
  27917. Scene.prototype.removeTransformNode = function (toRemove) {
  27918. var index = toRemove._indexInSceneTransformNodesArray;
  27919. if (index !== -1) {
  27920. if (index !== this.transformNodes.length - 1) {
  27921. var lastNode = this.transformNodes[this.transformNodes.length - 1];
  27922. this.transformNodes[index] = lastNode;
  27923. lastNode._indexInSceneTransformNodesArray = index;
  27924. }
  27925. toRemove._indexInSceneTransformNodesArray = -1;
  27926. this.transformNodes.pop();
  27927. }
  27928. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  27929. return index;
  27930. };
  27931. /**
  27932. * Remove a skeleton for the list of scene's skeletons
  27933. * @param toRemove defines the skeleton to remove
  27934. * @returns the index where the skeleton was in the skeleton list
  27935. */
  27936. Scene.prototype.removeSkeleton = function (toRemove) {
  27937. var index = this.skeletons.indexOf(toRemove);
  27938. if (index !== -1) {
  27939. // Remove from the scene if found
  27940. this.skeletons.splice(index, 1);
  27941. }
  27942. return index;
  27943. };
  27944. /**
  27945. * Remove a morph target for the list of scene's morph targets
  27946. * @param toRemove defines the morph target to remove
  27947. * @returns the index where the morph target was in the morph target list
  27948. */
  27949. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  27950. var index = this.morphTargetManagers.indexOf(toRemove);
  27951. if (index !== -1) {
  27952. // Remove from the scene if found
  27953. this.morphTargetManagers.splice(index, 1);
  27954. }
  27955. return index;
  27956. };
  27957. /**
  27958. * Remove a light for the list of scene's lights
  27959. * @param toRemove defines the light to remove
  27960. * @returns the index where the light was in the light list
  27961. */
  27962. Scene.prototype.removeLight = function (toRemove) {
  27963. var index = this.lights.indexOf(toRemove);
  27964. if (index !== -1) {
  27965. // Remove from meshes
  27966. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27967. var mesh = _a[_i];
  27968. mesh._removeLightSource(toRemove);
  27969. }
  27970. // Remove from the scene if mesh found
  27971. this.lights.splice(index, 1);
  27972. this.sortLightsByPriority();
  27973. }
  27974. this.onLightRemovedObservable.notifyObservers(toRemove);
  27975. return index;
  27976. };
  27977. /**
  27978. * Remove a camera for the list of scene's cameras
  27979. * @param toRemove defines the camera to remove
  27980. * @returns the index where the camera was in the camera list
  27981. */
  27982. Scene.prototype.removeCamera = function (toRemove) {
  27983. var index = this.cameras.indexOf(toRemove);
  27984. if (index !== -1) {
  27985. // Remove from the scene if mesh found
  27986. this.cameras.splice(index, 1);
  27987. }
  27988. // Remove from activeCameras
  27989. var index2 = this.activeCameras.indexOf(toRemove);
  27990. if (index2 !== -1) {
  27991. // Remove from the scene if mesh found
  27992. this.activeCameras.splice(index2, 1);
  27993. }
  27994. // Reset the activeCamera
  27995. if (this.activeCamera === toRemove) {
  27996. if (this.cameras.length > 0) {
  27997. this.activeCamera = this.cameras[0];
  27998. }
  27999. else {
  28000. this.activeCamera = null;
  28001. }
  28002. }
  28003. this.onCameraRemovedObservable.notifyObservers(toRemove);
  28004. return index;
  28005. };
  28006. /**
  28007. * Remove a particle system for the list of scene's particle systems
  28008. * @param toRemove defines the particle system to remove
  28009. * @returns the index where the particle system was in the particle system list
  28010. */
  28011. Scene.prototype.removeParticleSystem = function (toRemove) {
  28012. var index = this.particleSystems.indexOf(toRemove);
  28013. if (index !== -1) {
  28014. this.particleSystems.splice(index, 1);
  28015. }
  28016. return index;
  28017. };
  28018. /**
  28019. * Remove a animation for the list of scene's animations
  28020. * @param toRemove defines the animation to remove
  28021. * @returns the index where the animation was in the animation list
  28022. */
  28023. Scene.prototype.removeAnimation = function (toRemove) {
  28024. var index = this.animations.indexOf(toRemove);
  28025. if (index !== -1) {
  28026. this.animations.splice(index, 1);
  28027. }
  28028. return index;
  28029. };
  28030. /**
  28031. * Removes the given animation group from this scene.
  28032. * @param toRemove The animation group to remove
  28033. * @returns The index of the removed animation group
  28034. */
  28035. Scene.prototype.removeAnimationGroup = function (toRemove) {
  28036. var index = this.animationGroups.indexOf(toRemove);
  28037. if (index !== -1) {
  28038. this.animationGroups.splice(index, 1);
  28039. }
  28040. return index;
  28041. };
  28042. /**
  28043. * Removes the given multi-material from this scene.
  28044. * @param toRemove The multi-material to remove
  28045. * @returns The index of the removed multi-material
  28046. */
  28047. Scene.prototype.removeMultiMaterial = function (toRemove) {
  28048. var index = this.multiMaterials.indexOf(toRemove);
  28049. if (index !== -1) {
  28050. this.multiMaterials.splice(index, 1);
  28051. }
  28052. return index;
  28053. };
  28054. /**
  28055. * Removes the given material from this scene.
  28056. * @param toRemove The material to remove
  28057. * @returns The index of the removed material
  28058. */
  28059. Scene.prototype.removeMaterial = function (toRemove) {
  28060. var index = toRemove._indexInSceneMaterialArray;
  28061. if (index !== -1) {
  28062. if (index !== this.materials.length - 1) {
  28063. var lastMaterial = this.materials[this.materials.length - 1];
  28064. this.materials[index] = lastMaterial;
  28065. lastMaterial._indexInSceneMaterialArray = index;
  28066. }
  28067. toRemove._indexInSceneMaterialArray = -1;
  28068. this.materials.pop();
  28069. }
  28070. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  28071. return index;
  28072. };
  28073. /**
  28074. * Removes the given action manager from this scene.
  28075. * @param toRemove The action manager to remove
  28076. * @returns The index of the removed action manager
  28077. */
  28078. Scene.prototype.removeActionManager = function (toRemove) {
  28079. var index = this.actionManagers.indexOf(toRemove);
  28080. if (index !== -1) {
  28081. this.actionManagers.splice(index, 1);
  28082. }
  28083. return index;
  28084. };
  28085. /**
  28086. * Removes the given texture from this scene.
  28087. * @param toRemove The texture to remove
  28088. * @returns The index of the removed texture
  28089. */
  28090. Scene.prototype.removeTexture = function (toRemove) {
  28091. var index = this.textures.indexOf(toRemove);
  28092. if (index !== -1) {
  28093. this.textures.splice(index, 1);
  28094. }
  28095. this.onTextureRemovedObservable.notifyObservers(toRemove);
  28096. return index;
  28097. };
  28098. /**
  28099. * Adds the given light to this scene
  28100. * @param newLight The light to add
  28101. */
  28102. Scene.prototype.addLight = function (newLight) {
  28103. this.lights.push(newLight);
  28104. this.sortLightsByPriority();
  28105. // Add light to all meshes (To support if the light is removed and then readded)
  28106. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  28107. var mesh = _a[_i];
  28108. if (mesh._lightSources.indexOf(newLight) === -1) {
  28109. mesh._lightSources.push(newLight);
  28110. mesh._resyncLightSources();
  28111. }
  28112. }
  28113. this.onNewLightAddedObservable.notifyObservers(newLight);
  28114. };
  28115. /**
  28116. * Sorts the list list based on light priorities
  28117. */
  28118. Scene.prototype.sortLightsByPriority = function () {
  28119. if (this.requireLightSorting) {
  28120. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  28121. }
  28122. };
  28123. /**
  28124. * Adds the given camera to this scene
  28125. * @param newCamera The camera to add
  28126. */
  28127. Scene.prototype.addCamera = function (newCamera) {
  28128. this.cameras.push(newCamera);
  28129. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  28130. };
  28131. /**
  28132. * Adds the given skeleton to this scene
  28133. * @param newSkeleton The skeleton to add
  28134. */
  28135. Scene.prototype.addSkeleton = function (newSkeleton) {
  28136. this.skeletons.push(newSkeleton);
  28137. };
  28138. /**
  28139. * Adds the given particle system to this scene
  28140. * @param newParticleSystem The particle system to add
  28141. */
  28142. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  28143. this.particleSystems.push(newParticleSystem);
  28144. };
  28145. /**
  28146. * Adds the given animation to this scene
  28147. * @param newAnimation The animation to add
  28148. */
  28149. Scene.prototype.addAnimation = function (newAnimation) {
  28150. this.animations.push(newAnimation);
  28151. };
  28152. /**
  28153. * Adds the given animation group to this scene.
  28154. * @param newAnimationGroup The animation group to add
  28155. */
  28156. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  28157. this.animationGroups.push(newAnimationGroup);
  28158. };
  28159. /**
  28160. * Adds the given multi-material to this scene
  28161. * @param newMultiMaterial The multi-material to add
  28162. */
  28163. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  28164. this.multiMaterials.push(newMultiMaterial);
  28165. };
  28166. /**
  28167. * Adds the given material to this scene
  28168. * @param newMaterial The material to add
  28169. */
  28170. Scene.prototype.addMaterial = function (newMaterial) {
  28171. newMaterial._indexInSceneMaterialArray = this.materials.length;
  28172. this.materials.push(newMaterial);
  28173. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  28174. };
  28175. /**
  28176. * Adds the given morph target to this scene
  28177. * @param newMorphTargetManager The morph target to add
  28178. */
  28179. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  28180. this.morphTargetManagers.push(newMorphTargetManager);
  28181. };
  28182. /**
  28183. * Adds the given geometry to this scene
  28184. * @param newGeometry The geometry to add
  28185. */
  28186. Scene.prototype.addGeometry = function (newGeometry) {
  28187. if (this.geometriesById) {
  28188. this.geometriesById[newGeometry.id] = this.geometries.length;
  28189. }
  28190. this.geometries.push(newGeometry);
  28191. };
  28192. /**
  28193. * Adds the given action manager to this scene
  28194. * @param newActionManager The action manager to add
  28195. */
  28196. Scene.prototype.addActionManager = function (newActionManager) {
  28197. this.actionManagers.push(newActionManager);
  28198. };
  28199. /**
  28200. * Adds the given texture to this scene.
  28201. * @param newTexture The texture to add
  28202. */
  28203. Scene.prototype.addTexture = function (newTexture) {
  28204. this.textures.push(newTexture);
  28205. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  28206. };
  28207. /**
  28208. * Switch active camera
  28209. * @param newCamera defines the new active camera
  28210. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  28211. */
  28212. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  28213. if (attachControl === void 0) { attachControl = true; }
  28214. var canvas = this._engine.getRenderingCanvas();
  28215. if (!canvas) {
  28216. return;
  28217. }
  28218. if (this.activeCamera) {
  28219. this.activeCamera.detachControl(canvas);
  28220. }
  28221. this.activeCamera = newCamera;
  28222. if (attachControl) {
  28223. newCamera.attachControl(canvas);
  28224. }
  28225. };
  28226. /**
  28227. * sets the active camera of the scene using its ID
  28228. * @param id defines the camera's ID
  28229. * @return the new active camera or null if none found.
  28230. */
  28231. Scene.prototype.setActiveCameraByID = function (id) {
  28232. var camera = this.getCameraByID(id);
  28233. if (camera) {
  28234. this.activeCamera = camera;
  28235. return camera;
  28236. }
  28237. return null;
  28238. };
  28239. /**
  28240. * sets the active camera of the scene using its name
  28241. * @param name defines the camera's name
  28242. * @returns the new active camera or null if none found.
  28243. */
  28244. Scene.prototype.setActiveCameraByName = function (name) {
  28245. var camera = this.getCameraByName(name);
  28246. if (camera) {
  28247. this.activeCamera = camera;
  28248. return camera;
  28249. }
  28250. return null;
  28251. };
  28252. /**
  28253. * get an animation group using its name
  28254. * @param name defines the material's name
  28255. * @return the animation group or null if none found.
  28256. */
  28257. Scene.prototype.getAnimationGroupByName = function (name) {
  28258. for (var index = 0; index < this.animationGroups.length; index++) {
  28259. if (this.animationGroups[index].name === name) {
  28260. return this.animationGroups[index];
  28261. }
  28262. }
  28263. return null;
  28264. };
  28265. /**
  28266. * get a material using its id
  28267. * @param id defines the material's ID
  28268. * @return the material or null if none found.
  28269. */
  28270. Scene.prototype.getMaterialByID = function (id) {
  28271. for (var index = 0; index < this.materials.length; index++) {
  28272. if (this.materials[index].id === id) {
  28273. return this.materials[index];
  28274. }
  28275. }
  28276. return null;
  28277. };
  28278. /**
  28279. * Gets a material using its name
  28280. * @param name defines the material's name
  28281. * @return the material or null if none found.
  28282. */
  28283. Scene.prototype.getMaterialByName = function (name) {
  28284. for (var index = 0; index < this.materials.length; index++) {
  28285. if (this.materials[index].name === name) {
  28286. return this.materials[index];
  28287. }
  28288. }
  28289. return null;
  28290. };
  28291. /**
  28292. * Gets a camera using its id
  28293. * @param id defines the id to look for
  28294. * @returns the camera or null if not found
  28295. */
  28296. Scene.prototype.getCameraByID = function (id) {
  28297. for (var index = 0; index < this.cameras.length; index++) {
  28298. if (this.cameras[index].id === id) {
  28299. return this.cameras[index];
  28300. }
  28301. }
  28302. return null;
  28303. };
  28304. /**
  28305. * Gets a camera using its unique id
  28306. * @param uniqueId defines the unique id to look for
  28307. * @returns the camera or null if not found
  28308. */
  28309. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  28310. for (var index = 0; index < this.cameras.length; index++) {
  28311. if (this.cameras[index].uniqueId === uniqueId) {
  28312. return this.cameras[index];
  28313. }
  28314. }
  28315. return null;
  28316. };
  28317. /**
  28318. * Gets a camera using its name
  28319. * @param name defines the camera's name
  28320. * @return the camera or null if none found.
  28321. */
  28322. Scene.prototype.getCameraByName = function (name) {
  28323. for (var index = 0; index < this.cameras.length; index++) {
  28324. if (this.cameras[index].name === name) {
  28325. return this.cameras[index];
  28326. }
  28327. }
  28328. return null;
  28329. };
  28330. /**
  28331. * Gets a bone using its id
  28332. * @param id defines the bone's id
  28333. * @return the bone or null if not found
  28334. */
  28335. Scene.prototype.getBoneByID = function (id) {
  28336. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28337. var skeleton = this.skeletons[skeletonIndex];
  28338. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28339. if (skeleton.bones[boneIndex].id === id) {
  28340. return skeleton.bones[boneIndex];
  28341. }
  28342. }
  28343. }
  28344. return null;
  28345. };
  28346. /**
  28347. * Gets a bone using its id
  28348. * @param name defines the bone's name
  28349. * @return the bone or null if not found
  28350. */
  28351. Scene.prototype.getBoneByName = function (name) {
  28352. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28353. var skeleton = this.skeletons[skeletonIndex];
  28354. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28355. if (skeleton.bones[boneIndex].name === name) {
  28356. return skeleton.bones[boneIndex];
  28357. }
  28358. }
  28359. }
  28360. return null;
  28361. };
  28362. /**
  28363. * Gets a light node using its name
  28364. * @param name defines the the light's name
  28365. * @return the light or null if none found.
  28366. */
  28367. Scene.prototype.getLightByName = function (name) {
  28368. for (var index = 0; index < this.lights.length; index++) {
  28369. if (this.lights[index].name === name) {
  28370. return this.lights[index];
  28371. }
  28372. }
  28373. return null;
  28374. };
  28375. /**
  28376. * Gets a light node using its id
  28377. * @param id defines the light's id
  28378. * @return the light or null if none found.
  28379. */
  28380. Scene.prototype.getLightByID = function (id) {
  28381. for (var index = 0; index < this.lights.length; index++) {
  28382. if (this.lights[index].id === id) {
  28383. return this.lights[index];
  28384. }
  28385. }
  28386. return null;
  28387. };
  28388. /**
  28389. * Gets a light node using its scene-generated unique ID
  28390. * @param uniqueId defines the light's unique id
  28391. * @return the light or null if none found.
  28392. */
  28393. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  28394. for (var index = 0; index < this.lights.length; index++) {
  28395. if (this.lights[index].uniqueId === uniqueId) {
  28396. return this.lights[index];
  28397. }
  28398. }
  28399. return null;
  28400. };
  28401. /**
  28402. * Gets a particle system by id
  28403. * @param id defines the particle system id
  28404. * @return the corresponding system or null if none found
  28405. */
  28406. Scene.prototype.getParticleSystemByID = function (id) {
  28407. for (var index = 0; index < this.particleSystems.length; index++) {
  28408. if (this.particleSystems[index].id === id) {
  28409. return this.particleSystems[index];
  28410. }
  28411. }
  28412. return null;
  28413. };
  28414. /**
  28415. * Gets a geometry using its ID
  28416. * @param id defines the geometry's id
  28417. * @return the geometry or null if none found.
  28418. */
  28419. Scene.prototype.getGeometryByID = function (id) {
  28420. if (this.geometriesById) {
  28421. var index_1 = this.geometriesById[id];
  28422. if (index_1 !== undefined) {
  28423. return this.geometries[index_1];
  28424. }
  28425. }
  28426. else {
  28427. for (var index = 0; index < this.geometries.length; index++) {
  28428. if (this.geometries[index].id === id) {
  28429. return this.geometries[index];
  28430. }
  28431. }
  28432. }
  28433. return null;
  28434. };
  28435. /**
  28436. * Add a new geometry to this scene
  28437. * @param geometry defines the geometry to be added to the scene.
  28438. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  28439. * @return a boolean defining if the geometry was added or not
  28440. */
  28441. Scene.prototype.pushGeometry = function (geometry, force) {
  28442. if (!force && this.getGeometryByID(geometry.id)) {
  28443. return false;
  28444. }
  28445. this.addGeometry(geometry);
  28446. //notify the collision coordinator
  28447. if (this.collisionCoordinator) {
  28448. this.collisionCoordinator.onGeometryAdded(geometry);
  28449. }
  28450. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  28451. return true;
  28452. };
  28453. /**
  28454. * Removes an existing geometry
  28455. * @param geometry defines the geometry to be removed from the scene
  28456. * @return a boolean defining if the geometry was removed or not
  28457. */
  28458. Scene.prototype.removeGeometry = function (geometry) {
  28459. var index;
  28460. if (this.geometriesById) {
  28461. index = this.geometriesById[geometry.id];
  28462. if (index === undefined) {
  28463. return false;
  28464. }
  28465. }
  28466. else {
  28467. index = this.geometries.indexOf(geometry);
  28468. if (index < 0) {
  28469. return false;
  28470. }
  28471. }
  28472. if (index !== this.geometries.length - 1) {
  28473. var lastGeometry = this.geometries[this.geometries.length - 1];
  28474. this.geometries[index] = lastGeometry;
  28475. if (this.geometriesById) {
  28476. this.geometriesById[lastGeometry.id] = index;
  28477. this.geometriesById[geometry.id] = undefined;
  28478. }
  28479. }
  28480. this.geometries.pop();
  28481. //notify the collision coordinator
  28482. if (this.collisionCoordinator) {
  28483. this.collisionCoordinator.onGeometryDeleted(geometry);
  28484. }
  28485. this.onGeometryRemovedObservable.notifyObservers(geometry);
  28486. return true;
  28487. };
  28488. /**
  28489. * Gets the list of geometries attached to the scene
  28490. * @returns an array of Geometry
  28491. */
  28492. Scene.prototype.getGeometries = function () {
  28493. return this.geometries;
  28494. };
  28495. /**
  28496. * Gets the first added mesh found of a given ID
  28497. * @param id defines the id to search for
  28498. * @return the mesh found or null if not found at all
  28499. */
  28500. Scene.prototype.getMeshByID = function (id) {
  28501. for (var index = 0; index < this.meshes.length; index++) {
  28502. if (this.meshes[index].id === id) {
  28503. return this.meshes[index];
  28504. }
  28505. }
  28506. return null;
  28507. };
  28508. /**
  28509. * Gets a list of meshes using their id
  28510. * @param id defines the id to search for
  28511. * @returns a list of meshes
  28512. */
  28513. Scene.prototype.getMeshesByID = function (id) {
  28514. return this.meshes.filter(function (m) {
  28515. return m.id === id;
  28516. });
  28517. };
  28518. /**
  28519. * Gets the first added transform node found of a given ID
  28520. * @param id defines the id to search for
  28521. * @return the found transform node or null if not found at all.
  28522. */
  28523. Scene.prototype.getTransformNodeByID = function (id) {
  28524. for (var index = 0; index < this.transformNodes.length; index++) {
  28525. if (this.transformNodes[index].id === id) {
  28526. return this.transformNodes[index];
  28527. }
  28528. }
  28529. return null;
  28530. };
  28531. /**
  28532. * Gets a list of transform nodes using their id
  28533. * @param id defines the id to search for
  28534. * @returns a list of transform nodes
  28535. */
  28536. Scene.prototype.getTransformNodesByID = function (id) {
  28537. return this.transformNodes.filter(function (m) {
  28538. return m.id === id;
  28539. });
  28540. };
  28541. /**
  28542. * Gets a mesh with its auto-generated unique id
  28543. * @param uniqueId defines the unique id to search for
  28544. * @return the found mesh or null if not found at all.
  28545. */
  28546. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  28547. for (var index = 0; index < this.meshes.length; index++) {
  28548. if (this.meshes[index].uniqueId === uniqueId) {
  28549. return this.meshes[index];
  28550. }
  28551. }
  28552. return null;
  28553. };
  28554. /**
  28555. * Gets a the last added mesh using a given id
  28556. * @param id defines the id to search for
  28557. * @return the found mesh or null if not found at all.
  28558. */
  28559. Scene.prototype.getLastMeshByID = function (id) {
  28560. for (var index = this.meshes.length - 1; index >= 0; index--) {
  28561. if (this.meshes[index].id === id) {
  28562. return this.meshes[index];
  28563. }
  28564. }
  28565. return null;
  28566. };
  28567. /**
  28568. * Gets a the last added node (Mesh, Camera, Light) using a given id
  28569. * @param id defines the id to search for
  28570. * @return the found node or null if not found at all
  28571. */
  28572. Scene.prototype.getLastEntryByID = function (id) {
  28573. var index;
  28574. for (index = this.meshes.length - 1; index >= 0; index--) {
  28575. if (this.meshes[index].id === id) {
  28576. return this.meshes[index];
  28577. }
  28578. }
  28579. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  28580. if (this.transformNodes[index].id === id) {
  28581. return this.transformNodes[index];
  28582. }
  28583. }
  28584. for (index = this.cameras.length - 1; index >= 0; index--) {
  28585. if (this.cameras[index].id === id) {
  28586. return this.cameras[index];
  28587. }
  28588. }
  28589. for (index = this.lights.length - 1; index >= 0; index--) {
  28590. if (this.lights[index].id === id) {
  28591. return this.lights[index];
  28592. }
  28593. }
  28594. return null;
  28595. };
  28596. /**
  28597. * Gets a node (Mesh, Camera, Light) using a given id
  28598. * @param id defines the id to search for
  28599. * @return the found node or null if not found at all
  28600. */
  28601. Scene.prototype.getNodeByID = function (id) {
  28602. var mesh = this.getMeshByID(id);
  28603. if (mesh) {
  28604. return mesh;
  28605. }
  28606. var light = this.getLightByID(id);
  28607. if (light) {
  28608. return light;
  28609. }
  28610. var camera = this.getCameraByID(id);
  28611. if (camera) {
  28612. return camera;
  28613. }
  28614. var bone = this.getBoneByID(id);
  28615. return bone;
  28616. };
  28617. /**
  28618. * Gets a node (Mesh, Camera, Light) using a given name
  28619. * @param name defines the name to search for
  28620. * @return the found node or null if not found at all.
  28621. */
  28622. Scene.prototype.getNodeByName = function (name) {
  28623. var mesh = this.getMeshByName(name);
  28624. if (mesh) {
  28625. return mesh;
  28626. }
  28627. var light = this.getLightByName(name);
  28628. if (light) {
  28629. return light;
  28630. }
  28631. var camera = this.getCameraByName(name);
  28632. if (camera) {
  28633. return camera;
  28634. }
  28635. var bone = this.getBoneByName(name);
  28636. return bone;
  28637. };
  28638. /**
  28639. * Gets a mesh using a given name
  28640. * @param name defines the name to search for
  28641. * @return the found mesh or null if not found at all.
  28642. */
  28643. Scene.prototype.getMeshByName = function (name) {
  28644. for (var index = 0; index < this.meshes.length; index++) {
  28645. if (this.meshes[index].name === name) {
  28646. return this.meshes[index];
  28647. }
  28648. }
  28649. return null;
  28650. };
  28651. /**
  28652. * Gets a transform node using a given name
  28653. * @param name defines the name to search for
  28654. * @return the found transform node or null if not found at all.
  28655. */
  28656. Scene.prototype.getTransformNodeByName = function (name) {
  28657. for (var index = 0; index < this.transformNodes.length; index++) {
  28658. if (this.transformNodes[index].name === name) {
  28659. return this.transformNodes[index];
  28660. }
  28661. }
  28662. return null;
  28663. };
  28664. /**
  28665. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  28666. * @param id defines the id to search for
  28667. * @return the found skeleton or null if not found at all.
  28668. */
  28669. Scene.prototype.getLastSkeletonByID = function (id) {
  28670. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  28671. if (this.skeletons[index].id === id) {
  28672. return this.skeletons[index];
  28673. }
  28674. }
  28675. return null;
  28676. };
  28677. /**
  28678. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  28679. * @param id defines the id to search for
  28680. * @return the found skeleton or null if not found at all.
  28681. */
  28682. Scene.prototype.getSkeletonById = function (id) {
  28683. for (var index = 0; index < this.skeletons.length; index++) {
  28684. if (this.skeletons[index].id === id) {
  28685. return this.skeletons[index];
  28686. }
  28687. }
  28688. return null;
  28689. };
  28690. /**
  28691. * Gets a skeleton using a given name
  28692. * @param name defines the name to search for
  28693. * @return the found skeleton or null if not found at all.
  28694. */
  28695. Scene.prototype.getSkeletonByName = function (name) {
  28696. for (var index = 0; index < this.skeletons.length; index++) {
  28697. if (this.skeletons[index].name === name) {
  28698. return this.skeletons[index];
  28699. }
  28700. }
  28701. return null;
  28702. };
  28703. /**
  28704. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  28705. * @param id defines the id to search for
  28706. * @return the found morph target manager or null if not found at all.
  28707. */
  28708. Scene.prototype.getMorphTargetManagerById = function (id) {
  28709. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  28710. if (this.morphTargetManagers[index].uniqueId === id) {
  28711. return this.morphTargetManagers[index];
  28712. }
  28713. }
  28714. return null;
  28715. };
  28716. /**
  28717. * Gets a boolean indicating if the given mesh is active
  28718. * @param mesh defines the mesh to look for
  28719. * @returns true if the mesh is in the active list
  28720. */
  28721. Scene.prototype.isActiveMesh = function (mesh) {
  28722. return (this._activeMeshes.indexOf(mesh) !== -1);
  28723. };
  28724. Object.defineProperty(Scene.prototype, "uid", {
  28725. /**
  28726. * Return a unique id as a string which can serve as an identifier for the scene
  28727. */
  28728. get: function () {
  28729. if (!this._uid) {
  28730. this._uid = BABYLON.Tools.RandomId();
  28731. }
  28732. return this._uid;
  28733. },
  28734. enumerable: true,
  28735. configurable: true
  28736. });
  28737. /**
  28738. * Add an externaly attached data from its key.
  28739. * This method call will fail and return false, if such key already exists.
  28740. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  28741. * @param key the unique key that identifies the data
  28742. * @param data the data object to associate to the key for this Engine instance
  28743. * @return true if no such key were already present and the data was added successfully, false otherwise
  28744. */
  28745. Scene.prototype.addExternalData = function (key, data) {
  28746. if (!this._externalData) {
  28747. this._externalData = new BABYLON.StringDictionary();
  28748. }
  28749. return this._externalData.add(key, data);
  28750. };
  28751. /**
  28752. * Get an externaly attached data from its key
  28753. * @param key the unique key that identifies the data
  28754. * @return the associated data, if present (can be null), or undefined if not present
  28755. */
  28756. Scene.prototype.getExternalData = function (key) {
  28757. if (!this._externalData) {
  28758. return null;
  28759. }
  28760. return this._externalData.get(key);
  28761. };
  28762. /**
  28763. * Get an externaly attached data from its key, create it using a factory if it's not already present
  28764. * @param key the unique key that identifies the data
  28765. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  28766. * @return the associated data, can be null if the factory returned null.
  28767. */
  28768. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  28769. if (!this._externalData) {
  28770. this._externalData = new BABYLON.StringDictionary();
  28771. }
  28772. return this._externalData.getOrAddWithFactory(key, factory);
  28773. };
  28774. /**
  28775. * Remove an externaly attached data from the Engine instance
  28776. * @param key the unique key that identifies the data
  28777. * @return true if the data was successfully removed, false if it doesn't exist
  28778. */
  28779. Scene.prototype.removeExternalData = function (key) {
  28780. return this._externalData.remove(key);
  28781. };
  28782. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  28783. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  28784. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  28785. var step = _a[_i];
  28786. step.action(mesh, subMesh);
  28787. }
  28788. var material = subMesh.getMaterial();
  28789. if (material !== null && material !== undefined) {
  28790. // Render targets
  28791. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  28792. if (this._processedMaterials.indexOf(material) === -1) {
  28793. this._processedMaterials.push(material);
  28794. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  28795. }
  28796. }
  28797. // Dispatch
  28798. this._activeIndices.addCount(subMesh.indexCount, false);
  28799. this._renderingManager.dispatch(subMesh, mesh, material);
  28800. }
  28801. }
  28802. };
  28803. /**
  28804. * Clear the processed materials smart array preventing retention point in material dispose.
  28805. */
  28806. Scene.prototype.freeProcessedMaterials = function () {
  28807. this._processedMaterials.dispose();
  28808. };
  28809. Object.defineProperty(Scene.prototype, "blockfreeActiveMeshesAndRenderingGroups", {
  28810. /** Gets or sets a boolean blocking all the calls to freeActiveMeshes and freeRenderingGroups
  28811. * It can be used in order to prevent going through methods freeRenderingGroups and freeActiveMeshes several times to improve performance
  28812. * when disposing several meshes in a row or a hierarchy of meshes.
  28813. * When used, it is the responsability of the user to blockfreeActiveMeshesAndRenderingGroups back to false.
  28814. */
  28815. get: function () {
  28816. return this._preventFreeActiveMeshesAndRenderingGroups;
  28817. },
  28818. set: function (value) {
  28819. if (this._preventFreeActiveMeshesAndRenderingGroups === value) {
  28820. return;
  28821. }
  28822. if (value) {
  28823. this.freeActiveMeshes();
  28824. this.freeRenderingGroups();
  28825. }
  28826. this._preventFreeActiveMeshesAndRenderingGroups = value;
  28827. },
  28828. enumerable: true,
  28829. configurable: true
  28830. });
  28831. /**
  28832. * Clear the active meshes smart array preventing retention point in mesh dispose.
  28833. */
  28834. Scene.prototype.freeActiveMeshes = function () {
  28835. if (this.blockfreeActiveMeshesAndRenderingGroups) {
  28836. return;
  28837. }
  28838. this._activeMeshes.dispose();
  28839. if (this.activeCamera && this.activeCamera._activeMeshes) {
  28840. this.activeCamera._activeMeshes.dispose();
  28841. }
  28842. if (this.activeCameras) {
  28843. for (var i = 0; i < this.activeCameras.length; i++) {
  28844. var activeCamera = this.activeCameras[i];
  28845. if (activeCamera && activeCamera._activeMeshes) {
  28846. activeCamera._activeMeshes.dispose();
  28847. }
  28848. }
  28849. }
  28850. };
  28851. /**
  28852. * Clear the info related to rendering groups preventing retention points during dispose.
  28853. */
  28854. Scene.prototype.freeRenderingGroups = function () {
  28855. if (this.blockfreeActiveMeshesAndRenderingGroups) {
  28856. return;
  28857. }
  28858. if (this._renderingManager) {
  28859. this._renderingManager.freeRenderingGroups();
  28860. }
  28861. if (this.textures) {
  28862. for (var i = 0; i < this.textures.length; i++) {
  28863. var texture = this.textures[i];
  28864. if (texture && texture.renderList) {
  28865. texture.freeRenderingGroups();
  28866. }
  28867. }
  28868. }
  28869. };
  28870. /** @hidden */
  28871. Scene.prototype._isInIntermediateRendering = function () {
  28872. return this._intermediateRendering;
  28873. };
  28874. /**
  28875. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  28876. * @returns the current scene
  28877. */
  28878. Scene.prototype.freezeActiveMeshes = function () {
  28879. if (!this.activeCamera) {
  28880. return this;
  28881. }
  28882. if (!this._frustumPlanes) {
  28883. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28884. }
  28885. this._evaluateActiveMeshes();
  28886. this._activeMeshesFrozen = true;
  28887. return this;
  28888. };
  28889. /**
  28890. * Use this function to restart evaluating active meshes on every frame
  28891. * @returns the current scene
  28892. */
  28893. Scene.prototype.unfreezeActiveMeshes = function () {
  28894. this._activeMeshesFrozen = false;
  28895. return this;
  28896. };
  28897. Scene.prototype._evaluateActiveMeshes = function () {
  28898. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  28899. return;
  28900. }
  28901. if (!this.activeCamera) {
  28902. return;
  28903. }
  28904. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  28905. this.activeCamera._activeMeshes.reset();
  28906. this._activeMeshes.reset();
  28907. this._renderingManager.reset();
  28908. this._processedMaterials.reset();
  28909. this._activeParticleSystems.reset();
  28910. this._activeSkeletons.reset();
  28911. this._softwareSkinnedMeshes.reset();
  28912. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  28913. var step = _a[_i];
  28914. step.action();
  28915. }
  28916. // Determine mesh candidates
  28917. var meshes = this.getActiveMeshCandidates();
  28918. // Check each mesh
  28919. var len = meshes.length;
  28920. for (var i = 0; i < len; i++) {
  28921. var mesh = meshes.data[i];
  28922. if (mesh.isBlocked) {
  28923. continue;
  28924. }
  28925. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  28926. if (!mesh.isReady() || !mesh.isEnabled()) {
  28927. continue;
  28928. }
  28929. mesh.computeWorldMatrix();
  28930. // Intersections
  28931. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  28932. this._meshesForIntersections.pushNoDuplicate(mesh);
  28933. }
  28934. // Switch to current LOD
  28935. var meshLOD = mesh.getLOD(this.activeCamera);
  28936. if (meshLOD === undefined || meshLOD === null) {
  28937. continue;
  28938. }
  28939. mesh._preActivate();
  28940. if (mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && (mesh.alwaysSelectAsActiveMesh || mesh.isInFrustum(this._frustumPlanes))) {
  28941. this._activeMeshes.push(mesh);
  28942. this.activeCamera._activeMeshes.push(mesh);
  28943. mesh._activate(this._renderId);
  28944. if (meshLOD !== mesh) {
  28945. meshLOD._activate(this._renderId);
  28946. }
  28947. this._activeMesh(mesh, meshLOD);
  28948. }
  28949. }
  28950. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  28951. // Particle systems
  28952. if (this.particlesEnabled) {
  28953. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  28954. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  28955. var particleSystem = this.particleSystems[particleIndex];
  28956. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  28957. continue;
  28958. }
  28959. var emitter = particleSystem.emitter;
  28960. if (!emitter.position || emitter.isEnabled()) {
  28961. this._activeParticleSystems.push(particleSystem);
  28962. particleSystem.animate();
  28963. this._renderingManager.dispatchParticles(particleSystem);
  28964. }
  28965. }
  28966. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  28967. }
  28968. };
  28969. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  28970. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  28971. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  28972. mesh.skeleton.prepare();
  28973. }
  28974. if (!mesh.computeBonesUsingShaders) {
  28975. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  28976. }
  28977. }
  28978. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  28979. var step = _a[_i];
  28980. step.action(sourceMesh, mesh);
  28981. }
  28982. if (mesh !== undefined && mesh !== null
  28983. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  28984. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  28985. var len = subMeshes.length;
  28986. for (var i = 0; i < len; i++) {
  28987. var subMesh = subMeshes.data[i];
  28988. this._evaluateSubMesh(subMesh, mesh);
  28989. }
  28990. }
  28991. };
  28992. /**
  28993. * Update the transform matrix to update from the current active camera
  28994. * @param force defines a boolean used to force the update even if cache is up to date
  28995. */
  28996. Scene.prototype.updateTransformMatrix = function (force) {
  28997. if (!this.activeCamera) {
  28998. return;
  28999. }
  29000. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  29001. };
  29002. /**
  29003. * 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)
  29004. * @param alternateCamera defines the camera to use
  29005. */
  29006. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  29007. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  29008. };
  29009. Scene.prototype._renderForCamera = function (camera, rigParent) {
  29010. if (camera && camera._skipRendering) {
  29011. return;
  29012. }
  29013. var engine = this._engine;
  29014. this.activeCamera = camera;
  29015. if (!this.activeCamera) {
  29016. throw new Error("Active camera not set");
  29017. }
  29018. // Viewport
  29019. engine.setViewport(this.activeCamera.viewport);
  29020. // Camera
  29021. this.resetCachedMaterial();
  29022. this._renderId++;
  29023. this.updateTransformMatrix();
  29024. if (camera._alternateCamera) {
  29025. this.updateAlternateTransformMatrix(camera._alternateCamera);
  29026. this._alternateRendering = true;
  29027. }
  29028. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  29029. // Meshes
  29030. this._evaluateActiveMeshes();
  29031. // Software skinning
  29032. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  29033. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  29034. mesh.applySkeleton(mesh.skeleton);
  29035. }
  29036. // Render targets
  29037. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  29038. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  29039. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  29040. }
  29041. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  29042. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  29043. }
  29044. // Collects render targets from external components.
  29045. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  29046. var step = _a[_i];
  29047. step.action(this._renderTargets);
  29048. }
  29049. if (this.renderTargetsEnabled) {
  29050. this._intermediateRendering = true;
  29051. if (this._renderTargets.length > 0) {
  29052. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  29053. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  29054. var renderTarget = this._renderTargets.data[renderIndex];
  29055. if (renderTarget._shouldRender()) {
  29056. this._renderId++;
  29057. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  29058. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  29059. }
  29060. }
  29061. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  29062. this._renderId++;
  29063. }
  29064. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  29065. var step = _c[_b];
  29066. step.action(this.activeCamera);
  29067. }
  29068. this._intermediateRendering = false;
  29069. if (this.activeCamera.outputRenderTarget) {
  29070. var internalTexture = this.activeCamera.outputRenderTarget.getInternalTexture();
  29071. if (internalTexture) {
  29072. engine.bindFramebuffer(internalTexture);
  29073. }
  29074. else {
  29075. BABYLON.Tools.Error("Camera contains invalid customDefaultRenderTarget");
  29076. }
  29077. }
  29078. else {
  29079. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  29080. }
  29081. }
  29082. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  29083. // Prepare Frame
  29084. if (this.postProcessManager) {
  29085. this.postProcessManager._prepareFrame();
  29086. }
  29087. // Before Camera Draw
  29088. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  29089. var step = _e[_d];
  29090. step.action(this.activeCamera);
  29091. }
  29092. // Render
  29093. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  29094. this._renderingManager.render(null, null, true, true);
  29095. this.onAfterDrawPhaseObservable.notifyObservers(this);
  29096. // After Camera Draw
  29097. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  29098. var step = _g[_f];
  29099. step.action(this.activeCamera);
  29100. }
  29101. // Finalize frame
  29102. if (this.postProcessManager) {
  29103. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  29104. }
  29105. // Reset some special arrays
  29106. this._renderTargets.reset();
  29107. this._alternateRendering = false;
  29108. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  29109. };
  29110. Scene.prototype._processSubCameras = function (camera) {
  29111. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  29112. this._renderForCamera(camera);
  29113. return;
  29114. }
  29115. // rig cameras
  29116. for (var index = 0; index < camera._rigCameras.length; index++) {
  29117. this._renderForCamera(camera._rigCameras[index], camera);
  29118. }
  29119. this.activeCamera = camera;
  29120. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  29121. };
  29122. Scene.prototype._checkIntersections = function () {
  29123. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  29124. var sourceMesh = this._meshesForIntersections.data[index];
  29125. if (!sourceMesh.actionManager) {
  29126. continue;
  29127. }
  29128. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  29129. var action = sourceMesh.actionManager.actions[actionIndex];
  29130. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  29131. var parameters = action.getTriggerParameter();
  29132. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  29133. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  29134. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  29135. if (areIntersecting && currentIntersectionInProgress === -1) {
  29136. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  29137. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  29138. sourceMesh._intersectionsInProgress.push(otherMesh);
  29139. }
  29140. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  29141. sourceMesh._intersectionsInProgress.push(otherMesh);
  29142. }
  29143. }
  29144. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  29145. //They intersected, and now they don't.
  29146. //is this trigger an exit trigger? execute an event.
  29147. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  29148. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  29149. }
  29150. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  29151. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  29152. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  29153. return otherMesh === parameterMesh;
  29154. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  29155. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  29156. }
  29157. }
  29158. }
  29159. }
  29160. }
  29161. };
  29162. /** @hidden */
  29163. Scene.prototype._advancePhysicsEngineStep = function (step) {
  29164. // Do nothing. Code will be replaced if physics engine component is referenced
  29165. };
  29166. /**
  29167. * Render the scene
  29168. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  29169. */
  29170. Scene.prototype.render = function (updateCameras) {
  29171. if (updateCameras === void 0) { updateCameras = true; }
  29172. if (this.isDisposed) {
  29173. return;
  29174. }
  29175. this._frameId++;
  29176. // Register components that have been associated lately to the scene.
  29177. this._registerTransientComponents();
  29178. this._activeParticles.fetchNewFrame();
  29179. this._totalVertices.fetchNewFrame();
  29180. this._activeIndices.fetchNewFrame();
  29181. this._activeBones.fetchNewFrame();
  29182. this._meshesForIntersections.reset();
  29183. this.resetCachedMaterial();
  29184. this.onBeforeAnimationsObservable.notifyObservers(this);
  29185. // Actions
  29186. if (this.actionManager) {
  29187. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  29188. }
  29189. if (this._engine.isDeterministicLockStep()) {
  29190. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  29191. var defaultFPS = (60.0 / 1000.0);
  29192. var defaultFrameTime = this.getDeterministicFrameTime();
  29193. var stepsTaken = 0;
  29194. var maxSubSteps = this._engine.getLockstepMaxSteps();
  29195. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  29196. internalSteps = Math.min(internalSteps, maxSubSteps);
  29197. do {
  29198. this.onBeforeStepObservable.notifyObservers(this);
  29199. // Animations
  29200. this._animationRatio = defaultFrameTime * defaultFPS;
  29201. this._animate();
  29202. this.onAfterAnimationsObservable.notifyObservers(this);
  29203. // Physics
  29204. this._advancePhysicsEngineStep(defaultFrameTime);
  29205. this.onAfterStepObservable.notifyObservers(this);
  29206. this._currentStepId++;
  29207. stepsTaken++;
  29208. deltaTime -= defaultFrameTime;
  29209. } while (deltaTime > 0 && stepsTaken < internalSteps);
  29210. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  29211. }
  29212. else {
  29213. // Animations
  29214. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  29215. this._animationRatio = deltaTime * (60.0 / 1000.0);
  29216. this._animate();
  29217. this.onAfterAnimationsObservable.notifyObservers(this);
  29218. // Physics
  29219. this._advancePhysicsEngineStep(deltaTime);
  29220. }
  29221. // Before camera update steps
  29222. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  29223. var step = _a[_i];
  29224. step.action();
  29225. }
  29226. // Update Cameras
  29227. if (updateCameras) {
  29228. if (this.activeCameras.length > 0) {
  29229. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  29230. var camera = this.activeCameras[cameraIndex];
  29231. camera.update();
  29232. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  29233. // rig cameras
  29234. for (var index = 0; index < camera._rigCameras.length; index++) {
  29235. camera._rigCameras[index].update();
  29236. }
  29237. }
  29238. }
  29239. }
  29240. else if (this.activeCamera) {
  29241. this.activeCamera.update();
  29242. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  29243. // rig cameras
  29244. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  29245. this.activeCamera._rigCameras[index].update();
  29246. }
  29247. }
  29248. }
  29249. }
  29250. // Before render
  29251. this.onBeforeRenderObservable.notifyObservers(this);
  29252. // Customs render targets
  29253. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  29254. var engine = this.getEngine();
  29255. var currentActiveCamera = this.activeCamera;
  29256. if (this.renderTargetsEnabled) {
  29257. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  29258. this._intermediateRendering = true;
  29259. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  29260. var renderTarget = this.customRenderTargets[customIndex];
  29261. if (renderTarget._shouldRender()) {
  29262. this._renderId++;
  29263. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  29264. if (!this.activeCamera) {
  29265. throw new Error("Active camera not set");
  29266. }
  29267. // Viewport
  29268. engine.setViewport(this.activeCamera.viewport);
  29269. // Camera
  29270. this.updateTransformMatrix();
  29271. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  29272. }
  29273. }
  29274. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  29275. this._intermediateRendering = false;
  29276. this._renderId++;
  29277. }
  29278. // Restore back buffer
  29279. if (this.customRenderTargets.length > 0) {
  29280. engine.restoreDefaultFramebuffer();
  29281. }
  29282. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  29283. this.activeCamera = currentActiveCamera;
  29284. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  29285. var step = _c[_b];
  29286. step.action();
  29287. }
  29288. // Clear
  29289. if (this.autoClearDepthAndStencil || this.autoClear) {
  29290. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  29291. }
  29292. // Collects render targets from external components.
  29293. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  29294. var step = _e[_d];
  29295. step.action(this._renderTargets);
  29296. }
  29297. // Multi-cameras?
  29298. if (this.activeCameras.length > 0) {
  29299. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  29300. if (cameraIndex > 0) {
  29301. this._engine.clear(null, false, true, true);
  29302. }
  29303. this._processSubCameras(this.activeCameras[cameraIndex]);
  29304. }
  29305. }
  29306. else {
  29307. if (!this.activeCamera) {
  29308. throw new Error("No camera defined");
  29309. }
  29310. this._processSubCameras(this.activeCamera);
  29311. }
  29312. // Intersection checks
  29313. this._checkIntersections();
  29314. // Executes the after render stage actions.
  29315. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  29316. var step = _g[_f];
  29317. step.action();
  29318. }
  29319. // After render
  29320. if (this.afterRender) {
  29321. this.afterRender();
  29322. }
  29323. this.onAfterRenderObservable.notifyObservers(this);
  29324. // Cleaning
  29325. if (this._toBeDisposed.length) {
  29326. for (var index = 0; index < this._toBeDisposed.length; index++) {
  29327. var data = this._toBeDisposed[index];
  29328. if (data) {
  29329. data.dispose();
  29330. }
  29331. }
  29332. this._toBeDisposed = [];
  29333. }
  29334. if (this.dumpNextRenderTargets) {
  29335. this.dumpNextRenderTargets = false;
  29336. }
  29337. this._activeBones.addCount(0, true);
  29338. this._activeIndices.addCount(0, true);
  29339. this._activeParticles.addCount(0, true);
  29340. };
  29341. /**
  29342. * Freeze all materials
  29343. * A frozen material will not be updatable but should be faster to render
  29344. */
  29345. Scene.prototype.freezeMaterials = function () {
  29346. for (var i = 0; i < this.materials.length; i++) {
  29347. this.materials[i].freeze();
  29348. }
  29349. };
  29350. /**
  29351. * Unfreeze all materials
  29352. * A frozen material will not be updatable but should be faster to render
  29353. */
  29354. Scene.prototype.unfreezeMaterials = function () {
  29355. for (var i = 0; i < this.materials.length; i++) {
  29356. this.materials[i].unfreeze();
  29357. }
  29358. };
  29359. /**
  29360. * Releases all held ressources
  29361. */
  29362. Scene.prototype.dispose = function () {
  29363. this.beforeRender = null;
  29364. this.afterRender = null;
  29365. this.skeletons = [];
  29366. this.morphTargetManagers = [];
  29367. this._transientComponents = [];
  29368. this._isReadyForMeshStage.clear();
  29369. this._beforeEvaluateActiveMeshStage.clear();
  29370. this._evaluateSubMeshStage.clear();
  29371. this._activeMeshStage.clear();
  29372. this._cameraDrawRenderTargetStage.clear();
  29373. this._beforeCameraDrawStage.clear();
  29374. this._beforeRenderingGroupDrawStage.clear();
  29375. this._beforeRenderingMeshStage.clear();
  29376. this._afterRenderingMeshStage.clear();
  29377. this._afterRenderingGroupDrawStage.clear();
  29378. this._afterCameraDrawStage.clear();
  29379. this._afterRenderStage.clear();
  29380. this._beforeCameraUpdateStage.clear();
  29381. this._beforeClearStage.clear();
  29382. this._gatherRenderTargetsStage.clear();
  29383. this._gatherActiveCameraRenderTargetsStage.clear();
  29384. this._pointerMoveStage.clear();
  29385. this._pointerDownStage.clear();
  29386. this._pointerUpStage.clear();
  29387. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  29388. var component = _a[_i];
  29389. component.dispose();
  29390. }
  29391. this.importedMeshesFiles = new Array();
  29392. this.stopAllAnimations();
  29393. this.resetCachedMaterial();
  29394. // Smart arrays
  29395. if (this.activeCamera) {
  29396. this.activeCamera._activeMeshes.dispose();
  29397. this.activeCamera = null;
  29398. }
  29399. this._activeMeshes.dispose();
  29400. this._renderingManager.dispose();
  29401. this._processedMaterials.dispose();
  29402. this._activeParticleSystems.dispose();
  29403. this._activeSkeletons.dispose();
  29404. this._softwareSkinnedMeshes.dispose();
  29405. this._renderTargets.dispose();
  29406. this._registeredForLateAnimationBindings.dispose();
  29407. this._meshesForIntersections.dispose();
  29408. this._toBeDisposed = [];
  29409. // Abort active requests
  29410. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  29411. var request = _c[_b];
  29412. request.abort();
  29413. }
  29414. // Events
  29415. this.onDisposeObservable.notifyObservers(this);
  29416. this.onDisposeObservable.clear();
  29417. this.onBeforeRenderObservable.clear();
  29418. this.onAfterRenderObservable.clear();
  29419. this.onBeforeRenderTargetsRenderObservable.clear();
  29420. this.onAfterRenderTargetsRenderObservable.clear();
  29421. this.onAfterStepObservable.clear();
  29422. this.onBeforeStepObservable.clear();
  29423. this.onBeforeActiveMeshesEvaluationObservable.clear();
  29424. this.onAfterActiveMeshesEvaluationObservable.clear();
  29425. this.onBeforeParticlesRenderingObservable.clear();
  29426. this.onAfterParticlesRenderingObservable.clear();
  29427. this.onBeforeDrawPhaseObservable.clear();
  29428. this.onAfterDrawPhaseObservable.clear();
  29429. this.onBeforeAnimationsObservable.clear();
  29430. this.onAfterAnimationsObservable.clear();
  29431. this.onDataLoadedObservable.clear();
  29432. this.onBeforeRenderingGroupObservable.clear();
  29433. this.onAfterRenderingGroupObservable.clear();
  29434. this.onMeshImportedObservable.clear();
  29435. this.onBeforeCameraRenderObservable.clear();
  29436. this.onAfterCameraRenderObservable.clear();
  29437. this.onReadyObservable.clear();
  29438. this.onNewCameraAddedObservable.clear();
  29439. this.onCameraRemovedObservable.clear();
  29440. this.onNewLightAddedObservable.clear();
  29441. this.onLightRemovedObservable.clear();
  29442. this.onNewGeometryAddedObservable.clear();
  29443. this.onGeometryRemovedObservable.clear();
  29444. this.onNewTransformNodeAddedObservable.clear();
  29445. this.onTransformNodeRemovedObservable.clear();
  29446. this.onNewMeshAddedObservable.clear();
  29447. this.onMeshRemovedObservable.clear();
  29448. this.onNewMaterialAddedObservable.clear();
  29449. this.onMaterialRemovedObservable.clear();
  29450. this.onNewTextureAddedObservable.clear();
  29451. this.onTextureRemovedObservable.clear();
  29452. this.onPrePointerObservable.clear();
  29453. this.onPointerObservable.clear();
  29454. this.onPreKeyboardObservable.clear();
  29455. this.onKeyboardObservable.clear();
  29456. this.onActiveCameraChanged.clear();
  29457. this.detachControl();
  29458. // Detach cameras
  29459. var canvas = this._engine.getRenderingCanvas();
  29460. if (canvas) {
  29461. var index;
  29462. for (index = 0; index < this.cameras.length; index++) {
  29463. this.cameras[index].detachControl(canvas);
  29464. }
  29465. }
  29466. // Release animation groups
  29467. while (this.animationGroups.length) {
  29468. this.animationGroups[0].dispose();
  29469. }
  29470. // Release lights
  29471. while (this.lights.length) {
  29472. this.lights[0].dispose();
  29473. }
  29474. // Release meshes
  29475. while (this.meshes.length) {
  29476. this.meshes[0].dispose(true);
  29477. }
  29478. while (this.transformNodes.length) {
  29479. this.removeTransformNode(this.transformNodes[0]);
  29480. }
  29481. // Release cameras
  29482. while (this.cameras.length) {
  29483. this.cameras[0].dispose();
  29484. }
  29485. // Release materials
  29486. if (this.defaultMaterial) {
  29487. this.defaultMaterial.dispose();
  29488. }
  29489. while (this.multiMaterials.length) {
  29490. this.multiMaterials[0].dispose();
  29491. }
  29492. while (this.materials.length) {
  29493. this.materials[0].dispose();
  29494. }
  29495. // Release particles
  29496. while (this.particleSystems.length) {
  29497. this.particleSystems[0].dispose();
  29498. }
  29499. // Release postProcesses
  29500. while (this.postProcesses.length) {
  29501. this.postProcesses[0].dispose();
  29502. }
  29503. // Release textures
  29504. while (this.textures.length) {
  29505. this.textures[0].dispose();
  29506. }
  29507. // Release UBO
  29508. this._sceneUbo.dispose();
  29509. if (this._alternateSceneUbo) {
  29510. this._alternateSceneUbo.dispose();
  29511. }
  29512. // Post-processes
  29513. this.postProcessManager.dispose();
  29514. // Remove from engine
  29515. index = this._engine.scenes.indexOf(this);
  29516. if (index > -1) {
  29517. this._engine.scenes.splice(index, 1);
  29518. }
  29519. this._engine.wipeCaches(true);
  29520. this._isDisposed = true;
  29521. };
  29522. Object.defineProperty(Scene.prototype, "isDisposed", {
  29523. /**
  29524. * Gets if the scene is already disposed
  29525. */
  29526. get: function () {
  29527. return this._isDisposed;
  29528. },
  29529. enumerable: true,
  29530. configurable: true
  29531. });
  29532. /**
  29533. * Call this function to reduce memory footprint of the scene.
  29534. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  29535. */
  29536. Scene.prototype.clearCachedVertexData = function () {
  29537. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29538. var mesh = this.meshes[meshIndex];
  29539. var geometry = mesh.geometry;
  29540. if (geometry) {
  29541. geometry._indices = [];
  29542. for (var vbName in geometry._vertexBuffers) {
  29543. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  29544. continue;
  29545. }
  29546. geometry._vertexBuffers[vbName]._buffer._data = null;
  29547. }
  29548. }
  29549. }
  29550. };
  29551. /**
  29552. * This function will remove the local cached buffer data from texture.
  29553. * It will save memory but will prevent the texture from being rebuilt
  29554. */
  29555. Scene.prototype.cleanCachedTextureBuffer = function () {
  29556. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29557. var baseTexture = _a[_i];
  29558. var buffer = baseTexture._buffer;
  29559. if (buffer) {
  29560. baseTexture._buffer = null;
  29561. }
  29562. }
  29563. };
  29564. /**
  29565. * Get the world extend vectors with an optional filter
  29566. *
  29567. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  29568. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  29569. */
  29570. Scene.prototype.getWorldExtends = function (filterPredicate) {
  29571. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29572. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  29573. filterPredicate = filterPredicate || (function () { return true; });
  29574. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  29575. mesh.computeWorldMatrix(true);
  29576. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  29577. return;
  29578. }
  29579. var boundingInfo = mesh.getBoundingInfo();
  29580. var minBox = boundingInfo.boundingBox.minimumWorld;
  29581. var maxBox = boundingInfo.boundingBox.maximumWorld;
  29582. BABYLON.Tools.CheckExtends(minBox, min, max);
  29583. BABYLON.Tools.CheckExtends(maxBox, min, max);
  29584. });
  29585. return {
  29586. min: min,
  29587. max: max
  29588. };
  29589. };
  29590. // Picking
  29591. /**
  29592. * Creates a ray that can be used to pick in the scene
  29593. * @param x defines the x coordinate of the origin (on-screen)
  29594. * @param y defines the y coordinate of the origin (on-screen)
  29595. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29596. * @param camera defines the camera to use for the picking
  29597. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29598. * @returns a Ray
  29599. */
  29600. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  29601. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29602. var result = BABYLON.Ray.Zero();
  29603. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  29604. return result;
  29605. };
  29606. /**
  29607. * Creates a ray that can be used to pick in the scene
  29608. * @param x defines the x coordinate of the origin (on-screen)
  29609. * @param y defines the y coordinate of the origin (on-screen)
  29610. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29611. * @param result defines the ray where to store the picking ray
  29612. * @param camera defines the camera to use for the picking
  29613. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29614. * @returns the current scene
  29615. */
  29616. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  29617. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29618. var engine = this._engine;
  29619. if (!camera) {
  29620. if (!this.activeCamera) {
  29621. throw new Error("Active camera not set");
  29622. }
  29623. camera = this.activeCamera;
  29624. }
  29625. var cameraViewport = camera.viewport;
  29626. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29627. // Moving coordinates to local viewport world
  29628. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29629. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29630. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.IdentityReadOnly, cameraViewSpace ? BABYLON.Matrix.IdentityReadOnly : camera.getViewMatrix(), camera.getProjectionMatrix());
  29631. return this;
  29632. };
  29633. /**
  29634. * Creates a ray that can be used to pick in the scene
  29635. * @param x defines the x coordinate of the origin (on-screen)
  29636. * @param y defines the y coordinate of the origin (on-screen)
  29637. * @param camera defines the camera to use for the picking
  29638. * @returns a Ray
  29639. */
  29640. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  29641. var result = BABYLON.Ray.Zero();
  29642. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  29643. return result;
  29644. };
  29645. /**
  29646. * Creates a ray that can be used to pick in the scene
  29647. * @param x defines the x coordinate of the origin (on-screen)
  29648. * @param y defines the y coordinate of the origin (on-screen)
  29649. * @param result defines the ray where to store the picking ray
  29650. * @param camera defines the camera to use for the picking
  29651. * @returns the current scene
  29652. */
  29653. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  29654. if (!BABYLON.PickingInfo) {
  29655. return this;
  29656. }
  29657. var engine = this._engine;
  29658. if (!camera) {
  29659. if (!this.activeCamera) {
  29660. throw new Error("Active camera not set");
  29661. }
  29662. camera = this.activeCamera;
  29663. }
  29664. var cameraViewport = camera.viewport;
  29665. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29666. var identity = BABYLON.Matrix.Identity();
  29667. // Moving coordinates to local viewport world
  29668. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29669. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29670. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  29671. return this;
  29672. };
  29673. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  29674. if (!BABYLON.PickingInfo) {
  29675. return null;
  29676. }
  29677. var pickingInfo = null;
  29678. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29679. var mesh = this.meshes[meshIndex];
  29680. if (predicate) {
  29681. if (!predicate(mesh)) {
  29682. continue;
  29683. }
  29684. }
  29685. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29686. continue;
  29687. }
  29688. var world = mesh.getWorldMatrix();
  29689. var ray = rayFunction(world);
  29690. var result = mesh.intersects(ray, fastCheck);
  29691. if (!result || !result.hit) {
  29692. continue;
  29693. }
  29694. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
  29695. continue;
  29696. }
  29697. pickingInfo = result;
  29698. if (fastCheck) {
  29699. break;
  29700. }
  29701. }
  29702. return pickingInfo || new BABYLON.PickingInfo();
  29703. };
  29704. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  29705. if (!BABYLON.PickingInfo) {
  29706. return null;
  29707. }
  29708. var pickingInfos = new Array();
  29709. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29710. var mesh = this.meshes[meshIndex];
  29711. if (predicate) {
  29712. if (!predicate(mesh)) {
  29713. continue;
  29714. }
  29715. }
  29716. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29717. continue;
  29718. }
  29719. var world = mesh.getWorldMatrix();
  29720. var ray = rayFunction(world);
  29721. var result = mesh.intersects(ray, false);
  29722. if (!result || !result.hit) {
  29723. continue;
  29724. }
  29725. pickingInfos.push(result);
  29726. }
  29727. return pickingInfos;
  29728. };
  29729. /** Launch a ray to try to pick a mesh in the scene
  29730. * @param x position on screen
  29731. * @param y position on screen
  29732. * @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
  29733. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  29734. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29735. * @returns a PickingInfo
  29736. */
  29737. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  29738. var _this = this;
  29739. if (!BABYLON.PickingInfo) {
  29740. return null;
  29741. }
  29742. var result = this._internalPick(function (world) {
  29743. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  29744. return _this._tempPickingRay;
  29745. }, predicate, fastCheck);
  29746. if (result) {
  29747. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  29748. }
  29749. return result;
  29750. };
  29751. /** Use the given ray to pick a mesh in the scene
  29752. * @param ray The ray to use to pick meshes
  29753. * @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
  29754. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  29755. * @returns a PickingInfo
  29756. */
  29757. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  29758. var _this = this;
  29759. var result = this._internalPick(function (world) {
  29760. if (!_this._pickWithRayInverseMatrix) {
  29761. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29762. }
  29763. world.invertToRef(_this._pickWithRayInverseMatrix);
  29764. if (!_this._cachedRayForTransform) {
  29765. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29766. }
  29767. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29768. return _this._cachedRayForTransform;
  29769. }, predicate, fastCheck);
  29770. if (result) {
  29771. result.ray = ray;
  29772. }
  29773. return result;
  29774. };
  29775. /**
  29776. * Launch a ray to try to pick a mesh in the scene
  29777. * @param x X position on screen
  29778. * @param y Y position on screen
  29779. * @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
  29780. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29781. * @returns an array of PickingInfo
  29782. */
  29783. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  29784. var _this = this;
  29785. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  29786. };
  29787. /**
  29788. * Launch a ray to try to pick a mesh in the scene
  29789. * @param ray Ray to use
  29790. * @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
  29791. * @returns an array of PickingInfo
  29792. */
  29793. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  29794. var _this = this;
  29795. return this._internalMultiPick(function (world) {
  29796. if (!_this._pickWithRayInverseMatrix) {
  29797. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29798. }
  29799. world.invertToRef(_this._pickWithRayInverseMatrix);
  29800. if (!_this._cachedRayForTransform) {
  29801. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29802. }
  29803. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29804. return _this._cachedRayForTransform;
  29805. }, predicate);
  29806. };
  29807. /**
  29808. * Force the value of meshUnderPointer
  29809. * @param mesh defines the mesh to use
  29810. */
  29811. Scene.prototype.setPointerOverMesh = function (mesh) {
  29812. if (this._pointerOverMesh === mesh) {
  29813. return;
  29814. }
  29815. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29816. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29817. }
  29818. this._pointerOverMesh = mesh;
  29819. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29820. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29821. }
  29822. };
  29823. /**
  29824. * Gets the mesh under the pointer
  29825. * @returns a Mesh or null if no mesh is under the pointer
  29826. */
  29827. Scene.prototype.getPointerOverMesh = function () {
  29828. return this._pointerOverMesh;
  29829. };
  29830. // Misc.
  29831. /** @hidden */
  29832. Scene.prototype._rebuildGeometries = function () {
  29833. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  29834. var geometry = _a[_i];
  29835. geometry._rebuild();
  29836. }
  29837. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  29838. var mesh = _c[_b];
  29839. mesh._rebuild();
  29840. }
  29841. if (this.postProcessManager) {
  29842. this.postProcessManager._rebuild();
  29843. }
  29844. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  29845. var component = _e[_d];
  29846. component.rebuild();
  29847. }
  29848. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  29849. var system = _g[_f];
  29850. system.rebuild();
  29851. }
  29852. };
  29853. /** @hidden */
  29854. Scene.prototype._rebuildTextures = function () {
  29855. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29856. var texture = _a[_i];
  29857. texture._rebuild();
  29858. }
  29859. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29860. };
  29861. // Tags
  29862. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29863. if (tagsQuery === undefined) {
  29864. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29865. return list;
  29866. }
  29867. var listByTags = [];
  29868. forEach = forEach || (function (item) { return; });
  29869. for (var i in list) {
  29870. var item = list[i];
  29871. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29872. listByTags.push(item);
  29873. forEach(item);
  29874. }
  29875. }
  29876. return listByTags;
  29877. };
  29878. /**
  29879. * Get a list of meshes by tags
  29880. * @param tagsQuery defines the tags query to use
  29881. * @param forEach defines a predicate used to filter results
  29882. * @returns an array of Mesh
  29883. */
  29884. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29885. return this._getByTags(this.meshes, tagsQuery, forEach);
  29886. };
  29887. /**
  29888. * Get a list of cameras by tags
  29889. * @param tagsQuery defines the tags query to use
  29890. * @param forEach defines a predicate used to filter results
  29891. * @returns an array of Camera
  29892. */
  29893. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29894. return this._getByTags(this.cameras, tagsQuery, forEach);
  29895. };
  29896. /**
  29897. * Get a list of lights by tags
  29898. * @param tagsQuery defines the tags query to use
  29899. * @param forEach defines a predicate used to filter results
  29900. * @returns an array of Light
  29901. */
  29902. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29903. return this._getByTags(this.lights, tagsQuery, forEach);
  29904. };
  29905. /**
  29906. * Get a list of materials by tags
  29907. * @param tagsQuery defines the tags query to use
  29908. * @param forEach defines a predicate used to filter results
  29909. * @returns an array of Material
  29910. */
  29911. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29912. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29913. };
  29914. /**
  29915. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29916. * This allowed control for front to back rendering or reversly depending of the special needs.
  29917. *
  29918. * @param renderingGroupId The rendering group id corresponding to its index
  29919. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29920. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29921. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29922. */
  29923. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29924. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29925. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29926. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29927. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29928. };
  29929. /**
  29930. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29931. *
  29932. * @param renderingGroupId The rendering group id corresponding to its index
  29933. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29934. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29935. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29936. */
  29937. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29938. if (depth === void 0) { depth = true; }
  29939. if (stencil === void 0) { stencil = true; }
  29940. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29941. };
  29942. /**
  29943. * Gets the current auto clear configuration for one rendering group of the rendering
  29944. * manager.
  29945. * @param index the rendering group index to get the information for
  29946. * @returns The auto clear setup for the requested rendering group
  29947. */
  29948. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  29949. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  29950. };
  29951. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  29952. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  29953. get: function () {
  29954. return this._blockMaterialDirtyMechanism;
  29955. },
  29956. set: function (value) {
  29957. if (this._blockMaterialDirtyMechanism === value) {
  29958. return;
  29959. }
  29960. this._blockMaterialDirtyMechanism = value;
  29961. if (!value) { // Do a complete update
  29962. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  29963. }
  29964. },
  29965. enumerable: true,
  29966. configurable: true
  29967. });
  29968. /**
  29969. * Will flag all materials as dirty to trigger new shader compilation
  29970. * @param flag defines the flag used to specify which material part must be marked as dirty
  29971. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29972. */
  29973. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29974. if (this._blockMaterialDirtyMechanism) {
  29975. return;
  29976. }
  29977. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29978. var material = _a[_i];
  29979. if (predicate && !predicate(material)) {
  29980. continue;
  29981. }
  29982. material.markAsDirty(flag);
  29983. }
  29984. };
  29985. /** @hidden */
  29986. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useOfflineSupport, useArrayBuffer, onError) {
  29987. var _this = this;
  29988. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useOfflineSupport ? this.offlineProvider : undefined, useArrayBuffer, onError);
  29989. this._activeRequests.push(request);
  29990. request.onCompleteObservable.add(function (request) {
  29991. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29992. });
  29993. return request;
  29994. };
  29995. /** @hidden */
  29996. Scene.prototype._loadFileAsync = function (url, useOfflineSupport, useArrayBuffer) {
  29997. var _this = this;
  29998. return new Promise(function (resolve, reject) {
  29999. _this._loadFile(url, function (data) {
  30000. resolve(data);
  30001. }, undefined, useOfflineSupport, useArrayBuffer, function (request, exception) {
  30002. reject(exception);
  30003. });
  30004. });
  30005. };
  30006. // Statics
  30007. Scene._uniqueIdCounter = 0;
  30008. /** The fog is deactivated */
  30009. Scene.FOGMODE_NONE = 0;
  30010. /** The fog density is following an exponential function */
  30011. Scene.FOGMODE_EXP = 1;
  30012. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  30013. Scene.FOGMODE_EXP2 = 2;
  30014. /** The fog density is following a linear function. */
  30015. Scene.FOGMODE_LINEAR = 3;
  30016. /**
  30017. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  30018. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  30019. */
  30020. Scene.MinDeltaTime = 1.0;
  30021. /**
  30022. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  30023. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  30024. */
  30025. Scene.MaxDeltaTime = 1000.0;
  30026. /** The distance in pixel that you have to move to prevent some events */
  30027. Scene.DragMovementThreshold = 10; // in pixels
  30028. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  30029. Scene.LongPressDelay = 500; // in milliseconds
  30030. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  30031. Scene.DoubleClickDelay = 300; // in milliseconds
  30032. /** If you need to check double click without raising a single click at first click, enable this flag */
  30033. Scene.ExclusiveDoubleClickMode = false;
  30034. return Scene;
  30035. }(BABYLON.AbstractScene));
  30036. BABYLON.Scene = Scene;
  30037. })(BABYLON || (BABYLON = {}));
  30038. //# sourceMappingURL=scene.js.map
  30039. var BABYLON;
  30040. (function (BABYLON) {
  30041. /**
  30042. * Set of assets to keep when moving a scene into an asset container.
  30043. */
  30044. var KeepAssets = /** @class */ (function (_super) {
  30045. __extends(KeepAssets, _super);
  30046. function KeepAssets() {
  30047. return _super !== null && _super.apply(this, arguments) || this;
  30048. }
  30049. return KeepAssets;
  30050. }(BABYLON.AbstractScene));
  30051. BABYLON.KeepAssets = KeepAssets;
  30052. /**
  30053. * Container with a set of assets that can be added or removed from a scene.
  30054. */
  30055. var AssetContainer = /** @class */ (function (_super) {
  30056. __extends(AssetContainer, _super);
  30057. /**
  30058. * Instantiates an AssetContainer.
  30059. * @param scene The scene the AssetContainer belongs to.
  30060. */
  30061. function AssetContainer(scene) {
  30062. var _this = _super.call(this) || this;
  30063. _this.scene = scene;
  30064. _this["sounds"] = [];
  30065. _this["effectLayers"] = [];
  30066. _this["layers"] = [];
  30067. _this["lensFlareSystems"] = [];
  30068. _this["proceduralTextures"] = [];
  30069. return _this;
  30070. }
  30071. /**
  30072. * Adds all the assets from the container to the scene.
  30073. */
  30074. AssetContainer.prototype.addAllToScene = function () {
  30075. var _this = this;
  30076. this.cameras.forEach(function (o) {
  30077. _this.scene.addCamera(o);
  30078. });
  30079. this.lights.forEach(function (o) {
  30080. _this.scene.addLight(o);
  30081. });
  30082. this.meshes.forEach(function (o) {
  30083. _this.scene.addMesh(o);
  30084. });
  30085. this.skeletons.forEach(function (o) {
  30086. _this.scene.addSkeleton(o);
  30087. });
  30088. this.animations.forEach(function (o) {
  30089. _this.scene.addAnimation(o);
  30090. });
  30091. this.animationGroups.forEach(function (o) {
  30092. _this.scene.addAnimationGroup(o);
  30093. });
  30094. this.multiMaterials.forEach(function (o) {
  30095. _this.scene.addMultiMaterial(o);
  30096. });
  30097. this.materials.forEach(function (o) {
  30098. _this.scene.addMaterial(o);
  30099. });
  30100. this.morphTargetManagers.forEach(function (o) {
  30101. _this.scene.addMorphTargetManager(o);
  30102. });
  30103. this.geometries.forEach(function (o) {
  30104. _this.scene.addGeometry(o);
  30105. });
  30106. this.transformNodes.forEach(function (o) {
  30107. _this.scene.addTransformNode(o);
  30108. });
  30109. this.actionManagers.forEach(function (o) {
  30110. _this.scene.addActionManager(o);
  30111. });
  30112. this.textures.forEach(function (o) {
  30113. _this.scene.addTexture(o);
  30114. });
  30115. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  30116. var component = _a[_i];
  30117. component.addFromContainer(this);
  30118. }
  30119. };
  30120. /**
  30121. * Removes all the assets in the container from the scene
  30122. */
  30123. AssetContainer.prototype.removeAllFromScene = function () {
  30124. var _this = this;
  30125. this.cameras.forEach(function (o) {
  30126. _this.scene.removeCamera(o);
  30127. });
  30128. this.lights.forEach(function (o) {
  30129. _this.scene.removeLight(o);
  30130. });
  30131. this.meshes.forEach(function (o) {
  30132. _this.scene.removeMesh(o);
  30133. });
  30134. this.skeletons.forEach(function (o) {
  30135. _this.scene.removeSkeleton(o);
  30136. });
  30137. this.animations.forEach(function (o) {
  30138. _this.scene.removeAnimation(o);
  30139. });
  30140. this.animationGroups.forEach(function (o) {
  30141. _this.scene.removeAnimationGroup(o);
  30142. });
  30143. this.multiMaterials.forEach(function (o) {
  30144. _this.scene.removeMultiMaterial(o);
  30145. });
  30146. this.materials.forEach(function (o) {
  30147. _this.scene.removeMaterial(o);
  30148. });
  30149. this.morphTargetManagers.forEach(function (o) {
  30150. _this.scene.removeMorphTargetManager(o);
  30151. });
  30152. this.geometries.forEach(function (o) {
  30153. _this.scene.removeGeometry(o);
  30154. });
  30155. this.transformNodes.forEach(function (o) {
  30156. _this.scene.removeTransformNode(o);
  30157. });
  30158. this.actionManagers.forEach(function (o) {
  30159. _this.scene.removeActionManager(o);
  30160. });
  30161. this.textures.forEach(function (o) {
  30162. _this.scene.removeTexture(o);
  30163. });
  30164. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  30165. var component = _a[_i];
  30166. component.removeFromContainer(this);
  30167. }
  30168. };
  30169. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  30170. if (!sourceAssets) {
  30171. return;
  30172. }
  30173. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  30174. var asset = sourceAssets_1[_i];
  30175. var move = true;
  30176. if (keepAssets) {
  30177. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  30178. var keepAsset = keepAssets_1[_a];
  30179. if (asset === keepAsset) {
  30180. move = false;
  30181. break;
  30182. }
  30183. }
  30184. }
  30185. if (move) {
  30186. targetAssets.push(asset);
  30187. }
  30188. }
  30189. };
  30190. /**
  30191. * Removes all the assets contained in the scene and adds them to the container.
  30192. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  30193. */
  30194. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  30195. if (keepAssets === undefined) {
  30196. keepAssets = new KeepAssets();
  30197. }
  30198. for (var key in this) {
  30199. if (this.hasOwnProperty(key)) {
  30200. this[key] = this[key] || [];
  30201. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  30202. }
  30203. }
  30204. this.removeAllFromScene();
  30205. };
  30206. /**
  30207. * 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.
  30208. * @returns the root mesh
  30209. */
  30210. AssetContainer.prototype.createRootMesh = function () {
  30211. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  30212. this.meshes.forEach(function (m) {
  30213. if (!m.parent) {
  30214. rootMesh.addChild(m);
  30215. }
  30216. });
  30217. this.meshes.unshift(rootMesh);
  30218. return rootMesh;
  30219. };
  30220. return AssetContainer;
  30221. }(BABYLON.AbstractScene));
  30222. BABYLON.AssetContainer = AssetContainer;
  30223. })(BABYLON || (BABYLON = {}));
  30224. //# sourceMappingURL=assetContainer.js.map
  30225. var BABYLON;
  30226. (function (BABYLON) {
  30227. /**
  30228. * Class used to store data that will be store in GPU memory
  30229. */
  30230. var Buffer = /** @class */ (function () {
  30231. /**
  30232. * Constructor
  30233. * @param engine the engine
  30234. * @param data the data to use for this buffer
  30235. * @param updatable whether the data is updatable
  30236. * @param stride the stride (optional)
  30237. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  30238. * @param instanced whether the buffer is instanced (optional)
  30239. * @param useBytes set to true if the stride in in bytes (optional)
  30240. */
  30241. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  30242. if (stride === void 0) { stride = 0; }
  30243. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  30244. if (instanced === void 0) { instanced = false; }
  30245. if (useBytes === void 0) { useBytes = false; }
  30246. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  30247. this._engine = engine.getScene().getEngine();
  30248. }
  30249. else {
  30250. this._engine = engine;
  30251. }
  30252. this._updatable = updatable;
  30253. this._instanced = instanced;
  30254. this._data = data;
  30255. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  30256. if (!postponeInternalCreation) { // by default
  30257. this.create();
  30258. }
  30259. }
  30260. /**
  30261. * Create a new VertexBuffer based on the current buffer
  30262. * @param kind defines the vertex buffer kind (position, normal, etc.)
  30263. * @param offset defines offset in the buffer (0 by default)
  30264. * @param size defines the size in floats of attributes (position is 3 for instance)
  30265. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  30266. * @param instanced defines if the vertex buffer contains indexed data
  30267. * @param useBytes defines if the offset and stride are in bytes
  30268. * @returns the new vertex buffer
  30269. */
  30270. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  30271. if (useBytes === void 0) { useBytes = false; }
  30272. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  30273. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  30274. // a lot of these parameters are ignored as they are overriden by the buffer
  30275. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  30276. };
  30277. // Properties
  30278. /**
  30279. * Gets a boolean indicating if the Buffer is updatable?
  30280. * @returns true if the buffer is updatable
  30281. */
  30282. Buffer.prototype.isUpdatable = function () {
  30283. return this._updatable;
  30284. };
  30285. /**
  30286. * Gets current buffer's data
  30287. * @returns a DataArray or null
  30288. */
  30289. Buffer.prototype.getData = function () {
  30290. return this._data;
  30291. };
  30292. /**
  30293. * Gets underlying native buffer
  30294. * @returns underlying native buffer
  30295. */
  30296. Buffer.prototype.getBuffer = function () {
  30297. return this._buffer;
  30298. };
  30299. /**
  30300. * Gets the stride in float32 units (i.e. byte stride / 4).
  30301. * May not be an integer if the byte stride is not divisible by 4.
  30302. * DEPRECATED. Use byteStride instead.
  30303. * @returns the stride in float32 units
  30304. */
  30305. Buffer.prototype.getStrideSize = function () {
  30306. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  30307. };
  30308. // Methods
  30309. /**
  30310. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  30311. * @param data defines the data to store
  30312. */
  30313. Buffer.prototype.create = function (data) {
  30314. if (data === void 0) { data = null; }
  30315. if (!data && this._buffer) {
  30316. return; // nothing to do
  30317. }
  30318. data = data || this._data;
  30319. if (!data) {
  30320. return;
  30321. }
  30322. if (!this._buffer) { // create buffer
  30323. if (this._updatable) {
  30324. this._buffer = this._engine.createDynamicVertexBuffer(data);
  30325. this._data = data;
  30326. }
  30327. else {
  30328. this._buffer = this._engine.createVertexBuffer(data);
  30329. }
  30330. }
  30331. else if (this._updatable) { // update buffer
  30332. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  30333. this._data = data;
  30334. }
  30335. };
  30336. /** @hidden */
  30337. Buffer.prototype._rebuild = function () {
  30338. this._buffer = null;
  30339. this.create(this._data);
  30340. };
  30341. /**
  30342. * Update current buffer data
  30343. * @param data defines the data to store
  30344. */
  30345. Buffer.prototype.update = function (data) {
  30346. this.create(data);
  30347. };
  30348. /**
  30349. * Updates the data directly.
  30350. * @param data the new data
  30351. * @param offset the new offset
  30352. * @param vertexCount the vertex count (optional)
  30353. * @param useBytes set to true if the offset is in bytes
  30354. */
  30355. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  30356. if (useBytes === void 0) { useBytes = false; }
  30357. if (!this._buffer) {
  30358. return;
  30359. }
  30360. if (this._updatable) { // update buffer
  30361. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  30362. this._data = null;
  30363. }
  30364. };
  30365. /**
  30366. * Release all resources
  30367. */
  30368. Buffer.prototype.dispose = function () {
  30369. if (!this._buffer) {
  30370. return;
  30371. }
  30372. if (this._engine._releaseBuffer(this._buffer)) {
  30373. this._buffer = null;
  30374. }
  30375. };
  30376. return Buffer;
  30377. }());
  30378. BABYLON.Buffer = Buffer;
  30379. })(BABYLON || (BABYLON = {}));
  30380. //# sourceMappingURL=buffer.js.map
  30381. var BABYLON;
  30382. (function (BABYLON) {
  30383. /**
  30384. * Specialized buffer used to store vertex data
  30385. */
  30386. var VertexBuffer = /** @class */ (function () {
  30387. /**
  30388. * Constructor
  30389. * @param engine the engine
  30390. * @param data the data to use for this vertex buffer
  30391. * @param kind the vertex buffer kind
  30392. * @param updatable whether the data is updatable
  30393. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  30394. * @param stride the stride (optional)
  30395. * @param instanced whether the buffer is instanced (optional)
  30396. * @param offset the offset of the data (optional)
  30397. * @param size the number of components (optional)
  30398. * @param type the type of the component (optional)
  30399. * @param normalized whether the data contains normalized data (optional)
  30400. * @param useBytes set to true if stride and offset are in bytes (optional)
  30401. */
  30402. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  30403. if (normalized === void 0) { normalized = false; }
  30404. if (useBytes === void 0) { useBytes = false; }
  30405. if (data instanceof BABYLON.Buffer) {
  30406. this._buffer = data;
  30407. this._ownsBuffer = false;
  30408. }
  30409. else {
  30410. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  30411. this._ownsBuffer = true;
  30412. }
  30413. this._kind = kind;
  30414. if (type == undefined) {
  30415. var data_1 = this.getData();
  30416. this.type = VertexBuffer.FLOAT;
  30417. if (data_1 instanceof Int8Array) {
  30418. this.type = VertexBuffer.BYTE;
  30419. }
  30420. else if (data_1 instanceof Uint8Array) {
  30421. this.type = VertexBuffer.UNSIGNED_BYTE;
  30422. }
  30423. else if (data_1 instanceof Int16Array) {
  30424. this.type = VertexBuffer.SHORT;
  30425. }
  30426. else if (data_1 instanceof Uint16Array) {
  30427. this.type = VertexBuffer.UNSIGNED_SHORT;
  30428. }
  30429. else if (data_1 instanceof Int32Array) {
  30430. this.type = VertexBuffer.INT;
  30431. }
  30432. else if (data_1 instanceof Uint32Array) {
  30433. this.type = VertexBuffer.UNSIGNED_INT;
  30434. }
  30435. }
  30436. else {
  30437. this.type = type;
  30438. }
  30439. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  30440. if (useBytes) {
  30441. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  30442. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  30443. this.byteOffset = offset || 0;
  30444. }
  30445. else {
  30446. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  30447. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  30448. this.byteOffset = (offset || 0) * typeByteLength;
  30449. }
  30450. this.normalized = normalized;
  30451. this._instanced = instanced !== undefined ? instanced : false;
  30452. this._instanceDivisor = instanced ? 1 : 0;
  30453. }
  30454. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  30455. /**
  30456. * Gets or sets the instance divisor when in instanced mode
  30457. */
  30458. get: function () {
  30459. return this._instanceDivisor;
  30460. },
  30461. set: function (value) {
  30462. this._instanceDivisor = value;
  30463. if (value == 0) {
  30464. this._instanced = false;
  30465. }
  30466. else {
  30467. this._instanced = true;
  30468. }
  30469. },
  30470. enumerable: true,
  30471. configurable: true
  30472. });
  30473. /** @hidden */
  30474. VertexBuffer.prototype._rebuild = function () {
  30475. if (!this._buffer) {
  30476. return;
  30477. }
  30478. this._buffer._rebuild();
  30479. };
  30480. /**
  30481. * Returns the kind of the VertexBuffer (string)
  30482. * @returns a string
  30483. */
  30484. VertexBuffer.prototype.getKind = function () {
  30485. return this._kind;
  30486. };
  30487. // Properties
  30488. /**
  30489. * Gets a boolean indicating if the VertexBuffer is updatable?
  30490. * @returns true if the buffer is updatable
  30491. */
  30492. VertexBuffer.prototype.isUpdatable = function () {
  30493. return this._buffer.isUpdatable();
  30494. };
  30495. /**
  30496. * Gets current buffer's data
  30497. * @returns a DataArray or null
  30498. */
  30499. VertexBuffer.prototype.getData = function () {
  30500. return this._buffer.getData();
  30501. };
  30502. /**
  30503. * Gets underlying native buffer
  30504. * @returns underlying native buffer
  30505. */
  30506. VertexBuffer.prototype.getBuffer = function () {
  30507. return this._buffer.getBuffer();
  30508. };
  30509. /**
  30510. * Gets the stride in float32 units (i.e. byte stride / 4).
  30511. * May not be an integer if the byte stride is not divisible by 4.
  30512. * DEPRECATED. Use byteStride instead.
  30513. * @returns the stride in float32 units
  30514. */
  30515. VertexBuffer.prototype.getStrideSize = function () {
  30516. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  30517. };
  30518. /**
  30519. * Returns the offset as a multiple of the type byte length.
  30520. * DEPRECATED. Use byteOffset instead.
  30521. * @returns the offset in bytes
  30522. */
  30523. VertexBuffer.prototype.getOffset = function () {
  30524. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  30525. };
  30526. /**
  30527. * Returns the number of components per vertex attribute (integer)
  30528. * @returns the size in float
  30529. */
  30530. VertexBuffer.prototype.getSize = function () {
  30531. return this._size;
  30532. };
  30533. /**
  30534. * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced
  30535. * @returns true if this buffer is instanced
  30536. */
  30537. VertexBuffer.prototype.getIsInstanced = function () {
  30538. return this._instanced;
  30539. };
  30540. /**
  30541. * Returns the instancing divisor, zero for non-instanced (integer).
  30542. * @returns a number
  30543. */
  30544. VertexBuffer.prototype.getInstanceDivisor = function () {
  30545. return this._instanceDivisor;
  30546. };
  30547. // Methods
  30548. /**
  30549. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  30550. * @param data defines the data to store
  30551. */
  30552. VertexBuffer.prototype.create = function (data) {
  30553. this._buffer.create(data);
  30554. };
  30555. /**
  30556. * Updates the underlying buffer according to the passed numeric array or Float32Array.
  30557. * This function will create a new buffer if the current one is not updatable
  30558. * @param data defines the data to store
  30559. */
  30560. VertexBuffer.prototype.update = function (data) {
  30561. this._buffer.update(data);
  30562. };
  30563. /**
  30564. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  30565. * Returns the directly updated WebGLBuffer.
  30566. * @param data the new data
  30567. * @param offset the new offset
  30568. * @param useBytes set to true if the offset is in bytes
  30569. */
  30570. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  30571. if (useBytes === void 0) { useBytes = false; }
  30572. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  30573. };
  30574. /**
  30575. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  30576. */
  30577. VertexBuffer.prototype.dispose = function () {
  30578. if (this._ownsBuffer) {
  30579. this._buffer.dispose();
  30580. }
  30581. };
  30582. /**
  30583. * Enumerates each value of this vertex buffer as numbers.
  30584. * @param count the number of values to enumerate
  30585. * @param callback the callback function called for each value
  30586. */
  30587. VertexBuffer.prototype.forEach = function (count, callback) {
  30588. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  30589. };
  30590. /**
  30591. * Deduces the stride given a kind.
  30592. * @param kind The kind string to deduce
  30593. * @returns The deduced stride
  30594. */
  30595. VertexBuffer.DeduceStride = function (kind) {
  30596. switch (kind) {
  30597. case VertexBuffer.UVKind:
  30598. case VertexBuffer.UV2Kind:
  30599. case VertexBuffer.UV3Kind:
  30600. case VertexBuffer.UV4Kind:
  30601. case VertexBuffer.UV5Kind:
  30602. case VertexBuffer.UV6Kind:
  30603. return 2;
  30604. case VertexBuffer.NormalKind:
  30605. case VertexBuffer.PositionKind:
  30606. return 3;
  30607. case VertexBuffer.ColorKind:
  30608. case VertexBuffer.MatricesIndicesKind:
  30609. case VertexBuffer.MatricesIndicesExtraKind:
  30610. case VertexBuffer.MatricesWeightsKind:
  30611. case VertexBuffer.MatricesWeightsExtraKind:
  30612. case VertexBuffer.TangentKind:
  30613. return 4;
  30614. default:
  30615. throw new Error("Invalid kind '" + kind + "'");
  30616. }
  30617. };
  30618. /**
  30619. * Gets the byte length of the given type.
  30620. * @param type the type
  30621. * @returns the number of bytes
  30622. */
  30623. VertexBuffer.GetTypeByteLength = function (type) {
  30624. switch (type) {
  30625. case VertexBuffer.BYTE:
  30626. case VertexBuffer.UNSIGNED_BYTE:
  30627. return 1;
  30628. case VertexBuffer.SHORT:
  30629. case VertexBuffer.UNSIGNED_SHORT:
  30630. return 2;
  30631. case VertexBuffer.INT:
  30632. case VertexBuffer.FLOAT:
  30633. return 4;
  30634. default:
  30635. throw new Error("Invalid type '" + type + "'");
  30636. }
  30637. };
  30638. /**
  30639. * Enumerates each value of the given parameters as numbers.
  30640. * @param data the data to enumerate
  30641. * @param byteOffset the byte offset of the data
  30642. * @param byteStride the byte stride of the data
  30643. * @param componentCount the number of components per element
  30644. * @param componentType the type of the component
  30645. * @param count the total number of components
  30646. * @param normalized whether the data is normalized
  30647. * @param callback the callback function called for each value
  30648. */
  30649. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30650. if (data instanceof Array) {
  30651. var offset = byteOffset / 4;
  30652. var stride = byteStride / 4;
  30653. for (var index = 0; index < count; index += componentCount) {
  30654. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30655. callback(data[offset + componentIndex], index + componentIndex);
  30656. }
  30657. offset += stride;
  30658. }
  30659. }
  30660. else {
  30661. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30662. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30663. for (var index = 0; index < count; index += componentCount) {
  30664. var componentByteOffset = byteOffset;
  30665. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30666. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30667. callback(value, index + componentIndex);
  30668. componentByteOffset += componentByteLength;
  30669. }
  30670. byteOffset += byteStride;
  30671. }
  30672. }
  30673. };
  30674. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30675. switch (type) {
  30676. case VertexBuffer.BYTE: {
  30677. var value = dataView.getInt8(byteOffset);
  30678. if (normalized) {
  30679. value = Math.max(value / 127, -1);
  30680. }
  30681. return value;
  30682. }
  30683. case VertexBuffer.UNSIGNED_BYTE: {
  30684. var value = dataView.getUint8(byteOffset);
  30685. if (normalized) {
  30686. value = value / 255;
  30687. }
  30688. return value;
  30689. }
  30690. case VertexBuffer.SHORT: {
  30691. var value = dataView.getInt16(byteOffset, true);
  30692. if (normalized) {
  30693. value = Math.max(value / 16383, -1);
  30694. }
  30695. return value;
  30696. }
  30697. case VertexBuffer.UNSIGNED_SHORT: {
  30698. var value = dataView.getUint16(byteOffset, true);
  30699. if (normalized) {
  30700. value = value / 65535;
  30701. }
  30702. return value;
  30703. }
  30704. case VertexBuffer.FLOAT: {
  30705. return dataView.getFloat32(byteOffset, true);
  30706. }
  30707. default: {
  30708. throw new Error("Invalid component type " + type);
  30709. }
  30710. }
  30711. };
  30712. /**
  30713. * The byte type.
  30714. */
  30715. VertexBuffer.BYTE = 5120;
  30716. /**
  30717. * The unsigned byte type.
  30718. */
  30719. VertexBuffer.UNSIGNED_BYTE = 5121;
  30720. /**
  30721. * The short type.
  30722. */
  30723. VertexBuffer.SHORT = 5122;
  30724. /**
  30725. * The unsigned short type.
  30726. */
  30727. VertexBuffer.UNSIGNED_SHORT = 5123;
  30728. /**
  30729. * The integer type.
  30730. */
  30731. VertexBuffer.INT = 5124;
  30732. /**
  30733. * The unsigned integer type.
  30734. */
  30735. VertexBuffer.UNSIGNED_INT = 5125;
  30736. /**
  30737. * The float type.
  30738. */
  30739. VertexBuffer.FLOAT = 5126;
  30740. // Enums
  30741. /**
  30742. * Positions
  30743. */
  30744. VertexBuffer.PositionKind = "position";
  30745. /**
  30746. * Normals
  30747. */
  30748. VertexBuffer.NormalKind = "normal";
  30749. /**
  30750. * Tangents
  30751. */
  30752. VertexBuffer.TangentKind = "tangent";
  30753. /**
  30754. * Texture coordinates
  30755. */
  30756. VertexBuffer.UVKind = "uv";
  30757. /**
  30758. * Texture coordinates 2
  30759. */
  30760. VertexBuffer.UV2Kind = "uv2";
  30761. /**
  30762. * Texture coordinates 3
  30763. */
  30764. VertexBuffer.UV3Kind = "uv3";
  30765. /**
  30766. * Texture coordinates 4
  30767. */
  30768. VertexBuffer.UV4Kind = "uv4";
  30769. /**
  30770. * Texture coordinates 5
  30771. */
  30772. VertexBuffer.UV5Kind = "uv5";
  30773. /**
  30774. * Texture coordinates 6
  30775. */
  30776. VertexBuffer.UV6Kind = "uv6";
  30777. /**
  30778. * Colors
  30779. */
  30780. VertexBuffer.ColorKind = "color";
  30781. /**
  30782. * Matrix indices (for bones)
  30783. */
  30784. VertexBuffer.MatricesIndicesKind = "matricesIndices";
  30785. /**
  30786. * Matrix weights (for bones)
  30787. */
  30788. VertexBuffer.MatricesWeightsKind = "matricesWeights";
  30789. /**
  30790. * Additional matrix indices (for bones)
  30791. */
  30792. VertexBuffer.MatricesIndicesExtraKind = "matricesIndicesExtra";
  30793. /**
  30794. * Additional matrix weights (for bones)
  30795. */
  30796. VertexBuffer.MatricesWeightsExtraKind = "matricesWeightsExtra";
  30797. return VertexBuffer;
  30798. }());
  30799. BABYLON.VertexBuffer = VertexBuffer;
  30800. })(BABYLON || (BABYLON = {}));
  30801. //# sourceMappingURL=vertexBuffer.js.map
  30802. //# sourceMappingURL=internalTextureLoader.js.map
  30803. var BABYLON;
  30804. (function (BABYLON) {
  30805. /**
  30806. * Internal class used by the engine to get list of InternalTexture already bound to the GL context
  30807. */
  30808. var DummyInternalTextureTracker = /** @class */ (function () {
  30809. function DummyInternalTextureTracker() {
  30810. /**
  30811. * Gets or set the previous tracker in the list
  30812. */
  30813. this.previous = null;
  30814. /**
  30815. * Gets or set the next tracker in the list
  30816. */
  30817. this.next = null;
  30818. }
  30819. return DummyInternalTextureTracker;
  30820. }());
  30821. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30822. })(BABYLON || (BABYLON = {}));
  30823. //# sourceMappingURL=internalTextureTracker.js.map
  30824. var BABYLON;
  30825. (function (BABYLON) {
  30826. /**
  30827. * Class used to store data associated with WebGL texture data for the engine
  30828. * This class should not be used directly
  30829. */
  30830. var InternalTexture = /** @class */ (function () {
  30831. /**
  30832. * Creates a new InternalTexture
  30833. * @param engine defines the engine to use
  30834. * @param dataSource defines the type of data that will be used
  30835. * @param delayAllocation if the texture allocation should be delayed (default: false)
  30836. */
  30837. function InternalTexture(engine, dataSource, delayAllocation) {
  30838. if (delayAllocation === void 0) { delayAllocation = false; }
  30839. /**
  30840. * Observable called when the texture is loaded
  30841. */
  30842. this.onLoadedObservable = new BABYLON.Observable();
  30843. /**
  30844. * Gets or set the previous tracker in the list
  30845. */
  30846. this.previous = null;
  30847. /**
  30848. * Gets or set the next tracker in the list
  30849. */
  30850. this.next = null;
  30851. // Private
  30852. /** @hidden */
  30853. this._initialSlot = -1;
  30854. /** @hidden */
  30855. this._designatedSlot = -1;
  30856. /** @hidden */
  30857. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30858. /** @hidden */
  30859. this._comparisonFunction = 0;
  30860. /** @hidden */
  30861. this._sphericalPolynomial = null;
  30862. /** @hidden */
  30863. this._lodGenerationScale = 0;
  30864. /** @hidden */
  30865. this._lodGenerationOffset = 0;
  30866. /** @hidden */
  30867. this._isRGBD = false;
  30868. /** @hidden */
  30869. this._references = 1;
  30870. this._engine = engine;
  30871. this._dataSource = dataSource;
  30872. if (!delayAllocation) {
  30873. this._webGLTexture = engine._createTexture();
  30874. }
  30875. }
  30876. /**
  30877. * Gets the Engine the texture belongs to.
  30878. * @returns The babylon engine
  30879. */
  30880. InternalTexture.prototype.getEngine = function () {
  30881. return this._engine;
  30882. };
  30883. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30884. /**
  30885. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30886. */
  30887. get: function () {
  30888. return this._dataSource;
  30889. },
  30890. enumerable: true,
  30891. configurable: true
  30892. });
  30893. /**
  30894. * Increments the number of references (ie. the number of Texture that point to it)
  30895. */
  30896. InternalTexture.prototype.incrementReferences = function () {
  30897. this._references++;
  30898. };
  30899. /**
  30900. * Change the size of the texture (not the size of the content)
  30901. * @param width defines the new width
  30902. * @param height defines the new height
  30903. * @param depth defines the new depth (1 by default)
  30904. */
  30905. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30906. if (depth === void 0) { depth = 1; }
  30907. this.width = width;
  30908. this.height = height;
  30909. this.depth = depth;
  30910. this.baseWidth = width;
  30911. this.baseHeight = height;
  30912. this.baseDepth = depth;
  30913. this._size = width * height * depth;
  30914. };
  30915. /** @hidden */
  30916. InternalTexture.prototype._rebuild = function () {
  30917. var _this = this;
  30918. var proxy;
  30919. this.isReady = false;
  30920. this._cachedCoordinatesMode = null;
  30921. this._cachedWrapU = null;
  30922. this._cachedWrapV = null;
  30923. this._cachedAnisotropicFilteringLevel = null;
  30924. switch (this._dataSource) {
  30925. case InternalTexture.DATASOURCE_TEMP:
  30926. return;
  30927. case InternalTexture.DATASOURCE_URL:
  30928. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30929. _this.isReady = true;
  30930. }, null, this._buffer, undefined, this.format);
  30931. proxy._swapAndDie(this);
  30932. return;
  30933. case InternalTexture.DATASOURCE_RAW:
  30934. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30935. proxy._swapAndDie(this);
  30936. this.isReady = true;
  30937. return;
  30938. case InternalTexture.DATASOURCE_RAW3D:
  30939. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30940. proxy._swapAndDie(this);
  30941. this.isReady = true;
  30942. return;
  30943. case InternalTexture.DATASOURCE_DYNAMIC:
  30944. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30945. proxy._swapAndDie(this);
  30946. this._engine.updateDynamicTexture(this, this._engine.getRenderingCanvas(), this.invertY, undefined, undefined, true);
  30947. // The engine will make sure to update content so no need to flag it as isReady = true
  30948. return;
  30949. case InternalTexture.DATASOURCE_RENDERTARGET:
  30950. var options = new BABYLON.RenderTargetCreationOptions();
  30951. options.generateDepthBuffer = this._generateDepthBuffer;
  30952. options.generateMipMaps = this.generateMipMaps;
  30953. options.generateStencilBuffer = this._generateStencilBuffer;
  30954. options.samplingMode = this.samplingMode;
  30955. options.type = this.type;
  30956. if (this.isCube) {
  30957. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30958. }
  30959. else {
  30960. var size = {
  30961. width: this.width,
  30962. height: this.height
  30963. };
  30964. proxy = this._engine.createRenderTargetTexture(size, options);
  30965. }
  30966. proxy._swapAndDie(this);
  30967. this.isReady = true;
  30968. return;
  30969. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30970. var depthTextureOptions = {
  30971. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30972. comparisonFunction: this._comparisonFunction,
  30973. generateStencil: this._generateStencilBuffer,
  30974. isCube: this.isCube
  30975. };
  30976. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30977. proxy._swapAndDie(this);
  30978. this.isReady = true;
  30979. return;
  30980. case InternalTexture.DATASOURCE_CUBE:
  30981. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30982. _this.isReady = true;
  30983. }, null, this.format, this._extension);
  30984. proxy._swapAndDie(this);
  30985. return;
  30986. case InternalTexture.DATASOURCE_CUBERAW:
  30987. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30988. proxy._swapAndDie(this);
  30989. this.isReady = true;
  30990. return;
  30991. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30992. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30993. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30994. _this.isReady = true;
  30995. });
  30996. proxy._swapAndDie(this);
  30997. return;
  30998. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30999. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  31000. if (proxy) {
  31001. proxy._swapAndDie(_this);
  31002. }
  31003. _this.isReady = true;
  31004. }, null, this.format, this._extension);
  31005. proxy._sphericalPolynomial = this._sphericalPolynomial;
  31006. return;
  31007. }
  31008. };
  31009. /** @hidden */
  31010. InternalTexture.prototype._swapAndDie = function (target) {
  31011. target._webGLTexture = this._webGLTexture;
  31012. if (this._framebuffer) {
  31013. target._framebuffer = this._framebuffer;
  31014. }
  31015. if (this._depthStencilBuffer) {
  31016. target._depthStencilBuffer = this._depthStencilBuffer;
  31017. }
  31018. if (this._lodTextureHigh) {
  31019. if (target._lodTextureHigh) {
  31020. target._lodTextureHigh.dispose();
  31021. }
  31022. target._lodTextureHigh = this._lodTextureHigh;
  31023. }
  31024. if (this._lodTextureMid) {
  31025. if (target._lodTextureMid) {
  31026. target._lodTextureMid.dispose();
  31027. }
  31028. target._lodTextureMid = this._lodTextureMid;
  31029. }
  31030. if (this._lodTextureLow) {
  31031. if (target._lodTextureLow) {
  31032. target._lodTextureLow.dispose();
  31033. }
  31034. target._lodTextureLow = this._lodTextureLow;
  31035. }
  31036. var cache = this._engine.getLoadedTexturesCache();
  31037. var index = cache.indexOf(this);
  31038. if (index !== -1) {
  31039. cache.splice(index, 1);
  31040. }
  31041. };
  31042. /**
  31043. * Dispose the current allocated resources
  31044. */
  31045. InternalTexture.prototype.dispose = function () {
  31046. if (!this._webGLTexture) {
  31047. return;
  31048. }
  31049. this._references--;
  31050. if (this._references === 0) {
  31051. this._engine._releaseTexture(this);
  31052. this._webGLTexture = null;
  31053. this.previous = null;
  31054. this.next = null;
  31055. }
  31056. };
  31057. /**
  31058. * The source of the texture data is unknown
  31059. */
  31060. InternalTexture.DATASOURCE_UNKNOWN = 0;
  31061. /**
  31062. * Texture data comes from an URL
  31063. */
  31064. InternalTexture.DATASOURCE_URL = 1;
  31065. /**
  31066. * Texture data is only used for temporary storage
  31067. */
  31068. InternalTexture.DATASOURCE_TEMP = 2;
  31069. /**
  31070. * Texture data comes from raw data (ArrayBuffer)
  31071. */
  31072. InternalTexture.DATASOURCE_RAW = 3;
  31073. /**
  31074. * Texture content is dynamic (video or dynamic texture)
  31075. */
  31076. InternalTexture.DATASOURCE_DYNAMIC = 4;
  31077. /**
  31078. * Texture content is generated by rendering to it
  31079. */
  31080. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  31081. /**
  31082. * Texture content is part of a multi render target process
  31083. */
  31084. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  31085. /**
  31086. * Texture data comes from a cube data file
  31087. */
  31088. InternalTexture.DATASOURCE_CUBE = 7;
  31089. /**
  31090. * Texture data comes from a raw cube data
  31091. */
  31092. InternalTexture.DATASOURCE_CUBERAW = 8;
  31093. /**
  31094. * Texture data come from a prefiltered cube data file
  31095. */
  31096. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  31097. /**
  31098. * Texture content is raw 3D data
  31099. */
  31100. InternalTexture.DATASOURCE_RAW3D = 10;
  31101. /**
  31102. * Texture content is a depth texture
  31103. */
  31104. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  31105. /**
  31106. * Texture data comes from a raw cube data encoded with RGBD
  31107. */
  31108. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  31109. return InternalTexture;
  31110. }());
  31111. BABYLON.InternalTexture = InternalTexture;
  31112. })(BABYLON || (BABYLON = {}));
  31113. //# sourceMappingURL=internalTexture.js.map
  31114. var BABYLON;
  31115. (function (BABYLON) {
  31116. /**
  31117. * Base class of all the textures in babylon.
  31118. * It groups all the common properties the materials, post process, lights... might need
  31119. * in order to make a correct use of the texture.
  31120. */
  31121. var BaseTexture = /** @class */ (function () {
  31122. /**
  31123. * Instantiates a new BaseTexture.
  31124. * Base class of all the textures in babylon.
  31125. * It groups all the common properties the materials, post process, lights... might need
  31126. * in order to make a correct use of the texture.
  31127. * @param scene Define the scene the texture blongs to
  31128. */
  31129. function BaseTexture(scene) {
  31130. this._hasAlpha = false;
  31131. /**
  31132. * Defines if the alpha value should be determined via the rgb values.
  31133. * If true the luminance of the pixel might be used to find the corresponding alpha value.
  31134. */
  31135. this.getAlphaFromRGB = false;
  31136. /**
  31137. * Intensity or strength of the texture.
  31138. * It is commonly used by materials to fine tune the intensity of the texture
  31139. */
  31140. this.level = 1;
  31141. /**
  31142. * Define the UV chanel to use starting from 0 and defaulting to 0.
  31143. * This is part of the texture as textures usually maps to one uv set.
  31144. */
  31145. this.coordinatesIndex = 0;
  31146. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  31147. /**
  31148. * | Value | Type | Description |
  31149. * | ----- | ------------------ | ----------- |
  31150. * | 0 | CLAMP_ADDRESSMODE | |
  31151. * | 1 | WRAP_ADDRESSMODE | |
  31152. * | 2 | MIRROR_ADDRESSMODE | |
  31153. */
  31154. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31155. /**
  31156. * | Value | Type | Description |
  31157. * | ----- | ------------------ | ----------- |
  31158. * | 0 | CLAMP_ADDRESSMODE | |
  31159. * | 1 | WRAP_ADDRESSMODE | |
  31160. * | 2 | MIRROR_ADDRESSMODE | |
  31161. */
  31162. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31163. /**
  31164. * | Value | Type | Description |
  31165. * | ----- | ------------------ | ----------- |
  31166. * | 0 | CLAMP_ADDRESSMODE | |
  31167. * | 1 | WRAP_ADDRESSMODE | |
  31168. * | 2 | MIRROR_ADDRESSMODE | |
  31169. */
  31170. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  31171. /**
  31172. * With compliant hardware and browser (supporting anisotropic filtering)
  31173. * this defines the level of anisotropic filtering in the texture.
  31174. * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.
  31175. */
  31176. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  31177. /**
  31178. * Define if the texture is a cube texture or if false a 2d texture.
  31179. */
  31180. this.isCube = false;
  31181. /**
  31182. * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.
  31183. */
  31184. this.is3D = false;
  31185. /**
  31186. * Define if the texture contains data in gamma space (most of the png/jpg aside bump).
  31187. * HDR texture are usually stored in linear space.
  31188. * This only impacts the PBR and Background materials
  31189. */
  31190. this.gammaSpace = true;
  31191. /**
  31192. * Is Z inverted in the texture (useful in a cube texture).
  31193. */
  31194. this.invertZ = false;
  31195. /**
  31196. * @hidden
  31197. */
  31198. this.lodLevelInAlpha = false;
  31199. /**
  31200. * Define if the texture is a render target.
  31201. */
  31202. this.isRenderTarget = false;
  31203. /**
  31204. * Define the list of animation attached to the texture.
  31205. */
  31206. this.animations = new Array();
  31207. /**
  31208. * An event triggered when the texture is disposed.
  31209. */
  31210. this.onDisposeObservable = new BABYLON.Observable();
  31211. /**
  31212. * Define the current state of the loading sequence when in delayed load mode.
  31213. */
  31214. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31215. this._cachedSize = BABYLON.Size.Zero();
  31216. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31217. if (this._scene) {
  31218. this._scene.textures.push(this);
  31219. this._scene.onNewTextureAddedObservable.notifyObservers(this);
  31220. }
  31221. this._uid = null;
  31222. }
  31223. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  31224. get: function () {
  31225. return this._hasAlpha;
  31226. },
  31227. /**
  31228. * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance).
  31229. */
  31230. set: function (value) {
  31231. if (this._hasAlpha === value) {
  31232. return;
  31233. }
  31234. this._hasAlpha = value;
  31235. if (this._scene) {
  31236. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  31237. }
  31238. },
  31239. enumerable: true,
  31240. configurable: true
  31241. });
  31242. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  31243. get: function () {
  31244. return this._coordinatesMode;
  31245. },
  31246. /**
  31247. * How a texture is mapped.
  31248. *
  31249. * | Value | Type | Description |
  31250. * | ----- | ----------------------------------- | ----------- |
  31251. * | 0 | EXPLICIT_MODE | |
  31252. * | 1 | SPHERICAL_MODE | |
  31253. * | 2 | PLANAR_MODE | |
  31254. * | 3 | CUBIC_MODE | |
  31255. * | 4 | PROJECTION_MODE | |
  31256. * | 5 | SKYBOX_MODE | |
  31257. * | 6 | INVCUBIC_MODE | |
  31258. * | 7 | EQUIRECTANGULAR_MODE | |
  31259. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  31260. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  31261. */
  31262. set: function (value) {
  31263. if (this._coordinatesMode === value) {
  31264. return;
  31265. }
  31266. this._coordinatesMode = value;
  31267. if (this._scene) {
  31268. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31269. }
  31270. },
  31271. enumerable: true,
  31272. configurable: true
  31273. });
  31274. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  31275. /**
  31276. * Gets whether or not the texture contains RGBD data.
  31277. */
  31278. get: function () {
  31279. return this._texture != null && this._texture._isRGBD;
  31280. },
  31281. enumerable: true,
  31282. configurable: true
  31283. });
  31284. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  31285. /**
  31286. * With prefiltered texture, defined the offset used during the prefiltering steps.
  31287. */
  31288. get: function () {
  31289. if (this._texture) {
  31290. return this._texture._lodGenerationOffset;
  31291. }
  31292. return 0.0;
  31293. },
  31294. set: function (value) {
  31295. if (this._texture) {
  31296. this._texture._lodGenerationOffset = value;
  31297. }
  31298. },
  31299. enumerable: true,
  31300. configurable: true
  31301. });
  31302. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  31303. /**
  31304. * With prefiltered texture, defined the scale used during the prefiltering steps.
  31305. */
  31306. get: function () {
  31307. if (this._texture) {
  31308. return this._texture._lodGenerationScale;
  31309. }
  31310. return 0.0;
  31311. },
  31312. set: function (value) {
  31313. if (this._texture) {
  31314. this._texture._lodGenerationScale = value;
  31315. }
  31316. },
  31317. enumerable: true,
  31318. configurable: true
  31319. });
  31320. Object.defineProperty(BaseTexture.prototype, "uid", {
  31321. /**
  31322. * Define the unique id of the texture in the scene.
  31323. */
  31324. get: function () {
  31325. if (!this._uid) {
  31326. this._uid = BABYLON.Tools.RandomId();
  31327. }
  31328. return this._uid;
  31329. },
  31330. enumerable: true,
  31331. configurable: true
  31332. });
  31333. /**
  31334. * Return a string representation of the texture.
  31335. * @returns the texture as a string
  31336. */
  31337. BaseTexture.prototype.toString = function () {
  31338. return this.name;
  31339. };
  31340. /**
  31341. * Get the class name of the texture.
  31342. * @returns "BaseTexture"
  31343. */
  31344. BaseTexture.prototype.getClassName = function () {
  31345. return "BaseTexture";
  31346. };
  31347. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  31348. /**
  31349. * Callback triggered when the texture has been disposed.
  31350. * Kept for back compatibility, you can use the onDisposeObservable instead.
  31351. */
  31352. set: function (callback) {
  31353. if (this._onDisposeObserver) {
  31354. this.onDisposeObservable.remove(this._onDisposeObserver);
  31355. }
  31356. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31357. },
  31358. enumerable: true,
  31359. configurable: true
  31360. });
  31361. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  31362. /**
  31363. * Define if the texture is preventinga material to render or not.
  31364. * If not and the texture is not ready, the engine will use a default black texture instead.
  31365. */
  31366. get: function () {
  31367. return true;
  31368. },
  31369. enumerable: true,
  31370. configurable: true
  31371. });
  31372. /**
  31373. * Get the scene the texture belongs to.
  31374. * @returns the scene or null if undefined
  31375. */
  31376. BaseTexture.prototype.getScene = function () {
  31377. return this._scene;
  31378. };
  31379. /**
  31380. * Get the texture transform matrix used to offset tile the texture for istance.
  31381. * @returns the transformation matrix
  31382. */
  31383. BaseTexture.prototype.getTextureMatrix = function () {
  31384. return BABYLON.Matrix.IdentityReadOnly;
  31385. };
  31386. /**
  31387. * Get the texture reflection matrix used to rotate/transform the reflection.
  31388. * @returns the reflection matrix
  31389. */
  31390. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  31391. return BABYLON.Matrix.IdentityReadOnly;
  31392. };
  31393. /**
  31394. * Get the underlying lower level texture from Babylon.
  31395. * @returns the insternal texture
  31396. */
  31397. BaseTexture.prototype.getInternalTexture = function () {
  31398. return this._texture;
  31399. };
  31400. /**
  31401. * Get if the texture is ready to be consumed (either it is ready or it is not blocking)
  31402. * @returns true if ready or not blocking
  31403. */
  31404. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  31405. return !this.isBlocking || this.isReady();
  31406. };
  31407. /**
  31408. * Get if the texture is ready to be used (downloaded, converted, mip mapped...).
  31409. * @returns true if fully ready
  31410. */
  31411. BaseTexture.prototype.isReady = function () {
  31412. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31413. this.delayLoad();
  31414. return false;
  31415. }
  31416. if (this._texture) {
  31417. return this._texture.isReady;
  31418. }
  31419. return false;
  31420. };
  31421. /**
  31422. * Get the size of the texture.
  31423. * @returns the texture size.
  31424. */
  31425. BaseTexture.prototype.getSize = function () {
  31426. if (this._texture) {
  31427. if (this._texture.width) {
  31428. this._cachedSize.width = this._texture.width;
  31429. this._cachedSize.height = this._texture.height;
  31430. return this._cachedSize;
  31431. }
  31432. if (this._texture._size) {
  31433. this._cachedSize.width = this._texture._size;
  31434. this._cachedSize.height = this._texture._size;
  31435. return this._cachedSize;
  31436. }
  31437. }
  31438. return this._cachedSize;
  31439. };
  31440. /**
  31441. * Get the base size of the texture.
  31442. * It can be different from the size if the texture has been resized for POT for instance
  31443. * @returns the base size
  31444. */
  31445. BaseTexture.prototype.getBaseSize = function () {
  31446. if (!this.isReady() || !this._texture) {
  31447. return BABYLON.Size.Zero();
  31448. }
  31449. if (this._texture._size) {
  31450. return new BABYLON.Size(this._texture._size, this._texture._size);
  31451. }
  31452. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  31453. };
  31454. /**
  31455. * Scales the texture if is `canRescale()`
  31456. * @param ratio the resize factor we want to use to rescale
  31457. */
  31458. BaseTexture.prototype.scale = function (ratio) {
  31459. };
  31460. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  31461. /**
  31462. * Get if the texture can rescale.
  31463. */
  31464. get: function () {
  31465. return false;
  31466. },
  31467. enumerable: true,
  31468. configurable: true
  31469. });
  31470. /** @hidden */
  31471. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  31472. if (!this._scene) {
  31473. return null;
  31474. }
  31475. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  31476. for (var index = 0; index < texturesCache.length; index++) {
  31477. var texturesCacheEntry = texturesCache[index];
  31478. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  31479. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  31480. texturesCacheEntry.incrementReferences();
  31481. return texturesCacheEntry;
  31482. }
  31483. }
  31484. }
  31485. return null;
  31486. };
  31487. /** @hidden */
  31488. BaseTexture.prototype._rebuild = function () {
  31489. };
  31490. /**
  31491. * Triggers the load sequence in delayed load mode.
  31492. */
  31493. BaseTexture.prototype.delayLoad = function () {
  31494. };
  31495. /**
  31496. * Clones the texture.
  31497. * @returns the cloned texture
  31498. */
  31499. BaseTexture.prototype.clone = function () {
  31500. return null;
  31501. };
  31502. Object.defineProperty(BaseTexture.prototype, "textureType", {
  31503. /**
  31504. * Get the texture underlying type (INT, FLOAT...)
  31505. */
  31506. get: function () {
  31507. if (!this._texture) {
  31508. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31509. }
  31510. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31511. },
  31512. enumerable: true,
  31513. configurable: true
  31514. });
  31515. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  31516. /**
  31517. * Get the texture underlying format (RGB, RGBA...)
  31518. */
  31519. get: function () {
  31520. if (!this._texture) {
  31521. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31522. }
  31523. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31524. },
  31525. enumerable: true,
  31526. configurable: true
  31527. });
  31528. /**
  31529. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  31530. * This will returns an RGBA array buffer containing either in values (0-255) or
  31531. * float values (0-1) depending of the underlying buffer type.
  31532. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  31533. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  31534. * @param buffer defines a user defined buffer to fill with data (can be null)
  31535. * @returns The Array buffer containing the pixels data.
  31536. */
  31537. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  31538. if (faceIndex === void 0) { faceIndex = 0; }
  31539. if (level === void 0) { level = 0; }
  31540. if (buffer === void 0) { buffer = null; }
  31541. if (!this._texture) {
  31542. return null;
  31543. }
  31544. var size = this.getSize();
  31545. var width = size.width;
  31546. var height = size.height;
  31547. var scene = this.getScene();
  31548. if (!scene) {
  31549. return null;
  31550. }
  31551. var engine = scene.getEngine();
  31552. if (level != 0) {
  31553. width = width / Math.pow(2, level);
  31554. height = height / Math.pow(2, level);
  31555. width = Math.round(width);
  31556. height = Math.round(height);
  31557. }
  31558. if (this._texture.isCube) {
  31559. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  31560. }
  31561. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  31562. };
  31563. /**
  31564. * Release and destroy the underlying lower level texture aka internalTexture.
  31565. */
  31566. BaseTexture.prototype.releaseInternalTexture = function () {
  31567. if (this._texture) {
  31568. this._texture.dispose();
  31569. this._texture = null;
  31570. }
  31571. };
  31572. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  31573. /**
  31574. * Get the polynomial representation of the texture data.
  31575. * This is mainly use as a fast way to recover IBL Diffuse irradiance data.
  31576. * @see https://learnopengl.com/PBR/IBL/Diffuse-irradiance
  31577. */
  31578. get: function () {
  31579. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  31580. return null;
  31581. }
  31582. if (!this._texture._sphericalPolynomial) {
  31583. this._texture._sphericalPolynomial =
  31584. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  31585. }
  31586. return this._texture._sphericalPolynomial;
  31587. },
  31588. set: function (value) {
  31589. if (this._texture) {
  31590. this._texture._sphericalPolynomial = value;
  31591. }
  31592. },
  31593. enumerable: true,
  31594. configurable: true
  31595. });
  31596. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  31597. /** @hidden */
  31598. get: function () {
  31599. if (this._texture) {
  31600. return this._texture._lodTextureHigh;
  31601. }
  31602. return null;
  31603. },
  31604. enumerable: true,
  31605. configurable: true
  31606. });
  31607. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  31608. /** @hidden */
  31609. get: function () {
  31610. if (this._texture) {
  31611. return this._texture._lodTextureMid;
  31612. }
  31613. return null;
  31614. },
  31615. enumerable: true,
  31616. configurable: true
  31617. });
  31618. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  31619. /** @hidden */
  31620. get: function () {
  31621. if (this._texture) {
  31622. return this._texture._lodTextureLow;
  31623. }
  31624. return null;
  31625. },
  31626. enumerable: true,
  31627. configurable: true
  31628. });
  31629. /**
  31630. * Dispose the texture and release its associated resources.
  31631. */
  31632. BaseTexture.prototype.dispose = function () {
  31633. if (!this._scene) {
  31634. return;
  31635. }
  31636. // Animations
  31637. this._scene.stopAnimation(this);
  31638. // Remove from scene
  31639. this._scene._removePendingData(this);
  31640. var index = this._scene.textures.indexOf(this);
  31641. if (index >= 0) {
  31642. this._scene.textures.splice(index, 1);
  31643. }
  31644. this._scene.onTextureRemovedObservable.notifyObservers(this);
  31645. if (this._texture === undefined) {
  31646. return;
  31647. }
  31648. // Release
  31649. this.releaseInternalTexture();
  31650. // Callback
  31651. this.onDisposeObservable.notifyObservers(this);
  31652. this.onDisposeObservable.clear();
  31653. };
  31654. /**
  31655. * Serialize the texture into a JSON representation that can be parsed later on.
  31656. * @returns the JSON representation of the texture
  31657. */
  31658. BaseTexture.prototype.serialize = function () {
  31659. if (!this.name) {
  31660. return null;
  31661. }
  31662. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31663. // Animations
  31664. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  31665. return serializationObject;
  31666. };
  31667. /**
  31668. * Helper function to be called back once a list of texture contains only ready textures.
  31669. * @param textures Define the list of textures to wait for
  31670. * @param callback Define the callback triggered once the entire list will be ready
  31671. */
  31672. BaseTexture.WhenAllReady = function (textures, callback) {
  31673. var numRemaining = textures.length;
  31674. if (numRemaining === 0) {
  31675. callback();
  31676. return;
  31677. }
  31678. var _loop_1 = function () {
  31679. texture = textures[i];
  31680. if (texture.isReady()) {
  31681. if (--numRemaining === 0) {
  31682. callback();
  31683. }
  31684. }
  31685. else {
  31686. onLoadObservable = texture.onLoadObservable;
  31687. var onLoadCallback_1 = function () {
  31688. onLoadObservable.removeCallback(onLoadCallback_1);
  31689. if (--numRemaining === 0) {
  31690. callback();
  31691. }
  31692. };
  31693. onLoadObservable.add(onLoadCallback_1);
  31694. }
  31695. };
  31696. var texture, onLoadObservable;
  31697. for (var i = 0; i < textures.length; i++) {
  31698. _loop_1();
  31699. }
  31700. };
  31701. /**
  31702. * Default anisotropic filtering level for the application.
  31703. * It is set to 4 as a good tradeoff between perf and quality.
  31704. */
  31705. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  31706. __decorate([
  31707. BABYLON.serialize()
  31708. ], BaseTexture.prototype, "name", void 0);
  31709. __decorate([
  31710. BABYLON.serialize("hasAlpha")
  31711. ], BaseTexture.prototype, "_hasAlpha", void 0);
  31712. __decorate([
  31713. BABYLON.serialize()
  31714. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  31715. __decorate([
  31716. BABYLON.serialize()
  31717. ], BaseTexture.prototype, "level", void 0);
  31718. __decorate([
  31719. BABYLON.serialize()
  31720. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  31721. __decorate([
  31722. BABYLON.serialize("coordinatesMode")
  31723. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  31724. __decorate([
  31725. BABYLON.serialize()
  31726. ], BaseTexture.prototype, "wrapU", void 0);
  31727. __decorate([
  31728. BABYLON.serialize()
  31729. ], BaseTexture.prototype, "wrapV", void 0);
  31730. __decorate([
  31731. BABYLON.serialize()
  31732. ], BaseTexture.prototype, "wrapR", void 0);
  31733. __decorate([
  31734. BABYLON.serialize()
  31735. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  31736. __decorate([
  31737. BABYLON.serialize()
  31738. ], BaseTexture.prototype, "isCube", void 0);
  31739. __decorate([
  31740. BABYLON.serialize()
  31741. ], BaseTexture.prototype, "is3D", void 0);
  31742. __decorate([
  31743. BABYLON.serialize()
  31744. ], BaseTexture.prototype, "gammaSpace", void 0);
  31745. __decorate([
  31746. BABYLON.serialize()
  31747. ], BaseTexture.prototype, "invertZ", void 0);
  31748. __decorate([
  31749. BABYLON.serialize()
  31750. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  31751. __decorate([
  31752. BABYLON.serialize()
  31753. ], BaseTexture.prototype, "lodGenerationOffset", null);
  31754. __decorate([
  31755. BABYLON.serialize()
  31756. ], BaseTexture.prototype, "lodGenerationScale", null);
  31757. __decorate([
  31758. BABYLON.serialize()
  31759. ], BaseTexture.prototype, "isRenderTarget", void 0);
  31760. return BaseTexture;
  31761. }());
  31762. BABYLON.BaseTexture = BaseTexture;
  31763. })(BABYLON || (BABYLON = {}));
  31764. //# sourceMappingURL=baseTexture.js.map
  31765. var BABYLON;
  31766. (function (BABYLON) {
  31767. /**
  31768. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  31769. * @see http://doc.babylonjs.com/babylon101/materials#texture
  31770. */
  31771. var Texture = /** @class */ (function (_super) {
  31772. __extends(Texture, _super);
  31773. /**
  31774. * Instantiates a new texture.
  31775. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  31776. * @see http://doc.babylonjs.com/babylon101/materials#texture
  31777. * @param url define the url of the picture to load as a texture
  31778. * @param scene define the scene the texture will belong to
  31779. * @param noMipmap define if the texture will require mip maps or not
  31780. * @param invertY define if the texture needs to be inverted on the y axis during loading
  31781. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  31782. * @param onLoad define a callback triggered when the texture has been loaded
  31783. * @param onError define a callback triggered when an error occurred during the loading session
  31784. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  31785. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  31786. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  31787. */
  31788. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  31789. if (noMipmap === void 0) { noMipmap = false; }
  31790. if (invertY === void 0) { invertY = true; }
  31791. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31792. if (onLoad === void 0) { onLoad = null; }
  31793. if (onError === void 0) { onError = null; }
  31794. if (buffer === void 0) { buffer = null; }
  31795. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31796. var _this = _super.call(this, scene) || this;
  31797. /**
  31798. * Define an offset on the texture to offset the u coordinates of the UVs
  31799. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  31800. */
  31801. _this.uOffset = 0;
  31802. /**
  31803. * Define an offset on the texture to offset the v coordinates of the UVs
  31804. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  31805. */
  31806. _this.vOffset = 0;
  31807. /**
  31808. * Define an offset on the texture to scale the u coordinates of the UVs
  31809. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  31810. */
  31811. _this.uScale = 1.0;
  31812. /**
  31813. * Define an offset on the texture to scale the v coordinates of the UVs
  31814. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  31815. */
  31816. _this.vScale = 1.0;
  31817. /**
  31818. * Define an offset on the texture to rotate around the u coordinates of the UVs
  31819. * @see http://doc.babylonjs.com/how_to/more_materials
  31820. */
  31821. _this.uAng = 0;
  31822. /**
  31823. * Define an offset on the texture to rotate around the v coordinates of the UVs
  31824. * @see http://doc.babylonjs.com/how_to/more_materials
  31825. */
  31826. _this.vAng = 0;
  31827. /**
  31828. * Define an offset on the texture to rotate around the w coordinates of the UVs (in case of 3d texture)
  31829. * @see http://doc.babylonjs.com/how_to/more_materials
  31830. */
  31831. _this.wAng = 0;
  31832. /**
  31833. * Defines the center of rotation (U)
  31834. */
  31835. _this.uRotationCenter = 0.5;
  31836. /**
  31837. * Defines the center of rotation (V)
  31838. */
  31839. _this.vRotationCenter = 0.5;
  31840. /**
  31841. * Defines the center of rotation (W)
  31842. */
  31843. _this.wRotationCenter = 0.5;
  31844. /**
  31845. * Observable triggered once the texture has been loaded.
  31846. */
  31847. _this.onLoadObservable = new BABYLON.Observable();
  31848. _this._isBlocking = true;
  31849. _this.name = url || "";
  31850. _this.url = url;
  31851. _this._noMipmap = noMipmap;
  31852. _this._invertY = invertY;
  31853. _this._samplingMode = samplingMode;
  31854. _this._buffer = buffer;
  31855. _this._deleteBuffer = deleteBuffer;
  31856. if (format) {
  31857. _this._format = format;
  31858. }
  31859. scene = _this.getScene();
  31860. if (!scene) {
  31861. return _this;
  31862. }
  31863. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  31864. var load = function () {
  31865. if (_this.onLoadObservable.hasObservers()) {
  31866. _this.onLoadObservable.notifyObservers(_this);
  31867. }
  31868. if (onLoad) {
  31869. onLoad();
  31870. }
  31871. if (!_this.isBlocking && scene) {
  31872. scene.resetCachedMaterial();
  31873. }
  31874. };
  31875. if (!_this.url) {
  31876. _this._delayedOnLoad = load;
  31877. _this._delayedOnError = onError;
  31878. return _this;
  31879. }
  31880. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  31881. if (!_this._texture) {
  31882. if (!scene.useDelayedTextureLoading) {
  31883. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  31884. if (deleteBuffer) {
  31885. delete _this._buffer;
  31886. }
  31887. }
  31888. else {
  31889. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31890. _this._delayedOnLoad = load;
  31891. _this._delayedOnError = onError;
  31892. }
  31893. }
  31894. else {
  31895. if (_this._texture.isReady) {
  31896. BABYLON.Tools.SetImmediate(function () { return load(); });
  31897. }
  31898. else {
  31899. _this._texture.onLoadedObservable.add(load);
  31900. }
  31901. }
  31902. return _this;
  31903. }
  31904. Object.defineProperty(Texture.prototype, "noMipmap", {
  31905. /**
  31906. * Are mip maps generated for this texture or not.
  31907. */
  31908. get: function () {
  31909. return this._noMipmap;
  31910. },
  31911. enumerable: true,
  31912. configurable: true
  31913. });
  31914. Object.defineProperty(Texture.prototype, "isBlocking", {
  31915. get: function () {
  31916. return this._isBlocking;
  31917. },
  31918. /**
  31919. * Is the texture preventing material to render while loading.
  31920. * If false, a default texture will be used instead of the loading one during the preparation step.
  31921. */
  31922. set: function (value) {
  31923. this._isBlocking = value;
  31924. },
  31925. enumerable: true,
  31926. configurable: true
  31927. });
  31928. Object.defineProperty(Texture.prototype, "samplingMode", {
  31929. /**
  31930. * Get the current sampling mode associated with the texture.
  31931. */
  31932. get: function () {
  31933. return this._samplingMode;
  31934. },
  31935. enumerable: true,
  31936. configurable: true
  31937. });
  31938. /**
  31939. * Update the url (and optional buffer) of this texture if url was null during construction.
  31940. * @param url the url of the texture
  31941. * @param buffer the buffer of the texture (defaults to null)
  31942. */
  31943. Texture.prototype.updateURL = function (url, buffer) {
  31944. if (buffer === void 0) { buffer = null; }
  31945. if (this.url) {
  31946. throw new Error("URL is already set");
  31947. }
  31948. this.url = url;
  31949. this._buffer = buffer;
  31950. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31951. this.delayLoad();
  31952. };
  31953. /**
  31954. * Finish the loading sequence of a texture flagged as delayed load.
  31955. * @hidden
  31956. */
  31957. Texture.prototype.delayLoad = function () {
  31958. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31959. return;
  31960. }
  31961. var scene = this.getScene();
  31962. if (!scene) {
  31963. return;
  31964. }
  31965. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31966. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31967. if (!this._texture) {
  31968. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31969. if (this._deleteBuffer) {
  31970. delete this._buffer;
  31971. }
  31972. }
  31973. else {
  31974. if (this._delayedOnLoad) {
  31975. if (this._texture.isReady) {
  31976. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31977. }
  31978. else {
  31979. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31980. }
  31981. }
  31982. }
  31983. this._delayedOnLoad = null;
  31984. this._delayedOnError = null;
  31985. };
  31986. /**
  31987. * Update the sampling mode of the texture.
  31988. * Default is Trilinear mode.
  31989. *
  31990. * | Value | Type | Description |
  31991. * | ----- | ------------------ | ----------- |
  31992. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  31993. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  31994. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  31995. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  31996. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  31997. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  31998. * | 7 | NEAREST_LINEAR | |
  31999. * | 8 | NEAREST_NEAREST | |
  32000. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  32001. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  32002. * | 11 | LINEAR_LINEAR | |
  32003. * | 12 | LINEAR_NEAREST | |
  32004. *
  32005. * > _mag_: magnification filter (close to the viewer)
  32006. * > _min_: minification filter (far from the viewer)
  32007. * > _mip_: filter used between mip map levels
  32008. *@param samplingMode Define the new sampling mode of the texture
  32009. */
  32010. Texture.prototype.updateSamplingMode = function (samplingMode) {
  32011. if (!this._texture) {
  32012. return;
  32013. }
  32014. var scene = this.getScene();
  32015. if (!scene) {
  32016. return;
  32017. }
  32018. this._samplingMode = samplingMode;
  32019. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  32020. };
  32021. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  32022. x *= this.uScale;
  32023. y *= this.vScale;
  32024. x -= this.uRotationCenter * this.uScale;
  32025. y -= this.vRotationCenter * this.vScale;
  32026. z -= this.wRotationCenter;
  32027. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  32028. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  32029. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  32030. t.z += this.wRotationCenter;
  32031. };
  32032. /**
  32033. * Get the current texture matrix which includes the requested offsetting, tiling and rotation components.
  32034. * @returns the transform matrix of the texture.
  32035. */
  32036. Texture.prototype.getTextureMatrix = function () {
  32037. var _this = this;
  32038. if (this.uOffset === this._cachedUOffset &&
  32039. this.vOffset === this._cachedVOffset &&
  32040. this.uScale === this._cachedUScale &&
  32041. this.vScale === this._cachedVScale &&
  32042. this.uAng === this._cachedUAng &&
  32043. this.vAng === this._cachedVAng &&
  32044. this.wAng === this._cachedWAng) {
  32045. return this._cachedTextureMatrix;
  32046. }
  32047. this._cachedUOffset = this.uOffset;
  32048. this._cachedVOffset = this.vOffset;
  32049. this._cachedUScale = this.uScale;
  32050. this._cachedVScale = this.vScale;
  32051. this._cachedUAng = this.uAng;
  32052. this._cachedVAng = this.vAng;
  32053. this._cachedWAng = this.wAng;
  32054. if (!this._cachedTextureMatrix) {
  32055. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  32056. this._rowGenerationMatrix = new BABYLON.Matrix();
  32057. this._t0 = BABYLON.Vector3.Zero();
  32058. this._t1 = BABYLON.Vector3.Zero();
  32059. this._t2 = BABYLON.Vector3.Zero();
  32060. }
  32061. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  32062. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  32063. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  32064. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  32065. this._t1.subtractInPlace(this._t0);
  32066. this._t2.subtractInPlace(this._t0);
  32067. BABYLON.Matrix.FromValuesToRef(this._t1.x, this._t1.y, this._t1.z, 0.0, this._t2.x, this._t2.y, this._t2.z, 0.0, this._t0.x, this._t0.y, this._t0.z, 0.0, 0.0, 0.0, 0.0, 1.0, this._cachedTextureMatrix);
  32068. var scene = this.getScene();
  32069. if (!scene) {
  32070. return this._cachedTextureMatrix;
  32071. }
  32072. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  32073. return mat.hasTexture(_this);
  32074. });
  32075. return this._cachedTextureMatrix;
  32076. };
  32077. /**
  32078. * Get the current matrix used to apply reflection. This is useful to rotate an environment texture for instance.
  32079. * @returns The reflection texture transform
  32080. */
  32081. Texture.prototype.getReflectionTextureMatrix = function () {
  32082. var _this = this;
  32083. var scene = this.getScene();
  32084. if (!scene) {
  32085. return this._cachedTextureMatrix;
  32086. }
  32087. if (this.uOffset === this._cachedUOffset &&
  32088. this.vOffset === this._cachedVOffset &&
  32089. this.uScale === this._cachedUScale &&
  32090. this.vScale === this._cachedVScale &&
  32091. this.coordinatesMode === this._cachedCoordinatesMode) {
  32092. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  32093. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  32094. return this._cachedTextureMatrix;
  32095. }
  32096. }
  32097. else {
  32098. return this._cachedTextureMatrix;
  32099. }
  32100. }
  32101. if (!this._cachedTextureMatrix) {
  32102. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  32103. }
  32104. if (!this._projectionModeMatrix) {
  32105. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  32106. }
  32107. this._cachedUOffset = this.uOffset;
  32108. this._cachedVOffset = this.vOffset;
  32109. this._cachedUScale = this.uScale;
  32110. this._cachedVScale = this.vScale;
  32111. this._cachedCoordinatesMode = this.coordinatesMode;
  32112. switch (this.coordinatesMode) {
  32113. case Texture.PLANAR_MODE:
  32114. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  32115. this._cachedTextureMatrix[0] = this.uScale;
  32116. this._cachedTextureMatrix[5] = this.vScale;
  32117. this._cachedTextureMatrix[12] = this.uOffset;
  32118. this._cachedTextureMatrix[13] = this.vOffset;
  32119. break;
  32120. case Texture.PROJECTION_MODE:
  32121. BABYLON.Matrix.FromValuesToRef(0.5, 0.0, 0.0, 0.0, 0.0, -0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5, 1.0, 1.0, this._projectionModeMatrix);
  32122. var projectionMatrix = scene.getProjectionMatrix();
  32123. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  32124. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  32125. break;
  32126. default:
  32127. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  32128. break;
  32129. }
  32130. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  32131. return (mat.getActiveTextures().indexOf(_this) !== -1);
  32132. });
  32133. return this._cachedTextureMatrix;
  32134. };
  32135. /**
  32136. * Clones the texture.
  32137. * @returns the cloned texture
  32138. */
  32139. Texture.prototype.clone = function () {
  32140. var _this = this;
  32141. return BABYLON.SerializationHelper.Clone(function () {
  32142. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  32143. }, this);
  32144. };
  32145. /**
  32146. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  32147. * @returns The JSON representation of the texture
  32148. */
  32149. Texture.prototype.serialize = function () {
  32150. var serializationObject = _super.prototype.serialize.call(this);
  32151. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  32152. serializationObject.base64String = this._buffer;
  32153. serializationObject.name = serializationObject.name.replace("data:", "");
  32154. }
  32155. serializationObject.invertY = this._invertY;
  32156. serializationObject.samplingMode = this.samplingMode;
  32157. return serializationObject;
  32158. };
  32159. /**
  32160. * Get the current class name of the texture usefull for serialization or dynamic coding.
  32161. * @returns "Texture"
  32162. */
  32163. Texture.prototype.getClassName = function () {
  32164. return "Texture";
  32165. };
  32166. /**
  32167. * Dispose the texture and release its associated resources.
  32168. */
  32169. Texture.prototype.dispose = function () {
  32170. _super.prototype.dispose.call(this);
  32171. this.onLoadObservable.clear();
  32172. this._delayedOnLoad = null;
  32173. this._delayedOnError = null;
  32174. };
  32175. /**
  32176. * Parse the JSON representation of a texture in order to recreate the texture in the given scene.
  32177. * @param parsedTexture Define the JSON representation of the texture
  32178. * @param scene Define the scene the parsed texture should be instantiated in
  32179. * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies
  32180. * @returns The parsed texture if successful
  32181. */
  32182. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  32183. if (parsedTexture.customType) {
  32184. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  32185. // Update Sampling Mode
  32186. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  32187. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  32188. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  32189. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  32190. }
  32191. }
  32192. return parsedCustomTexture;
  32193. }
  32194. if (parsedTexture.isCube) {
  32195. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  32196. }
  32197. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  32198. return null;
  32199. }
  32200. var texture = BABYLON.SerializationHelper.Parse(function () {
  32201. var generateMipMaps = true;
  32202. if (parsedTexture.noMipmap) {
  32203. generateMipMaps = false;
  32204. }
  32205. if (parsedTexture.mirrorPlane) {
  32206. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  32207. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  32208. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  32209. return mirrorTexture;
  32210. }
  32211. else if (parsedTexture.isRenderTarget) {
  32212. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  32213. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  32214. return renderTargetTexture;
  32215. }
  32216. else {
  32217. var texture;
  32218. if (parsedTexture.base64String) {
  32219. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  32220. }
  32221. else {
  32222. var url = rootUrl + parsedTexture.name;
  32223. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  32224. url = parsedTexture.url;
  32225. }
  32226. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  32227. }
  32228. return texture;
  32229. }
  32230. }, parsedTexture, scene);
  32231. // Update Sampling Mode
  32232. if (parsedTexture.samplingMode) {
  32233. var sampling = parsedTexture.samplingMode;
  32234. if (texture._samplingMode !== sampling) {
  32235. texture.updateSamplingMode(sampling);
  32236. }
  32237. }
  32238. // Animations
  32239. if (parsedTexture.animations) {
  32240. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  32241. var parsedAnimation = parsedTexture.animations[animationIndex];
  32242. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32243. }
  32244. }
  32245. return texture;
  32246. };
  32247. /**
  32248. * Creates a texture from its base 64 representation.
  32249. * @param data Define the base64 payload without the data: prefix
  32250. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  32251. * @param scene Define the scene the texture should belong to
  32252. * @param noMipmap Forces the texture to not create mip map information if true
  32253. * @param invertY define if the texture needs to be inverted on the y axis during loading
  32254. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  32255. * @param onLoad define a callback triggered when the texture has been loaded
  32256. * @param onError define a callback triggered when an error occurred during the loading session
  32257. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  32258. * @returns the created texture
  32259. */
  32260. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  32261. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  32262. if (onLoad === void 0) { onLoad = null; }
  32263. if (onError === void 0) { onError = null; }
  32264. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32265. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  32266. };
  32267. /**
  32268. * Creates a texture from its data: representation. (data: will be added in case only the payload has been passed in)
  32269. * @param data Define the base64 payload without the data: prefix
  32270. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  32271. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  32272. * @param scene Define the scene the texture should belong to
  32273. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  32274. * @param noMipmap Forces the texture to not create mip map information if true
  32275. * @param invertY define if the texture needs to be inverted on the y axis during loading
  32276. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  32277. * @param onLoad define a callback triggered when the texture has been loaded
  32278. * @param onError define a callback triggered when an error occurred during the loading session
  32279. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  32280. * @returns the created texture
  32281. */
  32282. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  32283. if (deleteBuffer === void 0) { deleteBuffer = false; }
  32284. if (noMipmap === void 0) { noMipmap = false; }
  32285. if (invertY === void 0) { invertY = true; }
  32286. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  32287. if (onLoad === void 0) { onLoad = null; }
  32288. if (onError === void 0) { onError = null; }
  32289. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32290. if (name.substr(0, 5) !== "data:") {
  32291. name = "data:" + name;
  32292. }
  32293. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  32294. };
  32295. /** nearest is mag = nearest and min = nearest and mip = linear */
  32296. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  32297. /** nearest is mag = nearest and min = nearest and mip = linear */
  32298. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  32299. /** Bilinear is mag = linear and min = linear and mip = nearest */
  32300. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  32301. /** Bilinear is mag = linear and min = linear and mip = nearest */
  32302. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  32303. /** Trilinear is mag = linear and min = linear and mip = linear */
  32304. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  32305. /** Trilinear is mag = linear and min = linear and mip = linear */
  32306. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  32307. /** mag = nearest and min = nearest and mip = nearest */
  32308. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  32309. /** mag = nearest and min = linear and mip = nearest */
  32310. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  32311. /** mag = nearest and min = linear and mip = linear */
  32312. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  32313. /** mag = nearest and min = linear and mip = none */
  32314. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  32315. /** mag = nearest and min = nearest and mip = none */
  32316. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  32317. /** mag = linear and min = nearest and mip = nearest */
  32318. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  32319. /** mag = linear and min = nearest and mip = linear */
  32320. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  32321. /** mag = linear and min = linear and mip = none */
  32322. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  32323. /** mag = linear and min = nearest and mip = none */
  32324. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  32325. /** Explicit coordinates mode */
  32326. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  32327. /** Spherical coordinates mode */
  32328. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  32329. /** Planar coordinates mode */
  32330. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  32331. /** Cubic coordinates mode */
  32332. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  32333. /** Projection coordinates mode */
  32334. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  32335. /** Inverse Cubic coordinates mode */
  32336. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  32337. /** Inverse Cubic coordinates mode */
  32338. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  32339. /** Equirectangular coordinates mode */
  32340. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  32341. /** Equirectangular Fixed coordinates mode */
  32342. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  32343. /** Equirectangular Fixed Mirrored coordinates mode */
  32344. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  32345. /** Texture is not repeating outside of 0..1 UVs */
  32346. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  32347. /** Texture is repeating outside of 0..1 UVs */
  32348. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  32349. /** Texture is repeating and mirrored */
  32350. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  32351. /**
  32352. * 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
  32353. */
  32354. Texture.UseSerializedUrlIfAny = false;
  32355. __decorate([
  32356. BABYLON.serialize()
  32357. ], Texture.prototype, "url", void 0);
  32358. __decorate([
  32359. BABYLON.serialize()
  32360. ], Texture.prototype, "uOffset", void 0);
  32361. __decorate([
  32362. BABYLON.serialize()
  32363. ], Texture.prototype, "vOffset", void 0);
  32364. __decorate([
  32365. BABYLON.serialize()
  32366. ], Texture.prototype, "uScale", void 0);
  32367. __decorate([
  32368. BABYLON.serialize()
  32369. ], Texture.prototype, "vScale", void 0);
  32370. __decorate([
  32371. BABYLON.serialize()
  32372. ], Texture.prototype, "uAng", void 0);
  32373. __decorate([
  32374. BABYLON.serialize()
  32375. ], Texture.prototype, "vAng", void 0);
  32376. __decorate([
  32377. BABYLON.serialize()
  32378. ], Texture.prototype, "wAng", void 0);
  32379. __decorate([
  32380. BABYLON.serialize()
  32381. ], Texture.prototype, "uRotationCenter", void 0);
  32382. __decorate([
  32383. BABYLON.serialize()
  32384. ], Texture.prototype, "vRotationCenter", void 0);
  32385. __decorate([
  32386. BABYLON.serialize()
  32387. ], Texture.prototype, "wRotationCenter", void 0);
  32388. __decorate([
  32389. BABYLON.serialize()
  32390. ], Texture.prototype, "isBlocking", null);
  32391. return Texture;
  32392. }(BABYLON.BaseTexture));
  32393. BABYLON.Texture = Texture;
  32394. })(BABYLON || (BABYLON = {}));
  32395. //# sourceMappingURL=texture.js.map
  32396. var BABYLON;
  32397. (function (BABYLON) {
  32398. /**
  32399. * @hidden
  32400. **/
  32401. var _CreationDataStorage = /** @class */ (function () {
  32402. function _CreationDataStorage() {
  32403. }
  32404. return _CreationDataStorage;
  32405. }());
  32406. BABYLON._CreationDataStorage = _CreationDataStorage;
  32407. /**
  32408. * @hidden
  32409. **/
  32410. var _InstanceDataStorage = /** @class */ (function () {
  32411. function _InstanceDataStorage() {
  32412. this.visibleInstances = {};
  32413. this.renderIdForInstances = new Array();
  32414. this.batchCache = new _InstancesBatch();
  32415. this.instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  32416. }
  32417. return _InstanceDataStorage;
  32418. }());
  32419. /**
  32420. * @hidden
  32421. **/
  32422. var _InstancesBatch = /** @class */ (function () {
  32423. function _InstancesBatch() {
  32424. this.mustReturn = false;
  32425. this.visibleInstances = new Array();
  32426. this.renderSelf = new Array();
  32427. }
  32428. return _InstancesBatch;
  32429. }());
  32430. BABYLON._InstancesBatch = _InstancesBatch;
  32431. /**
  32432. * Class used to represent renderable models
  32433. */
  32434. var Mesh = /** @class */ (function (_super) {
  32435. __extends(Mesh, _super);
  32436. /**
  32437. * @constructor
  32438. * @param name The value used by scene.getMeshByName() to do a lookup.
  32439. * @param scene The scene to add this mesh to.
  32440. * @param parent The parent of this mesh, if it has one
  32441. * @param source An optional Mesh from which geometry is shared, cloned.
  32442. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  32443. * When false, achieved by calling a clone(), also passing False.
  32444. * This will make creation of children, recursive.
  32445. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  32446. */
  32447. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  32448. if (scene === void 0) { scene = null; }
  32449. if (parent === void 0) { parent = null; }
  32450. if (source === void 0) { source = null; }
  32451. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32452. var _this = _super.call(this, name, scene) || this;
  32453. // Members
  32454. /**
  32455. * Gets the delay loading state of the mesh (when delay loading is turned on)
  32456. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  32457. */
  32458. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32459. /**
  32460. * Gets the list of instances created from this mesh
  32461. * it is not supposed to be modified manually.
  32462. * Note also that the order of the InstancedMesh wihin the array is not significant and might change.
  32463. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32464. */
  32465. _this.instances = new Array();
  32466. _this._LODLevels = new Array();
  32467. /** @hidden */
  32468. _this._instanceDataStorage = new _InstanceDataStorage();
  32469. // Use by builder only to know what orientation were the mesh build in.
  32470. /** @hidden */
  32471. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  32472. /**
  32473. * Use this property to change the original side orientation defined at construction time
  32474. */
  32475. _this.overrideMaterialSideOrientation = null;
  32476. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  32477. // Will be used to save a source mesh reference, If any
  32478. _this._source = null;
  32479. scene = _this.getScene();
  32480. if (source) {
  32481. // Geometry
  32482. if (source._geometry) {
  32483. source._geometry.applyToMesh(_this);
  32484. }
  32485. // Deep copy
  32486. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  32487. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  32488. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  32489. ], ["_poseMatrix"]);
  32490. // Source mesh
  32491. _this._source = source;
  32492. if (scene.useClonedMeshhMap) {
  32493. if (!source.meshMap) {
  32494. source.meshMap = {};
  32495. }
  32496. source.meshMap[_this.uniqueId] = _this;
  32497. }
  32498. // Construction Params
  32499. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  32500. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  32501. _this._creationDataStorage = source._creationDataStorage;
  32502. // Animation ranges
  32503. if (_this._source._ranges) {
  32504. var ranges = _this._source._ranges;
  32505. for (var name in ranges) {
  32506. if (!ranges.hasOwnProperty(name)) {
  32507. continue;
  32508. }
  32509. if (!ranges[name]) {
  32510. continue;
  32511. }
  32512. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  32513. }
  32514. }
  32515. // Metadata
  32516. if (source.metadata && source.metadata.clone) {
  32517. _this.metadata = source.metadata.clone();
  32518. }
  32519. else {
  32520. _this.metadata = source.metadata;
  32521. }
  32522. // Tags
  32523. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  32524. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  32525. }
  32526. // Parent
  32527. _this.parent = source.parent;
  32528. // Pivot
  32529. _this.setPivotMatrix(source.getPivotMatrix());
  32530. _this.id = name + "." + source.id;
  32531. // Material
  32532. _this.material = source.material;
  32533. var index;
  32534. if (!doNotCloneChildren) {
  32535. // Children
  32536. var directDescendants = source.getDescendants(true);
  32537. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  32538. var child = directDescendants[index_1];
  32539. if (child.clone) {
  32540. child.clone(name + "." + child.name, _this);
  32541. }
  32542. }
  32543. }
  32544. // Physics clone
  32545. var physicsEngine = _this.getScene().getPhysicsEngine();
  32546. if (clonePhysicsImpostor && physicsEngine) {
  32547. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  32548. if (impostor) {
  32549. _this.physicsImpostor = impostor.clone(_this);
  32550. }
  32551. }
  32552. // Particles
  32553. for (index = 0; index < scene.particleSystems.length; index++) {
  32554. var system = scene.particleSystems[index];
  32555. if (system.emitter === source) {
  32556. system.clone(system.name, _this);
  32557. }
  32558. }
  32559. _this.refreshBoundingInfo();
  32560. _this.computeWorldMatrix(true);
  32561. }
  32562. // Parent
  32563. if (parent !== null) {
  32564. _this.parent = parent;
  32565. }
  32566. return _this;
  32567. }
  32568. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  32569. /**
  32570. * An event triggered before rendering the mesh
  32571. */
  32572. get: function () {
  32573. if (!this._onBeforeRenderObservable) {
  32574. this._onBeforeRenderObservable = new BABYLON.Observable();
  32575. }
  32576. return this._onBeforeRenderObservable;
  32577. },
  32578. enumerable: true,
  32579. configurable: true
  32580. });
  32581. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  32582. /**
  32583. * An event triggered after rendering the mesh
  32584. */
  32585. get: function () {
  32586. if (!this._onAfterRenderObservable) {
  32587. this._onAfterRenderObservable = new BABYLON.Observable();
  32588. }
  32589. return this._onAfterRenderObservable;
  32590. },
  32591. enumerable: true,
  32592. configurable: true
  32593. });
  32594. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  32595. /**
  32596. * An event triggered before drawing the mesh
  32597. */
  32598. get: function () {
  32599. if (!this._onBeforeDrawObservable) {
  32600. this._onBeforeDrawObservable = new BABYLON.Observable();
  32601. }
  32602. return this._onBeforeDrawObservable;
  32603. },
  32604. enumerable: true,
  32605. configurable: true
  32606. });
  32607. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  32608. /**
  32609. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  32610. */
  32611. set: function (callback) {
  32612. if (this._onBeforeDrawObserver) {
  32613. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  32614. }
  32615. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  32616. },
  32617. enumerable: true,
  32618. configurable: true
  32619. });
  32620. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  32621. /**
  32622. * Gets or sets the morph target manager
  32623. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  32624. */
  32625. get: function () {
  32626. return this._morphTargetManager;
  32627. },
  32628. set: function (value) {
  32629. if (this._morphTargetManager === value) {
  32630. return;
  32631. }
  32632. this._morphTargetManager = value;
  32633. this._syncGeometryWithMorphTargetManager();
  32634. },
  32635. enumerable: true,
  32636. configurable: true
  32637. });
  32638. Object.defineProperty(Mesh.prototype, "source", {
  32639. /**
  32640. * Gets the source mesh (the one used to clone this one from)
  32641. */
  32642. get: function () {
  32643. return this._source;
  32644. },
  32645. enumerable: true,
  32646. configurable: true
  32647. });
  32648. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  32649. /**
  32650. * Gets or sets a boolean indicating that this mesh does not use index buffer
  32651. */
  32652. get: function () {
  32653. return this._unIndexed;
  32654. },
  32655. set: function (value) {
  32656. if (this._unIndexed !== value) {
  32657. this._unIndexed = value;
  32658. this._markSubMeshesAsAttributesDirty();
  32659. }
  32660. },
  32661. enumerable: true,
  32662. configurable: true
  32663. });
  32664. // Methods
  32665. /**
  32666. * Gets the class name
  32667. * @returns the string "Mesh".
  32668. */
  32669. Mesh.prototype.getClassName = function () {
  32670. return "Mesh";
  32671. };
  32672. /**
  32673. * Returns a description of this mesh
  32674. * @param fullDetails define if full details about this mesh must be used
  32675. * @returns a descriptive string representing this mesh
  32676. */
  32677. Mesh.prototype.toString = function (fullDetails) {
  32678. var ret = _super.prototype.toString.call(this, fullDetails);
  32679. ret += ", n vertices: " + this.getTotalVertices();
  32680. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  32681. if (this.animations) {
  32682. for (var i = 0; i < this.animations.length; i++) {
  32683. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  32684. }
  32685. }
  32686. if (fullDetails) {
  32687. if (this._geometry) {
  32688. var ib = this.getIndices();
  32689. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32690. if (vb && ib) {
  32691. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  32692. }
  32693. }
  32694. else {
  32695. ret += ", flat shading: UNKNOWN";
  32696. }
  32697. }
  32698. return ret;
  32699. };
  32700. /** @hidden */
  32701. Mesh.prototype._unBindEffect = function () {
  32702. _super.prototype._unBindEffect.call(this);
  32703. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  32704. var instance = _a[_i];
  32705. instance._unBindEffect();
  32706. }
  32707. };
  32708. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  32709. /**
  32710. * Gets a boolean indicating if this mesh has LOD
  32711. */
  32712. get: function () {
  32713. return this._LODLevels.length > 0;
  32714. },
  32715. enumerable: true,
  32716. configurable: true
  32717. });
  32718. /**
  32719. * Gets the list of MeshLODLevel associated with the current mesh
  32720. * @returns an array of MeshLODLevel
  32721. */
  32722. Mesh.prototype.getLODLevels = function () {
  32723. return this._LODLevels;
  32724. };
  32725. Mesh.prototype._sortLODLevels = function () {
  32726. this._LODLevels.sort(function (a, b) {
  32727. if (a.distance < b.distance) {
  32728. return 1;
  32729. }
  32730. if (a.distance > b.distance) {
  32731. return -1;
  32732. }
  32733. return 0;
  32734. });
  32735. };
  32736. /**
  32737. * Add a mesh as LOD level triggered at the given distance.
  32738. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32739. * @param distance The distance from the center of the object to show this level
  32740. * @param mesh The mesh to be added as LOD level (can be null)
  32741. * @return This mesh (for chaining)
  32742. */
  32743. Mesh.prototype.addLODLevel = function (distance, mesh) {
  32744. if (mesh && mesh._masterMesh) {
  32745. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  32746. return this;
  32747. }
  32748. var level = new BABYLON.MeshLODLevel(distance, mesh);
  32749. this._LODLevels.push(level);
  32750. if (mesh) {
  32751. mesh._masterMesh = this;
  32752. }
  32753. this._sortLODLevels();
  32754. return this;
  32755. };
  32756. /**
  32757. * Returns the LOD level mesh at the passed distance or null if not found.
  32758. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32759. * @param distance The distance from the center of the object to show this level
  32760. * @returns a Mesh or `null`
  32761. */
  32762. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  32763. for (var index = 0; index < this._LODLevels.length; index++) {
  32764. var level = this._LODLevels[index];
  32765. if (level.distance === distance) {
  32766. return level.mesh;
  32767. }
  32768. }
  32769. return null;
  32770. };
  32771. /**
  32772. * Remove a mesh from the LOD array
  32773. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32774. * @param mesh defines the mesh to be removed
  32775. * @return This mesh (for chaining)
  32776. */
  32777. Mesh.prototype.removeLODLevel = function (mesh) {
  32778. for (var index = 0; index < this._LODLevels.length; index++) {
  32779. if (this._LODLevels[index].mesh === mesh) {
  32780. this._LODLevels.splice(index, 1);
  32781. if (mesh) {
  32782. mesh._masterMesh = null;
  32783. }
  32784. }
  32785. }
  32786. this._sortLODLevels();
  32787. return this;
  32788. };
  32789. /**
  32790. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  32791. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32792. * @param camera defines the camera to use to compute distance
  32793. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  32794. * @return This mesh (for chaining)
  32795. */
  32796. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  32797. if (!this._LODLevels || this._LODLevels.length === 0) {
  32798. return this;
  32799. }
  32800. var bSphere;
  32801. if (boundingSphere) {
  32802. bSphere = boundingSphere;
  32803. }
  32804. else {
  32805. var boundingInfo = this.getBoundingInfo();
  32806. bSphere = boundingInfo.boundingSphere;
  32807. }
  32808. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  32809. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  32810. if (this.onLODLevelSelection) {
  32811. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  32812. }
  32813. return this;
  32814. }
  32815. for (var index = 0; index < this._LODLevels.length; index++) {
  32816. var level = this._LODLevels[index];
  32817. if (level.distance < distanceToCamera) {
  32818. if (level.mesh) {
  32819. level.mesh._preActivate();
  32820. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  32821. }
  32822. if (this.onLODLevelSelection) {
  32823. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  32824. }
  32825. return level.mesh;
  32826. }
  32827. }
  32828. if (this.onLODLevelSelection) {
  32829. this.onLODLevelSelection(distanceToCamera, this, this);
  32830. }
  32831. return this;
  32832. };
  32833. Object.defineProperty(Mesh.prototype, "geometry", {
  32834. /**
  32835. * Gets the mesh internal Geometry object
  32836. */
  32837. get: function () {
  32838. return this._geometry;
  32839. },
  32840. enumerable: true,
  32841. configurable: true
  32842. });
  32843. /**
  32844. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  32845. * @returns the total number of vertices
  32846. */
  32847. Mesh.prototype.getTotalVertices = function () {
  32848. if (this._geometry === null || this._geometry === undefined) {
  32849. return 0;
  32850. }
  32851. return this._geometry.getTotalVertices();
  32852. };
  32853. /**
  32854. * Returns the content of an associated vertex buffer
  32855. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32856. * - BABYLON.VertexBuffer.PositionKind
  32857. * - BABYLON.VertexBuffer.UVKind
  32858. * - BABYLON.VertexBuffer.UV2Kind
  32859. * - BABYLON.VertexBuffer.UV3Kind
  32860. * - BABYLON.VertexBuffer.UV4Kind
  32861. * - BABYLON.VertexBuffer.UV5Kind
  32862. * - BABYLON.VertexBuffer.UV6Kind
  32863. * - BABYLON.VertexBuffer.ColorKind
  32864. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32865. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32866. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32867. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32868. * @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
  32869. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  32870. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  32871. */
  32872. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32873. if (!this._geometry) {
  32874. return null;
  32875. }
  32876. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  32877. };
  32878. /**
  32879. * Returns the mesh VertexBuffer object from the requested `kind`
  32880. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32881. * - BABYLON.VertexBuffer.PositionKind
  32882. * - BABYLON.VertexBuffer.UVKind
  32883. * - BABYLON.VertexBuffer.UV2Kind
  32884. * - BABYLON.VertexBuffer.UV3Kind
  32885. * - BABYLON.VertexBuffer.UV4Kind
  32886. * - BABYLON.VertexBuffer.UV5Kind
  32887. * - BABYLON.VertexBuffer.UV6Kind
  32888. * - BABYLON.VertexBuffer.ColorKind
  32889. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32890. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32891. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32892. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32893. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  32894. */
  32895. Mesh.prototype.getVertexBuffer = function (kind) {
  32896. if (!this._geometry) {
  32897. return null;
  32898. }
  32899. return this._geometry.getVertexBuffer(kind);
  32900. };
  32901. /**
  32902. * Tests if a specific vertex buffer is associated with this mesh
  32903. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32904. * - BABYLON.VertexBuffer.PositionKind
  32905. * - BABYLON.VertexBuffer.UVKind
  32906. * - BABYLON.VertexBuffer.UV2Kind
  32907. * - BABYLON.VertexBuffer.UV3Kind
  32908. * - BABYLON.VertexBuffer.UV4Kind
  32909. * - BABYLON.VertexBuffer.UV5Kind
  32910. * - BABYLON.VertexBuffer.UV6Kind
  32911. * - BABYLON.VertexBuffer.ColorKind
  32912. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32913. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32914. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32915. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32916. * @returns a boolean
  32917. */
  32918. Mesh.prototype.isVerticesDataPresent = function (kind) {
  32919. if (!this._geometry) {
  32920. if (this._delayInfo) {
  32921. return this._delayInfo.indexOf(kind) !== -1;
  32922. }
  32923. return false;
  32924. }
  32925. return this._geometry.isVerticesDataPresent(kind);
  32926. };
  32927. /**
  32928. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  32929. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32930. * - BABYLON.VertexBuffer.PositionKind
  32931. * - BABYLON.VertexBuffer.UVKind
  32932. * - BABYLON.VertexBuffer.UV2Kind
  32933. * - BABYLON.VertexBuffer.UV3Kind
  32934. * - BABYLON.VertexBuffer.UV4Kind
  32935. * - BABYLON.VertexBuffer.UV5Kind
  32936. * - BABYLON.VertexBuffer.UV6Kind
  32937. * - BABYLON.VertexBuffer.ColorKind
  32938. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32939. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32940. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32941. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32942. * @returns a boolean
  32943. */
  32944. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  32945. if (!this._geometry) {
  32946. if (this._delayInfo) {
  32947. return this._delayInfo.indexOf(kind) !== -1;
  32948. }
  32949. return false;
  32950. }
  32951. return this._geometry.isVertexBufferUpdatable(kind);
  32952. };
  32953. /**
  32954. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  32955. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32956. * - BABYLON.VertexBuffer.PositionKind
  32957. * - BABYLON.VertexBuffer.UVKind
  32958. * - BABYLON.VertexBuffer.UV2Kind
  32959. * - BABYLON.VertexBuffer.UV3Kind
  32960. * - BABYLON.VertexBuffer.UV4Kind
  32961. * - BABYLON.VertexBuffer.UV5Kind
  32962. * - BABYLON.VertexBuffer.UV6Kind
  32963. * - BABYLON.VertexBuffer.ColorKind
  32964. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32965. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32966. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32967. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32968. * @returns an array of strings
  32969. */
  32970. Mesh.prototype.getVerticesDataKinds = function () {
  32971. if (!this._geometry) {
  32972. var result = new Array();
  32973. if (this._delayInfo) {
  32974. this._delayInfo.forEach(function (kind, index, array) {
  32975. result.push(kind);
  32976. });
  32977. }
  32978. return result;
  32979. }
  32980. return this._geometry.getVerticesDataKinds();
  32981. };
  32982. /**
  32983. * Returns a positive integer : the total number of indices in this mesh geometry.
  32984. * @returns the numner of indices or zero if the mesh has no geometry.
  32985. */
  32986. Mesh.prototype.getTotalIndices = function () {
  32987. if (!this._geometry) {
  32988. return 0;
  32989. }
  32990. return this._geometry.getTotalIndices();
  32991. };
  32992. /**
  32993. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  32994. * @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.
  32995. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32996. * @returns the indices array or an empty array if the mesh has no geometry
  32997. */
  32998. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  32999. if (!this._geometry) {
  33000. return [];
  33001. }
  33002. return this._geometry.getIndices(copyWhenShared, forceCopy);
  33003. };
  33004. Object.defineProperty(Mesh.prototype, "isBlocked", {
  33005. get: function () {
  33006. return this._masterMesh !== null && this._masterMesh !== undefined;
  33007. },
  33008. enumerable: true,
  33009. configurable: true
  33010. });
  33011. /**
  33012. * Determine if the current mesh is ready to be rendered
  33013. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  33014. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  33015. * @returns true if all associated assets are ready (material, textures, shaders)
  33016. */
  33017. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  33018. if (completeCheck === void 0) { completeCheck = false; }
  33019. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  33020. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33021. return false;
  33022. }
  33023. if (!_super.prototype.isReady.call(this, completeCheck)) {
  33024. return false;
  33025. }
  33026. if (!this.subMeshes || this.subMeshes.length === 0) {
  33027. return true;
  33028. }
  33029. if (!completeCheck) {
  33030. return true;
  33031. }
  33032. var engine = this.getEngine();
  33033. var scene = this.getScene();
  33034. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  33035. this.computeWorldMatrix();
  33036. var mat = this.material || scene.defaultMaterial;
  33037. if (mat) {
  33038. if (mat._storeEffectOnSubMeshes) {
  33039. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  33040. var subMesh = _a[_i];
  33041. var effectiveMaterial = subMesh.getMaterial();
  33042. if (effectiveMaterial) {
  33043. if (effectiveMaterial._storeEffectOnSubMeshes) {
  33044. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  33045. return false;
  33046. }
  33047. }
  33048. else {
  33049. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  33050. return false;
  33051. }
  33052. }
  33053. }
  33054. }
  33055. }
  33056. else {
  33057. if (!mat.isReady(this, hardwareInstancedRendering)) {
  33058. return false;
  33059. }
  33060. }
  33061. }
  33062. // Shadows
  33063. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  33064. var light = _c[_b];
  33065. var generator = light.getShadowGenerator();
  33066. if (generator) {
  33067. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  33068. var subMesh = _e[_d];
  33069. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  33070. return false;
  33071. }
  33072. }
  33073. }
  33074. }
  33075. // LOD
  33076. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  33077. var lod = _g[_f];
  33078. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  33079. return false;
  33080. }
  33081. }
  33082. return true;
  33083. };
  33084. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  33085. /**
  33086. * 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.
  33087. */
  33088. get: function () {
  33089. return this._areNormalsFrozen;
  33090. },
  33091. enumerable: true,
  33092. configurable: true
  33093. });
  33094. /**
  33095. * 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.
  33096. * @returns the current mesh
  33097. */
  33098. Mesh.prototype.freezeNormals = function () {
  33099. this._areNormalsFrozen = true;
  33100. return this;
  33101. };
  33102. /**
  33103. * 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
  33104. * @returns the current mesh
  33105. */
  33106. Mesh.prototype.unfreezeNormals = function () {
  33107. this._areNormalsFrozen = false;
  33108. return this;
  33109. };
  33110. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  33111. /**
  33112. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  33113. */
  33114. set: function (count) {
  33115. this._instanceDataStorage.overridenInstanceCount = count;
  33116. },
  33117. enumerable: true,
  33118. configurable: true
  33119. });
  33120. // Methods
  33121. /** @hidden */
  33122. Mesh.prototype._preActivate = function () {
  33123. var sceneRenderId = this.getScene().getRenderId();
  33124. if (this._preActivateId === sceneRenderId) {
  33125. return this;
  33126. }
  33127. this._preActivateId = sceneRenderId;
  33128. this._instanceDataStorage.visibleInstances = null;
  33129. return this;
  33130. };
  33131. /** @hidden */
  33132. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  33133. if (this._instanceDataStorage.visibleInstances) {
  33134. this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
  33135. }
  33136. return this;
  33137. };
  33138. /** @hidden */
  33139. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  33140. if (!this._instanceDataStorage.visibleInstances) {
  33141. this._instanceDataStorage.visibleInstances = {
  33142. defaultRenderId: renderId,
  33143. selfDefaultRenderId: this._renderId
  33144. };
  33145. }
  33146. if (!this._instanceDataStorage.visibleInstances[renderId]) {
  33147. this._instanceDataStorage.visibleInstances[renderId] = new Array();
  33148. }
  33149. this._instanceDataStorage.visibleInstances[renderId].push(instance);
  33150. return this;
  33151. };
  33152. /**
  33153. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  33154. * This means the mesh underlying bounding box and sphere are recomputed.
  33155. * @returns the current mesh
  33156. */
  33157. Mesh.prototype.refreshBoundingInfo = function () {
  33158. return this._refreshBoundingInfo(false);
  33159. };
  33160. /** @hidden */
  33161. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  33162. if (this._boundingInfo && this._boundingInfo.isLocked) {
  33163. return this;
  33164. }
  33165. var data = this._getPositionData(applySkeleton);
  33166. if (data) {
  33167. var bias = this.geometry ? this.geometry.boundingBias : null;
  33168. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  33169. if (this._boundingInfo) {
  33170. this._boundingInfo.reConstruct(extend.minimum, extend.maximum);
  33171. }
  33172. else {
  33173. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33174. }
  33175. }
  33176. if (this.subMeshes) {
  33177. for (var index = 0; index < this.subMeshes.length; index++) {
  33178. this.subMeshes[index].refreshBoundingInfo();
  33179. }
  33180. }
  33181. this._updateBoundingInfo();
  33182. return this;
  33183. };
  33184. Mesh.prototype._getPositionData = function (applySkeleton) {
  33185. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33186. if (data && applySkeleton && this.skeleton) {
  33187. data = BABYLON.Tools.Slice(data);
  33188. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33189. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33190. if (matricesWeightsData && matricesIndicesData) {
  33191. var needExtras = this.numBoneInfluencers > 4;
  33192. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33193. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33194. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  33195. var tempVector = BABYLON.Tmp.Vector3[0];
  33196. var finalMatrix = BABYLON.Tmp.Matrix[0];
  33197. var tempMatrix = BABYLON.Tmp.Matrix[1];
  33198. var matWeightIdx = 0;
  33199. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  33200. finalMatrix.reset();
  33201. var inf;
  33202. var weight;
  33203. for (inf = 0; inf < 4; inf++) {
  33204. weight = matricesWeightsData[matWeightIdx + inf];
  33205. if (weight > 0) {
  33206. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33207. finalMatrix.addToSelf(tempMatrix);
  33208. }
  33209. }
  33210. if (needExtras) {
  33211. for (inf = 0; inf < 4; inf++) {
  33212. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33213. if (weight > 0) {
  33214. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33215. finalMatrix.addToSelf(tempMatrix);
  33216. }
  33217. }
  33218. }
  33219. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  33220. tempVector.toArray(data, index);
  33221. }
  33222. }
  33223. }
  33224. return data;
  33225. };
  33226. /** @hidden */
  33227. Mesh.prototype._createGlobalSubMesh = function (force) {
  33228. var totalVertices = this.getTotalVertices();
  33229. if (!totalVertices || !this.getIndices()) {
  33230. return null;
  33231. }
  33232. // Check if we need to recreate the submeshes
  33233. if (this.subMeshes && this.subMeshes.length > 0) {
  33234. var ib = this.getIndices();
  33235. if (!ib) {
  33236. return null;
  33237. }
  33238. var totalIndices = ib.length;
  33239. var needToRecreate = false;
  33240. if (force) {
  33241. needToRecreate = true;
  33242. }
  33243. else {
  33244. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  33245. var submesh = _a[_i];
  33246. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  33247. needToRecreate = true;
  33248. break;
  33249. }
  33250. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  33251. needToRecreate = true;
  33252. break;
  33253. }
  33254. }
  33255. }
  33256. if (!needToRecreate) {
  33257. return this.subMeshes[0];
  33258. }
  33259. }
  33260. this.releaseSubMeshes();
  33261. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  33262. };
  33263. /**
  33264. * This function will subdivide the mesh into multiple submeshes
  33265. * @param count defines the expected number of submeshes
  33266. */
  33267. Mesh.prototype.subdivide = function (count) {
  33268. if (count < 1) {
  33269. return;
  33270. }
  33271. var totalIndices = this.getTotalIndices();
  33272. var subdivisionSize = (totalIndices / count) | 0;
  33273. var offset = 0;
  33274. // Ensure that subdivisionSize is a multiple of 3
  33275. while (subdivisionSize % 3 !== 0) {
  33276. subdivisionSize++;
  33277. }
  33278. this.releaseSubMeshes();
  33279. for (var index = 0; index < count; index++) {
  33280. if (offset >= totalIndices) {
  33281. break;
  33282. }
  33283. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  33284. offset += subdivisionSize;
  33285. }
  33286. this.synchronizeInstances();
  33287. };
  33288. /**
  33289. * Copy a FloatArray into a specific associated vertex buffer
  33290. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  33291. * - BABYLON.VertexBuffer.PositionKind
  33292. * - BABYLON.VertexBuffer.UVKind
  33293. * - BABYLON.VertexBuffer.UV2Kind
  33294. * - BABYLON.VertexBuffer.UV3Kind
  33295. * - BABYLON.VertexBuffer.UV4Kind
  33296. * - BABYLON.VertexBuffer.UV5Kind
  33297. * - BABYLON.VertexBuffer.UV6Kind
  33298. * - BABYLON.VertexBuffer.ColorKind
  33299. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33300. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33301. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33302. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33303. * @param data defines the data source
  33304. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  33305. * @param stride defines the data stride size (can be null)
  33306. * @returns the current mesh
  33307. */
  33308. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  33309. if (updatable === void 0) { updatable = false; }
  33310. if (!this._geometry) {
  33311. var vertexData = new BABYLON.VertexData();
  33312. vertexData.set(data, kind);
  33313. var scene = this.getScene();
  33314. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  33315. }
  33316. else {
  33317. this._geometry.setVerticesData(kind, data, updatable, stride);
  33318. }
  33319. return this;
  33320. };
  33321. /**
  33322. * Flags an associated vertex buffer as updatable
  33323. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  33324. * - BABYLON.VertexBuffer.PositionKind
  33325. * - BABYLON.VertexBuffer.UVKind
  33326. * - BABYLON.VertexBuffer.UV2Kind
  33327. * - BABYLON.VertexBuffer.UV3Kind
  33328. * - BABYLON.VertexBuffer.UV4Kind
  33329. * - BABYLON.VertexBuffer.UV5Kind
  33330. * - BABYLON.VertexBuffer.UV6Kind
  33331. * - BABYLON.VertexBuffer.ColorKind
  33332. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33333. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33334. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33335. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33336. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  33337. */
  33338. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  33339. if (updatable === void 0) { updatable = true; }
  33340. var vb = this.getVertexBuffer(kind);
  33341. if (!vb || vb.isUpdatable() === updatable) {
  33342. return;
  33343. }
  33344. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  33345. };
  33346. /**
  33347. * Sets the mesh global Vertex Buffer
  33348. * @param buffer defines the buffer to use
  33349. * @returns the current mesh
  33350. */
  33351. Mesh.prototype.setVerticesBuffer = function (buffer) {
  33352. if (!this._geometry) {
  33353. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  33354. }
  33355. this._geometry.setVerticesBuffer(buffer);
  33356. return this;
  33357. };
  33358. /**
  33359. * Update a specific associated vertex buffer
  33360. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  33361. * - BABYLON.VertexBuffer.PositionKind
  33362. * - BABYLON.VertexBuffer.UVKind
  33363. * - BABYLON.VertexBuffer.UV2Kind
  33364. * - BABYLON.VertexBuffer.UV3Kind
  33365. * - BABYLON.VertexBuffer.UV4Kind
  33366. * - BABYLON.VertexBuffer.UV5Kind
  33367. * - BABYLON.VertexBuffer.UV6Kind
  33368. * - BABYLON.VertexBuffer.ColorKind
  33369. * - BABYLON.VertexBuffer.MatricesIndicesKind
  33370. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  33371. * - BABYLON.VertexBuffer.MatricesWeightsKind
  33372. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  33373. * @param data defines the data source
  33374. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  33375. * @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)
  33376. * @returns the current mesh
  33377. */
  33378. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  33379. if (!this._geometry) {
  33380. return this;
  33381. }
  33382. if (!makeItUnique) {
  33383. this._geometry.updateVerticesData(kind, data, updateExtends);
  33384. }
  33385. else {
  33386. this.makeGeometryUnique();
  33387. this.updateVerticesData(kind, data, updateExtends, false);
  33388. }
  33389. return this;
  33390. };
  33391. /**
  33392. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  33393. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  33394. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  33395. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  33396. * @returns the current mesh
  33397. */
  33398. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  33399. if (computeNormals === void 0) { computeNormals = true; }
  33400. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33401. if (!positions) {
  33402. return this;
  33403. }
  33404. positionFunction(positions);
  33405. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  33406. if (computeNormals) {
  33407. var indices = this.getIndices();
  33408. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33409. if (!normals) {
  33410. return this;
  33411. }
  33412. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  33413. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  33414. }
  33415. return this;
  33416. };
  33417. /**
  33418. * Creates a un-shared specific occurence of the geometry for the mesh.
  33419. * @returns the current mesh
  33420. */
  33421. Mesh.prototype.makeGeometryUnique = function () {
  33422. if (!this._geometry) {
  33423. return this;
  33424. }
  33425. var oldGeometry = this._geometry;
  33426. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  33427. oldGeometry.releaseForMesh(this, true);
  33428. geometry.applyToMesh(this);
  33429. return this;
  33430. };
  33431. /**
  33432. * Set the index buffer of this mesh
  33433. * @param indices defines the source data
  33434. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  33435. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  33436. * @returns the current mesh
  33437. */
  33438. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  33439. if (totalVertices === void 0) { totalVertices = null; }
  33440. if (updatable === void 0) { updatable = false; }
  33441. if (!this._geometry) {
  33442. var vertexData = new BABYLON.VertexData();
  33443. vertexData.indices = indices;
  33444. var scene = this.getScene();
  33445. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  33446. }
  33447. else {
  33448. this._geometry.setIndices(indices, totalVertices, updatable);
  33449. }
  33450. return this;
  33451. };
  33452. /**
  33453. * Update the current index buffer
  33454. * @param indices defines the source data
  33455. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  33456. * @returns the current mesh
  33457. */
  33458. Mesh.prototype.updateIndices = function (indices, offset) {
  33459. if (!this._geometry) {
  33460. return this;
  33461. }
  33462. this._geometry.updateIndices(indices, offset);
  33463. return this;
  33464. };
  33465. /**
  33466. * Invert the geometry to move from a right handed system to a left handed one.
  33467. * @returns the current mesh
  33468. */
  33469. Mesh.prototype.toLeftHanded = function () {
  33470. if (!this._geometry) {
  33471. return this;
  33472. }
  33473. this._geometry.toLeftHanded();
  33474. return this;
  33475. };
  33476. /** @hidden */
  33477. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  33478. if (!this._geometry) {
  33479. return this;
  33480. }
  33481. var engine = this.getScene().getEngine();
  33482. // Wireframe
  33483. var indexToBind;
  33484. if (this._unIndexed) {
  33485. indexToBind = null;
  33486. }
  33487. else {
  33488. switch (fillMode) {
  33489. case BABYLON.Material.PointFillMode:
  33490. indexToBind = null;
  33491. break;
  33492. case BABYLON.Material.WireFrameFillMode:
  33493. indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
  33494. break;
  33495. default:
  33496. case BABYLON.Material.TriangleFillMode:
  33497. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  33498. break;
  33499. }
  33500. }
  33501. // VBOs
  33502. this._geometry._bind(effect, indexToBind);
  33503. return this;
  33504. };
  33505. /** @hidden */
  33506. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  33507. if (alternate === void 0) { alternate = false; }
  33508. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33509. return this;
  33510. }
  33511. if (this._onBeforeDrawObservable) {
  33512. this._onBeforeDrawObservable.notifyObservers(this);
  33513. }
  33514. var scene = this.getScene();
  33515. var engine = scene.getEngine();
  33516. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  33517. // or triangles as points
  33518. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  33519. }
  33520. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  33521. // Triangles as wireframe
  33522. engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
  33523. }
  33524. else {
  33525. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  33526. }
  33527. if (scene._isAlternateRenderingEnabled && !alternate) {
  33528. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  33529. if (!effect || !scene.activeCamera) {
  33530. return this;
  33531. }
  33532. scene._switchToAlternateCameraConfiguration(true);
  33533. this._effectiveMaterial.bindView(effect);
  33534. this._effectiveMaterial.bindViewProjection(effect);
  33535. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  33536. this._draw(subMesh, fillMode, instancesCount, true);
  33537. engine.setViewport(scene.activeCamera.viewport);
  33538. scene._switchToAlternateCameraConfiguration(false);
  33539. this._effectiveMaterial.bindView(effect);
  33540. this._effectiveMaterial.bindViewProjection(effect);
  33541. }
  33542. return this;
  33543. };
  33544. /**
  33545. * Registers for this mesh a javascript function called just before the rendering process
  33546. * @param func defines the function to call before rendering this mesh
  33547. * @returns the current mesh
  33548. */
  33549. Mesh.prototype.registerBeforeRender = function (func) {
  33550. this.onBeforeRenderObservable.add(func);
  33551. return this;
  33552. };
  33553. /**
  33554. * Disposes a previously registered javascript function called before the rendering
  33555. * @param func defines the function to remove
  33556. * @returns the current mesh
  33557. */
  33558. Mesh.prototype.unregisterBeforeRender = function (func) {
  33559. this.onBeforeRenderObservable.removeCallback(func);
  33560. return this;
  33561. };
  33562. /**
  33563. * Registers for this mesh a javascript function called just after the rendering is complete
  33564. * @param func defines the function to call after rendering this mesh
  33565. * @returns the current mesh
  33566. */
  33567. Mesh.prototype.registerAfterRender = function (func) {
  33568. this.onAfterRenderObservable.add(func);
  33569. return this;
  33570. };
  33571. /**
  33572. * Disposes a previously registered javascript function called after the rendering.
  33573. * @param func defines the function to remove
  33574. * @returns the current mesh
  33575. */
  33576. Mesh.prototype.unregisterAfterRender = function (func) {
  33577. this.onAfterRenderObservable.removeCallback(func);
  33578. return this;
  33579. };
  33580. /** @hidden */
  33581. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  33582. var scene = this.getScene();
  33583. var batchCache = this._instanceDataStorage.batchCache;
  33584. batchCache.mustReturn = false;
  33585. batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  33586. batchCache.visibleInstances[subMeshId] = null;
  33587. if (this._instanceDataStorage.visibleInstances) {
  33588. var visibleInstances = this._instanceDataStorage.visibleInstances;
  33589. var currentRenderId = scene.getRenderId();
  33590. var defaultRenderId = (scene._isInIntermediateRendering() ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId);
  33591. batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
  33592. var selfRenderId = this._renderId;
  33593. if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  33594. batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
  33595. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  33596. selfRenderId = Math.max(visibleInstances.selfDefaultRenderId, currentRenderId);
  33597. }
  33598. var visibleInstancesForSubMesh = batchCache.visibleInstances[subMeshId];
  33599. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  33600. if (this._instanceDataStorage.renderIdForInstances[subMeshId] === currentRenderId) {
  33601. batchCache.mustReturn = true;
  33602. return batchCache;
  33603. }
  33604. if (currentRenderId !== selfRenderId) {
  33605. batchCache.renderSelf[subMeshId] = false;
  33606. }
  33607. }
  33608. this._instanceDataStorage.renderIdForInstances[subMeshId] = currentRenderId;
  33609. }
  33610. return batchCache;
  33611. };
  33612. /** @hidden */
  33613. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  33614. var visibleInstances = batch.visibleInstances[subMesh._id];
  33615. if (!visibleInstances) {
  33616. return this;
  33617. }
  33618. var matricesCount = visibleInstances.length + 1;
  33619. var bufferSize = matricesCount * 16 * 4;
  33620. var instanceStorage = this._instanceDataStorage;
  33621. var currentInstancesBufferSize = instanceStorage.instancesBufferSize;
  33622. var instancesBuffer = instanceStorage.instancesBuffer;
  33623. while (instanceStorage.instancesBufferSize < bufferSize) {
  33624. instanceStorage.instancesBufferSize *= 2;
  33625. }
  33626. if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33627. instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
  33628. }
  33629. var offset = 0;
  33630. var instancesCount = 0;
  33631. var world = this.getWorldMatrix();
  33632. if (batch.renderSelf[subMesh._id]) {
  33633. world.copyToArray(instanceStorage.instancesData, offset);
  33634. offset += 16;
  33635. instancesCount++;
  33636. }
  33637. if (visibleInstances) {
  33638. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  33639. var instance = visibleInstances[instanceIndex];
  33640. instance.getWorldMatrix().copyToArray(instanceStorage.instancesData, offset);
  33641. offset += 16;
  33642. instancesCount++;
  33643. }
  33644. }
  33645. if (!instancesBuffer || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33646. if (instancesBuffer) {
  33647. instancesBuffer.dispose();
  33648. }
  33649. instancesBuffer = new BABYLON.Buffer(engine, instanceStorage.instancesData, true, 16, false, true);
  33650. instanceStorage.instancesBuffer = instancesBuffer;
  33651. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  33652. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  33653. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  33654. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  33655. }
  33656. else {
  33657. instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
  33658. }
  33659. this._bind(subMesh, effect, fillMode);
  33660. this._draw(subMesh, fillMode, instancesCount);
  33661. engine.unbindInstanceAttributes();
  33662. return this;
  33663. };
  33664. /** @hidden */
  33665. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  33666. var scene = this.getScene();
  33667. var engine = scene.getEngine();
  33668. if (hardwareInstancedRendering) {
  33669. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  33670. }
  33671. else {
  33672. if (batch.renderSelf[subMesh._id]) {
  33673. // Draw
  33674. if (onBeforeDraw) {
  33675. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  33676. }
  33677. this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
  33678. }
  33679. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  33680. if (visibleInstancesForSubMesh) {
  33681. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  33682. var instance = visibleInstancesForSubMesh[instanceIndex];
  33683. // World
  33684. var world = instance.getWorldMatrix();
  33685. if (onBeforeDraw) {
  33686. onBeforeDraw(true, world, effectiveMaterial);
  33687. }
  33688. // Draw
  33689. this._draw(subMesh, fillMode);
  33690. }
  33691. }
  33692. }
  33693. return this;
  33694. };
  33695. /**
  33696. * 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
  33697. * @param subMesh defines the subMesh to render
  33698. * @param enableAlphaMode defines if alpha mode can be changed
  33699. * @returns the current mesh
  33700. */
  33701. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  33702. if (this._checkOcclusionQuery()) {
  33703. return this;
  33704. }
  33705. var scene = this.getScene();
  33706. // Managing instances
  33707. var batch = this._getInstancesRenderList(subMesh._id);
  33708. if (batch.mustReturn) {
  33709. return this;
  33710. }
  33711. // Checking geometry state
  33712. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33713. return this;
  33714. }
  33715. if (this._onBeforeRenderObservable) {
  33716. this._onBeforeRenderObservable.notifyObservers(this);
  33717. }
  33718. var engine = scene.getEngine();
  33719. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33720. // Material
  33721. var material = subMesh.getMaterial();
  33722. if (!material) {
  33723. return this;
  33724. }
  33725. this._effectiveMaterial = material;
  33726. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  33727. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  33728. return this;
  33729. }
  33730. }
  33731. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  33732. return this;
  33733. }
  33734. // Alpha mode
  33735. if (enableAlphaMode) {
  33736. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  33737. }
  33738. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  33739. var step = _a[_i];
  33740. step.action(this, subMesh, batch);
  33741. }
  33742. var effect;
  33743. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  33744. effect = subMesh.effect;
  33745. }
  33746. else {
  33747. effect = this._effectiveMaterial.getEffect();
  33748. }
  33749. if (!effect) {
  33750. return this;
  33751. }
  33752. var sideOrientation = this.overrideMaterialSideOrientation;
  33753. if (sideOrientation == null) {
  33754. sideOrientation = this._effectiveMaterial.sideOrientation;
  33755. if (this._getWorldMatrixDeterminant() < 0) {
  33756. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  33757. }
  33758. }
  33759. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  33760. if (this._effectiveMaterial.forceDepthWrite) {
  33761. engine.setDepthWrite(true);
  33762. }
  33763. // Bind
  33764. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  33765. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  33766. this._bind(subMesh, effect, fillMode);
  33767. }
  33768. var world = this.getWorldMatrix();
  33769. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  33770. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  33771. }
  33772. else {
  33773. this._effectiveMaterial.bind(world, this);
  33774. }
  33775. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  33776. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  33777. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33778. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  33779. }
  33780. // Draw
  33781. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33782. // Unbind
  33783. this._effectiveMaterial.unbind();
  33784. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  33785. var step = _c[_b];
  33786. step.action(this, subMesh, batch);
  33787. }
  33788. if (this._onAfterRenderObservable) {
  33789. this._onAfterRenderObservable.notifyObservers(this);
  33790. }
  33791. return this;
  33792. };
  33793. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  33794. if (isInstance && effectiveMaterial) {
  33795. effectiveMaterial.bindOnlyWorldMatrix(world);
  33796. }
  33797. };
  33798. /**
  33799. * Renormalize the mesh and patch it up if there are no weights
  33800. * Similar to normalization by adding the weights compute the reciprocal and multiply all elements, this wil ensure that everything adds to 1.
  33801. * However in the case of zero weights then we set just a single influence to 1.
  33802. * We check in the function for extra's present and if so we use the normalizeSkinWeightsWithExtras rather than the FourWeights version.
  33803. */
  33804. Mesh.prototype.cleanMatrixWeights = function () {
  33805. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33806. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33807. this.normalizeSkinWeightsAndExtra();
  33808. }
  33809. else {
  33810. this.normalizeSkinFourWeights();
  33811. }
  33812. }
  33813. };
  33814. // faster 4 weight version.
  33815. Mesh.prototype.normalizeSkinFourWeights = function () {
  33816. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33817. var numWeights = matricesWeights.length;
  33818. for (var a = 0; a < numWeights; a += 4) {
  33819. // accumulate weights
  33820. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  33821. // check for invalid weight and just set it to 1.
  33822. if (t === 0) {
  33823. matricesWeights[a] = 1;
  33824. }
  33825. else {
  33826. // renormalize so everything adds to 1 use reciprical
  33827. var recip = 1 / t;
  33828. matricesWeights[a] *= recip;
  33829. matricesWeights[a + 1] *= recip;
  33830. matricesWeights[a + 2] *= recip;
  33831. matricesWeights[a + 3] *= recip;
  33832. }
  33833. }
  33834. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33835. };
  33836. // handle special case of extra verts. (in theory gltf can handle 12 influences)
  33837. Mesh.prototype.normalizeSkinWeightsAndExtra = function () {
  33838. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33839. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33840. var numWeights = matricesWeights.length;
  33841. for (var a = 0; a < numWeights; a += 4) {
  33842. // accumulate weights
  33843. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  33844. t += matricesWeightsExtra[a] + matricesWeightsExtra[a + 1] + matricesWeightsExtra[a + 2] + matricesWeightsExtra[a + 3];
  33845. // check for invalid weight and just set it to 1.
  33846. if (t === 0) {
  33847. matricesWeights[a] = 1;
  33848. }
  33849. else {
  33850. // renormalize so everything adds to 1 use reciprical
  33851. var recip = 1 / t;
  33852. matricesWeights[a] *= recip;
  33853. matricesWeights[a + 1] *= recip;
  33854. matricesWeights[a + 2] *= recip;
  33855. matricesWeights[a + 3] *= recip;
  33856. // same goes for extras
  33857. matricesWeightsExtra[a] *= recip;
  33858. matricesWeightsExtra[a + 1] *= recip;
  33859. matricesWeightsExtra[a + 2] *= recip;
  33860. matricesWeightsExtra[a + 3] *= recip;
  33861. }
  33862. }
  33863. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33864. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsExtra);
  33865. };
  33866. /**
  33867. * ValidateSkinning is used to determine that a mesh has valid skinning data along with skin metrics, if missing weights,
  33868. * or not normalized it is returned as invalid mesh the string can be used for console logs, or on screen messages to let
  33869. * the user know there was an issue with importing the mesh
  33870. * @returns a validation object with skinned, valid and report string
  33871. */
  33872. Mesh.prototype.validateSkinning = function () {
  33873. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33874. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33875. if (matricesWeights === null || this.skeleton == null) {
  33876. return { skinned: false, valid: true, report: "not skinned" };
  33877. }
  33878. var numWeights = matricesWeights.length;
  33879. var numberNotSorted = 0;
  33880. var missingWeights = 0;
  33881. var maxUsedWeights = 0;
  33882. var numberNotNormalized = 0;
  33883. var numInfluences = matricesWeightsExtra === null ? 4 : 8;
  33884. var usedWeightCounts = new Array();
  33885. for (var a = 0; a <= numInfluences; a++) {
  33886. usedWeightCounts[a] = 0;
  33887. }
  33888. var toleranceEpsilon = 0.001;
  33889. for (var a = 0; a < numWeights; a += 4) {
  33890. var lastWeight = matricesWeights[a];
  33891. var t = lastWeight;
  33892. var usedWeights = t === 0 ? 0 : 1;
  33893. for (var b = 1; b < numInfluences; b++) {
  33894. var d = b < 4 ? matricesWeights[a + b] : matricesWeightsExtra[a + b - 4];
  33895. if (d > lastWeight) {
  33896. numberNotSorted++;
  33897. }
  33898. if (d !== 0) {
  33899. usedWeights++;
  33900. }
  33901. t += d;
  33902. lastWeight = d;
  33903. }
  33904. // count the buffer weights usage
  33905. usedWeightCounts[usedWeights]++;
  33906. // max influences
  33907. if (usedWeights > maxUsedWeights) {
  33908. maxUsedWeights = usedWeights;
  33909. }
  33910. // check for invalid weight and just set it to 1.
  33911. if (t === 0) {
  33912. missingWeights++;
  33913. }
  33914. else {
  33915. // renormalize so everything adds to 1 use reciprical
  33916. var recip = 1 / t;
  33917. var tolerance = 0;
  33918. for (b = 0; b < numInfluences; b++) {
  33919. if (b < 4) {
  33920. tolerance += Math.abs(matricesWeights[a + b] - (matricesWeights[a + b] * recip));
  33921. }
  33922. else {
  33923. tolerance += Math.abs(matricesWeightsExtra[a + b - 4] - (matricesWeightsExtra[a + b - 4] * recip));
  33924. }
  33925. }
  33926. // arbitary epsilon value for dicdating not normalized
  33927. if (tolerance > toleranceEpsilon) {
  33928. numberNotNormalized++;
  33929. }
  33930. }
  33931. }
  33932. // validate bone indices are in range of the skeleton
  33933. var numBones = this.skeleton.bones.length;
  33934. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33935. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33936. var numBadBoneIndices = 0;
  33937. for (var a = 0; a < numWeights; a++) {
  33938. for (var b = 0; b < numInfluences; b++) {
  33939. var index = b < 4 ? matricesIndices[b] : matricesIndicesExtra[b - 4];
  33940. if (index >= numBones || index < 0) {
  33941. numBadBoneIndices++;
  33942. }
  33943. }
  33944. }
  33945. // log mesh stats
  33946. var output = "Number of Weights = " + numWeights / 4 + "\nMaximum influences = " + maxUsedWeights +
  33947. "\nMissing Weights = " + missingWeights + "\nNot Sorted = " + numberNotSorted +
  33948. "\nNot Normalized = " + numberNotNormalized + "\nWeightCounts = [" + usedWeightCounts + "]" +
  33949. "\nNumber of bones = " + numBones + "\nBad Bone Indices = " + numBadBoneIndices;
  33950. return { skinned: true, valid: missingWeights === 0 && numberNotNormalized === 0 && numBadBoneIndices === 0, report: output };
  33951. };
  33952. /** @hidden */
  33953. Mesh.prototype._checkDelayState = function () {
  33954. var scene = this.getScene();
  33955. if (this._geometry) {
  33956. this._geometry.load(scene);
  33957. }
  33958. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33959. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33960. this._queueLoad(scene);
  33961. }
  33962. return this;
  33963. };
  33964. Mesh.prototype._queueLoad = function (scene) {
  33965. var _this = this;
  33966. scene._addPendingData(this);
  33967. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  33968. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  33969. if (data instanceof ArrayBuffer) {
  33970. _this._delayLoadingFunction(data, _this);
  33971. }
  33972. else {
  33973. _this._delayLoadingFunction(JSON.parse(data), _this);
  33974. }
  33975. _this.instances.forEach(function (instance) {
  33976. instance._syncSubMeshes();
  33977. });
  33978. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33979. scene._removePendingData(_this);
  33980. }, function () { }, scene.offlineProvider, getBinaryData);
  33981. return this;
  33982. };
  33983. /**
  33984. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  33985. * A mesh is in the frustum if its bounding box intersects the frustum
  33986. * @param frustumPlanes defines the frustum to test
  33987. * @returns true if the mesh is in the frustum planes
  33988. */
  33989. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  33990. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33991. return false;
  33992. }
  33993. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  33994. return false;
  33995. }
  33996. this._checkDelayState();
  33997. return true;
  33998. };
  33999. /**
  34000. * Sets the mesh material by the material or multiMaterial `id` property
  34001. * @param id is a string identifying the material or the multiMaterial
  34002. * @returns the current mesh
  34003. */
  34004. Mesh.prototype.setMaterialByID = function (id) {
  34005. var materials = this.getScene().materials;
  34006. var index;
  34007. for (index = materials.length - 1; index > -1; index--) {
  34008. if (materials[index].id === id) {
  34009. this.material = materials[index];
  34010. return this;
  34011. }
  34012. }
  34013. // Multi
  34014. var multiMaterials = this.getScene().multiMaterials;
  34015. for (index = multiMaterials.length - 1; index > -1; index--) {
  34016. if (multiMaterials[index].id === id) {
  34017. this.material = multiMaterials[index];
  34018. return this;
  34019. }
  34020. }
  34021. return this;
  34022. };
  34023. /**
  34024. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  34025. * @returns an array of IAnimatable
  34026. */
  34027. Mesh.prototype.getAnimatables = function () {
  34028. var results = new Array();
  34029. if (this.material) {
  34030. results.push(this.material);
  34031. }
  34032. if (this.skeleton) {
  34033. results.push(this.skeleton);
  34034. }
  34035. return results;
  34036. };
  34037. /**
  34038. * Modifies the mesh geometry according to the passed transformation matrix.
  34039. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  34040. * The mesh normals are modified using the same transformation.
  34041. * Note that, under the hood, this method sets a new VertexBuffer each call.
  34042. * @param transform defines the transform matrix to use
  34043. * @see http://doc.babylonjs.com/resources/baking_transformations
  34044. * @returns the current mesh
  34045. */
  34046. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  34047. // Position
  34048. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34049. return this;
  34050. }
  34051. var submeshes = this.subMeshes.splice(0);
  34052. this._resetPointsArrayCache();
  34053. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34054. var temp = new Array();
  34055. var index;
  34056. for (index = 0; index < data.length; index += 3) {
  34057. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  34058. }
  34059. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  34060. // Normals
  34061. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34062. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34063. temp = [];
  34064. for (index = 0; index < data.length; index += 3) {
  34065. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  34066. }
  34067. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  34068. }
  34069. // flip faces?
  34070. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  34071. this.flipFaces();
  34072. }
  34073. // Restore submeshes
  34074. this.releaseSubMeshes();
  34075. this.subMeshes = submeshes;
  34076. return this;
  34077. };
  34078. /**
  34079. * Modifies the mesh geometry according to its own current World Matrix.
  34080. * The mesh World Matrix is then reset.
  34081. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  34082. * Note that, under the hood, this method sets a new VertexBuffer each call.
  34083. * @see http://doc.babylonjs.com/resources/baking_transformations
  34084. * @returns the current mesh
  34085. */
  34086. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  34087. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  34088. this.scaling.copyFromFloats(1, 1, 1);
  34089. this.position.copyFromFloats(0, 0, 0);
  34090. this.rotation.copyFromFloats(0, 0, 0);
  34091. //only if quaternion is already set
  34092. if (this.rotationQuaternion) {
  34093. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  34094. }
  34095. this._worldMatrix = BABYLON.Matrix.Identity();
  34096. return this;
  34097. };
  34098. Object.defineProperty(Mesh.prototype, "_positions", {
  34099. // Cache
  34100. /** @hidden */
  34101. get: function () {
  34102. if (this._geometry) {
  34103. return this._geometry._positions;
  34104. }
  34105. return null;
  34106. },
  34107. enumerable: true,
  34108. configurable: true
  34109. });
  34110. /** @hidden */
  34111. Mesh.prototype._resetPointsArrayCache = function () {
  34112. if (this._geometry) {
  34113. this._geometry._resetPointsArrayCache();
  34114. }
  34115. return this;
  34116. };
  34117. /** @hidden */
  34118. Mesh.prototype._generatePointsArray = function () {
  34119. if (this._geometry) {
  34120. return this._geometry._generatePointsArray();
  34121. }
  34122. return false;
  34123. };
  34124. /**
  34125. * Returns a new Mesh object generated from the current mesh properties.
  34126. * This method must not get confused with createInstance()
  34127. * @param name is a string, the name given to the new mesh
  34128. * @param newParent can be any Node object (default `null`)
  34129. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  34130. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  34131. * @returns a new mesh
  34132. */
  34133. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  34134. if (name === void 0) { name = ""; }
  34135. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  34136. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  34137. };
  34138. /**
  34139. * Releases resources associated with this mesh.
  34140. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  34141. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  34142. */
  34143. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  34144. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  34145. this.morphTargetManager = null;
  34146. if (this._geometry) {
  34147. this._geometry.releaseForMesh(this, true);
  34148. }
  34149. if (this._onBeforeDrawObservable) {
  34150. this._onBeforeDrawObservable.clear();
  34151. }
  34152. if (this._onBeforeRenderObservable) {
  34153. this._onBeforeRenderObservable.clear();
  34154. }
  34155. if (this._onAfterRenderObservable) {
  34156. this._onAfterRenderObservable.clear();
  34157. }
  34158. // Sources
  34159. if (this._scene.useClonedMeshhMap) {
  34160. if (this.meshMap) {
  34161. for (var uniqueId in this.meshMap) {
  34162. var mesh = this.meshMap[uniqueId];
  34163. if (mesh) {
  34164. mesh._source = null;
  34165. this.meshMap[uniqueId] = undefined;
  34166. }
  34167. }
  34168. }
  34169. if (this._source && this._source.meshMap) {
  34170. this._source.meshMap[this.uniqueId] = undefined;
  34171. }
  34172. }
  34173. else {
  34174. var meshes = this.getScene().meshes;
  34175. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  34176. var abstractMesh = meshes_1[_i];
  34177. var mesh = abstractMesh;
  34178. if (mesh._source && mesh._source === this) {
  34179. mesh._source = null;
  34180. }
  34181. }
  34182. }
  34183. this._source = null;
  34184. // Instances
  34185. if (this._instanceDataStorage.instancesBuffer) {
  34186. this._instanceDataStorage.instancesBuffer.dispose();
  34187. this._instanceDataStorage.instancesBuffer = null;
  34188. }
  34189. while (this.instances.length) {
  34190. this.instances[0].dispose();
  34191. }
  34192. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  34193. };
  34194. /**
  34195. * Modifies the mesh geometry according to a displacement map.
  34196. * 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.
  34197. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  34198. * @param url is a string, the URL from the image file is to be downloaded.
  34199. * @param minHeight is the lower limit of the displacement.
  34200. * @param maxHeight is the upper limit of the displacement.
  34201. * @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.
  34202. * @param uvOffset is an optional vector2 used to offset UV.
  34203. * @param uvScale is an optional vector2 used to scale UV.
  34204. * @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.
  34205. * @returns the Mesh.
  34206. */
  34207. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  34208. var _this = this;
  34209. if (forceUpdate === void 0) { forceUpdate = false; }
  34210. var scene = this.getScene();
  34211. var onload = function (img) {
  34212. // Getting height map data
  34213. var canvas = document.createElement("canvas");
  34214. var context = canvas.getContext("2d");
  34215. var heightMapWidth = img.width;
  34216. var heightMapHeight = img.height;
  34217. canvas.width = heightMapWidth;
  34218. canvas.height = heightMapHeight;
  34219. context.drawImage(img, 0, 0);
  34220. // Create VertexData from map data
  34221. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  34222. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  34223. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  34224. //execute success callback, if set
  34225. if (onSuccess) {
  34226. onSuccess(_this);
  34227. }
  34228. };
  34229. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.offlineProvider);
  34230. return this;
  34231. };
  34232. /**
  34233. * Modifies the mesh geometry according to a displacementMap buffer.
  34234. * 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.
  34235. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  34236. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  34237. * @param heightMapWidth is the width of the buffer image.
  34238. * @param heightMapHeight is the height of the buffer image.
  34239. * @param minHeight is the lower limit of the displacement.
  34240. * @param maxHeight is the upper limit of the displacement.
  34241. * @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.
  34242. * @param uvOffset is an optional vector2 used to offset UV.
  34243. * @param uvScale is an optional vector2 used to scale UV.
  34244. * @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.
  34245. * @returns the Mesh.
  34246. */
  34247. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  34248. if (forceUpdate === void 0) { forceUpdate = false; }
  34249. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  34250. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  34251. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34252. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  34253. return this;
  34254. }
  34255. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  34256. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34257. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34258. var position = BABYLON.Vector3.Zero();
  34259. var normal = BABYLON.Vector3.Zero();
  34260. var uv = BABYLON.Vector2.Zero();
  34261. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  34262. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  34263. for (var index = 0; index < positions.length; index += 3) {
  34264. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  34265. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  34266. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  34267. // Compute height
  34268. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  34269. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  34270. var pos = (u + v * heightMapWidth) * 4;
  34271. var r = buffer[pos] / 255.0;
  34272. var g = buffer[pos + 1] / 255.0;
  34273. var b = buffer[pos + 2] / 255.0;
  34274. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  34275. normal.normalize();
  34276. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  34277. position = position.add(normal);
  34278. position.toArray(positions, index);
  34279. }
  34280. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  34281. if (forceUpdate) {
  34282. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  34283. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  34284. }
  34285. else {
  34286. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  34287. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  34288. }
  34289. return this;
  34290. };
  34291. /**
  34292. * Modify the mesh to get a flat shading rendering.
  34293. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  34294. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  34295. * @returns current mesh
  34296. */
  34297. Mesh.prototype.convertToFlatShadedMesh = function () {
  34298. var kinds = this.getVerticesDataKinds();
  34299. var vbs = {};
  34300. var data = {};
  34301. var newdata = {};
  34302. var updatableNormals = false;
  34303. var kindIndex;
  34304. var kind;
  34305. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34306. kind = kinds[kindIndex];
  34307. var vertexBuffer = this.getVertexBuffer(kind);
  34308. if (kind === BABYLON.VertexBuffer.NormalKind) {
  34309. updatableNormals = vertexBuffer.isUpdatable();
  34310. kinds.splice(kindIndex, 1);
  34311. kindIndex--;
  34312. continue;
  34313. }
  34314. vbs[kind] = vertexBuffer;
  34315. data[kind] = vbs[kind].getData();
  34316. newdata[kind] = [];
  34317. }
  34318. // Save previous submeshes
  34319. var previousSubmeshes = this.subMeshes.slice(0);
  34320. var indices = this.getIndices();
  34321. var totalIndices = this.getTotalIndices();
  34322. // Generating unique vertices per face
  34323. var index;
  34324. for (index = 0; index < totalIndices; index++) {
  34325. var vertexIndex = indices[index];
  34326. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34327. kind = kinds[kindIndex];
  34328. var stride = vbs[kind].getStrideSize();
  34329. for (var offset = 0; offset < stride; offset++) {
  34330. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  34331. }
  34332. }
  34333. }
  34334. // Updating faces & normal
  34335. var normals = [];
  34336. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  34337. for (index = 0; index < totalIndices; index += 3) {
  34338. indices[index] = index;
  34339. indices[index + 1] = index + 1;
  34340. indices[index + 2] = index + 2;
  34341. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  34342. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  34343. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  34344. var p1p2 = p1.subtract(p2);
  34345. var p3p2 = p3.subtract(p2);
  34346. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  34347. // Store same normals for every vertex
  34348. for (var localIndex = 0; localIndex < 3; localIndex++) {
  34349. normals.push(normal.x);
  34350. normals.push(normal.y);
  34351. normals.push(normal.z);
  34352. }
  34353. }
  34354. this.setIndices(indices);
  34355. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  34356. // Updating vertex buffers
  34357. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34358. kind = kinds[kindIndex];
  34359. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  34360. }
  34361. // Updating submeshes
  34362. this.releaseSubMeshes();
  34363. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  34364. var previousOne = previousSubmeshes[submeshIndex];
  34365. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  34366. }
  34367. this.synchronizeInstances();
  34368. return this;
  34369. };
  34370. /**
  34371. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  34372. * In other words, more vertices, no more indices and a single bigger VBO.
  34373. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  34374. * @returns current mesh
  34375. */
  34376. Mesh.prototype.convertToUnIndexedMesh = function () {
  34377. var kinds = this.getVerticesDataKinds();
  34378. var vbs = {};
  34379. var data = {};
  34380. var newdata = {};
  34381. var kindIndex;
  34382. var kind;
  34383. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34384. kind = kinds[kindIndex];
  34385. var vertexBuffer = this.getVertexBuffer(kind);
  34386. vbs[kind] = vertexBuffer;
  34387. data[kind] = vbs[kind].getData();
  34388. newdata[kind] = [];
  34389. }
  34390. // Save previous submeshes
  34391. var previousSubmeshes = this.subMeshes.slice(0);
  34392. var indices = this.getIndices();
  34393. var totalIndices = this.getTotalIndices();
  34394. // Generating unique vertices per face
  34395. var index;
  34396. for (index = 0; index < totalIndices; index++) {
  34397. var vertexIndex = indices[index];
  34398. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34399. kind = kinds[kindIndex];
  34400. var stride = vbs[kind].getStrideSize();
  34401. for (var offset = 0; offset < stride; offset++) {
  34402. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  34403. }
  34404. }
  34405. }
  34406. // Updating indices
  34407. for (index = 0; index < totalIndices; index += 3) {
  34408. indices[index] = index;
  34409. indices[index + 1] = index + 1;
  34410. indices[index + 2] = index + 2;
  34411. }
  34412. this.setIndices(indices);
  34413. // Updating vertex buffers
  34414. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34415. kind = kinds[kindIndex];
  34416. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  34417. }
  34418. // Updating submeshes
  34419. this.releaseSubMeshes();
  34420. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  34421. var previousOne = previousSubmeshes[submeshIndex];
  34422. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  34423. }
  34424. this._unIndexed = true;
  34425. this.synchronizeInstances();
  34426. return this;
  34427. };
  34428. /**
  34429. * Inverses facet orientations.
  34430. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  34431. * @param flipNormals will also inverts the normals
  34432. * @returns current mesh
  34433. */
  34434. Mesh.prototype.flipFaces = function (flipNormals) {
  34435. if (flipNormals === void 0) { flipNormals = false; }
  34436. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  34437. var i;
  34438. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  34439. for (i = 0; i < vertex_data.normals.length; i++) {
  34440. vertex_data.normals[i] *= -1;
  34441. }
  34442. }
  34443. if (vertex_data.indices) {
  34444. var temp;
  34445. for (i = 0; i < vertex_data.indices.length; i += 3) {
  34446. // reassign indices
  34447. temp = vertex_data.indices[i + 1];
  34448. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  34449. vertex_data.indices[i + 2] = temp;
  34450. }
  34451. }
  34452. vertex_data.applyToMesh(this);
  34453. return this;
  34454. };
  34455. // Instances
  34456. /**
  34457. * Creates a new InstancedMesh object from the mesh model.
  34458. * Warning : this method is not supported for Line mesh and LineSystem
  34459. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  34460. * @param name defines the name of the new instance
  34461. * @returns a new InstancedMesh
  34462. */
  34463. Mesh.prototype.createInstance = function (name) {
  34464. return new BABYLON.InstancedMesh(name, this);
  34465. };
  34466. /**
  34467. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  34468. * After this call, all the mesh instances have the same submeshes than the current mesh.
  34469. * @returns the current mesh
  34470. */
  34471. Mesh.prototype.synchronizeInstances = function () {
  34472. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  34473. var instance = this.instances[instanceIndex];
  34474. instance._syncSubMeshes();
  34475. }
  34476. return this;
  34477. };
  34478. /**
  34479. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  34480. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  34481. * This should be used together with the simplification to avoid disappearing triangles.
  34482. * @param successCallback an optional success callback to be called after the optimization finished.
  34483. * @returns the current mesh
  34484. */
  34485. Mesh.prototype.optimizeIndices = function (successCallback) {
  34486. var _this = this;
  34487. var indices = this.getIndices();
  34488. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34489. if (!positions || !indices) {
  34490. return this;
  34491. }
  34492. var vectorPositions = new Array();
  34493. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  34494. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  34495. }
  34496. var dupes = new Array();
  34497. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  34498. var realPos = vectorPositions.length - 1 - iteration;
  34499. var testedPosition = vectorPositions[realPos];
  34500. for (var j = 0; j < realPos; ++j) {
  34501. var againstPosition = vectorPositions[j];
  34502. if (testedPosition.equals(againstPosition)) {
  34503. dupes[realPos] = j;
  34504. break;
  34505. }
  34506. }
  34507. }, function () {
  34508. for (var i = 0; i < indices.length; ++i) {
  34509. indices[i] = dupes[indices[i]] || indices[i];
  34510. }
  34511. //indices are now reordered
  34512. var originalSubMeshes = _this.subMeshes.slice(0);
  34513. _this.setIndices(indices);
  34514. _this.subMeshes = originalSubMeshes;
  34515. if (successCallback) {
  34516. successCallback(_this);
  34517. }
  34518. });
  34519. return this;
  34520. };
  34521. /**
  34522. * Serialize current mesh
  34523. * @param serializationObject defines the object which will receive the serialization data
  34524. */
  34525. Mesh.prototype.serialize = function (serializationObject) {
  34526. serializationObject.name = this.name;
  34527. serializationObject.id = this.id;
  34528. serializationObject.type = this.getClassName();
  34529. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34530. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34531. }
  34532. serializationObject.position = this.position.asArray();
  34533. if (this.rotationQuaternion) {
  34534. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  34535. }
  34536. else if (this.rotation) {
  34537. serializationObject.rotation = this.rotation.asArray();
  34538. }
  34539. serializationObject.scaling = this.scaling.asArray();
  34540. if (this._postMultiplyPivotMatrix) {
  34541. serializationObject.pivotMatrix = this.getPivotMatrix().asArray();
  34542. }
  34543. else {
  34544. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  34545. }
  34546. serializationObject.isEnabled = this.isEnabled(false);
  34547. serializationObject.isVisible = this.isVisible;
  34548. serializationObject.infiniteDistance = this.infiniteDistance;
  34549. serializationObject.pickable = this.isPickable;
  34550. serializationObject.receiveShadows = this.receiveShadows;
  34551. serializationObject.billboardMode = this.billboardMode;
  34552. serializationObject.visibility = this.visibility;
  34553. serializationObject.checkCollisions = this.checkCollisions;
  34554. serializationObject.isBlocker = this.isBlocker;
  34555. // Parent
  34556. if (this.parent) {
  34557. serializationObject.parentId = this.parent.id;
  34558. }
  34559. // Geometry
  34560. serializationObject.isUnIndexed = this.isUnIndexed;
  34561. var geometry = this._geometry;
  34562. if (geometry) {
  34563. var geometryId = geometry.id;
  34564. serializationObject.geometryId = geometryId;
  34565. // SubMeshes
  34566. serializationObject.subMeshes = [];
  34567. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  34568. var subMesh = this.subMeshes[subIndex];
  34569. serializationObject.subMeshes.push({
  34570. materialIndex: subMesh.materialIndex,
  34571. verticesStart: subMesh.verticesStart,
  34572. verticesCount: subMesh.verticesCount,
  34573. indexStart: subMesh.indexStart,
  34574. indexCount: subMesh.indexCount
  34575. });
  34576. }
  34577. }
  34578. // Material
  34579. if (this.material) {
  34580. serializationObject.materialId = this.material.id;
  34581. }
  34582. else {
  34583. this.material = null;
  34584. }
  34585. // Morph targets
  34586. if (this.morphTargetManager) {
  34587. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  34588. }
  34589. // Skeleton
  34590. if (this.skeleton) {
  34591. serializationObject.skeletonId = this.skeleton.id;
  34592. }
  34593. // Physics
  34594. //TODO implement correct serialization for physics impostors.
  34595. var impostor = this.getPhysicsImpostor();
  34596. if (impostor) {
  34597. serializationObject.physicsMass = impostor.getParam("mass");
  34598. serializationObject.physicsFriction = impostor.getParam("friction");
  34599. serializationObject.physicsRestitution = impostor.getParam("mass");
  34600. serializationObject.physicsImpostor = impostor.type;
  34601. }
  34602. // Metadata
  34603. if (this.metadata) {
  34604. serializationObject.metadata = this.metadata;
  34605. }
  34606. // Instances
  34607. serializationObject.instances = [];
  34608. for (var index = 0; index < this.instances.length; index++) {
  34609. var instance = this.instances[index];
  34610. if (instance.doNotSerialize) {
  34611. continue;
  34612. }
  34613. var serializationInstance = {
  34614. name: instance.name,
  34615. id: instance.id,
  34616. position: instance.position.asArray(),
  34617. scaling: instance.scaling.asArray()
  34618. };
  34619. if (instance.parent) {
  34620. serializationInstance.parentId = instance.parent.id;
  34621. }
  34622. if (instance.rotationQuaternion) {
  34623. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  34624. }
  34625. else if (instance.rotation) {
  34626. serializationInstance.rotation = instance.rotation.asArray();
  34627. }
  34628. serializationObject.instances.push(serializationInstance);
  34629. // Animations
  34630. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  34631. serializationInstance.ranges = instance.serializeAnimationRanges();
  34632. }
  34633. //
  34634. // Animations
  34635. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  34636. serializationObject.ranges = this.serializeAnimationRanges();
  34637. // Layer mask
  34638. serializationObject.layerMask = this.layerMask;
  34639. // Alpha
  34640. serializationObject.alphaIndex = this.alphaIndex;
  34641. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  34642. // Overlay
  34643. serializationObject.overlayAlpha = this.overlayAlpha;
  34644. serializationObject.overlayColor = this.overlayColor.asArray();
  34645. serializationObject.renderOverlay = this.renderOverlay;
  34646. // Fog
  34647. serializationObject.applyFog = this.applyFog;
  34648. // Action Manager
  34649. if (this.actionManager) {
  34650. serializationObject.actions = this.actionManager.serialize(this.name);
  34651. }
  34652. };
  34653. /** @hidden */
  34654. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  34655. if (!this.geometry) {
  34656. return;
  34657. }
  34658. this._markSubMeshesAsAttributesDirty();
  34659. var morphTargetManager = this._morphTargetManager;
  34660. if (morphTargetManager && morphTargetManager.vertexCount) {
  34661. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  34662. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  34663. this.morphTargetManager = null;
  34664. return;
  34665. }
  34666. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  34667. var morphTarget = morphTargetManager.getActiveTarget(index);
  34668. var positions = morphTarget.getPositions();
  34669. if (!positions) {
  34670. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  34671. return;
  34672. }
  34673. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  34674. var normals = morphTarget.getNormals();
  34675. if (normals) {
  34676. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  34677. }
  34678. var tangents = morphTarget.getTangents();
  34679. if (tangents) {
  34680. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  34681. }
  34682. }
  34683. }
  34684. else {
  34685. var index = 0;
  34686. // Positions
  34687. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  34688. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  34689. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  34690. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  34691. }
  34692. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  34693. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  34694. }
  34695. index++;
  34696. }
  34697. }
  34698. };
  34699. // Statics
  34700. /**
  34701. * Returns a new Mesh object parsed from the source provided.
  34702. * @param parsedMesh is the source
  34703. * @param scene defines the hosting scene
  34704. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  34705. * @returns a new Mesh
  34706. */
  34707. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  34708. var mesh;
  34709. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  34710. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  34711. }
  34712. else {
  34713. mesh = new Mesh(parsedMesh.name, scene);
  34714. }
  34715. mesh.id = parsedMesh.id;
  34716. if (BABYLON.Tags) {
  34717. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  34718. }
  34719. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  34720. if (parsedMesh.metadata !== undefined) {
  34721. mesh.metadata = parsedMesh.metadata;
  34722. }
  34723. if (parsedMesh.rotationQuaternion) {
  34724. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  34725. }
  34726. else if (parsedMesh.rotation) {
  34727. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  34728. }
  34729. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  34730. if (parsedMesh.localMatrix) {
  34731. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  34732. }
  34733. else if (parsedMesh.pivotMatrix) {
  34734. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  34735. }
  34736. mesh.setEnabled(parsedMesh.isEnabled);
  34737. mesh.isVisible = parsedMesh.isVisible;
  34738. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  34739. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  34740. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  34741. if (parsedMesh.applyFog !== undefined) {
  34742. mesh.applyFog = parsedMesh.applyFog;
  34743. }
  34744. if (parsedMesh.pickable !== undefined) {
  34745. mesh.isPickable = parsedMesh.pickable;
  34746. }
  34747. if (parsedMesh.alphaIndex !== undefined) {
  34748. mesh.alphaIndex = parsedMesh.alphaIndex;
  34749. }
  34750. mesh.receiveShadows = parsedMesh.receiveShadows;
  34751. mesh.billboardMode = parsedMesh.billboardMode;
  34752. if (parsedMesh.visibility !== undefined) {
  34753. mesh.visibility = parsedMesh.visibility;
  34754. }
  34755. mesh.checkCollisions = parsedMesh.checkCollisions;
  34756. if (parsedMesh.isBlocker !== undefined) {
  34757. mesh.isBlocker = parsedMesh.isBlocker;
  34758. }
  34759. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  34760. // freezeWorldMatrix
  34761. if (parsedMesh.freezeWorldMatrix) {
  34762. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  34763. }
  34764. // Parent
  34765. if (parsedMesh.parentId) {
  34766. mesh._waitingParentId = parsedMesh.parentId;
  34767. }
  34768. // Actions
  34769. if (parsedMesh.actions !== undefined) {
  34770. mesh._waitingActions = parsedMesh.actions;
  34771. }
  34772. // Overlay
  34773. if (parsedMesh.overlayAlpha !== undefined) {
  34774. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  34775. }
  34776. if (parsedMesh.overlayColor !== undefined) {
  34777. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  34778. }
  34779. if (parsedMesh.renderOverlay !== undefined) {
  34780. mesh.renderOverlay = parsedMesh.renderOverlay;
  34781. }
  34782. // Geometry
  34783. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  34784. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  34785. if (parsedMesh.delayLoadingFile) {
  34786. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34787. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  34788. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  34789. if (parsedMesh._binaryInfo) {
  34790. mesh._binaryInfo = parsedMesh._binaryInfo;
  34791. }
  34792. mesh._delayInfo = [];
  34793. if (parsedMesh.hasUVs) {
  34794. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  34795. }
  34796. if (parsedMesh.hasUVs2) {
  34797. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  34798. }
  34799. if (parsedMesh.hasUVs3) {
  34800. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  34801. }
  34802. if (parsedMesh.hasUVs4) {
  34803. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  34804. }
  34805. if (parsedMesh.hasUVs5) {
  34806. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  34807. }
  34808. if (parsedMesh.hasUVs6) {
  34809. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  34810. }
  34811. if (parsedMesh.hasColors) {
  34812. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  34813. }
  34814. if (parsedMesh.hasMatricesIndices) {
  34815. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34816. }
  34817. if (parsedMesh.hasMatricesWeights) {
  34818. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34819. }
  34820. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  34821. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  34822. mesh._checkDelayState();
  34823. }
  34824. }
  34825. else {
  34826. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  34827. }
  34828. // Material
  34829. if (parsedMesh.materialId) {
  34830. mesh.setMaterialByID(parsedMesh.materialId);
  34831. }
  34832. else {
  34833. mesh.material = null;
  34834. }
  34835. // Morph targets
  34836. if (parsedMesh.morphTargetManagerId > -1) {
  34837. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  34838. }
  34839. // Skeleton
  34840. if (parsedMesh.skeletonId > -1) {
  34841. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  34842. if (parsedMesh.numBoneInfluencers) {
  34843. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  34844. }
  34845. }
  34846. // Animations
  34847. if (parsedMesh.animations) {
  34848. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  34849. var parsedAnimation = parsedMesh.animations[animationIndex];
  34850. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34851. }
  34852. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  34853. }
  34854. if (parsedMesh.autoAnimate) {
  34855. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  34856. }
  34857. // Layer Mask
  34858. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  34859. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  34860. }
  34861. else {
  34862. mesh.layerMask = 0x0FFFFFFF;
  34863. }
  34864. // Physics
  34865. if (parsedMesh.physicsImpostor) {
  34866. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  34867. mass: parsedMesh.physicsMass,
  34868. friction: parsedMesh.physicsFriction,
  34869. restitution: parsedMesh.physicsRestitution
  34870. }, scene);
  34871. }
  34872. // Instances
  34873. if (parsedMesh.instances) {
  34874. for (var index = 0; index < parsedMesh.instances.length; index++) {
  34875. var parsedInstance = parsedMesh.instances[index];
  34876. var instance = mesh.createInstance(parsedInstance.name);
  34877. if (parsedInstance.id) {
  34878. instance.id = parsedInstance.id;
  34879. }
  34880. if (BABYLON.Tags) {
  34881. if (parsedInstance.tags) {
  34882. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  34883. }
  34884. else {
  34885. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  34886. }
  34887. }
  34888. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  34889. if (parsedInstance.parentId) {
  34890. instance._waitingParentId = parsedInstance.parentId;
  34891. }
  34892. if (parsedInstance.rotationQuaternion) {
  34893. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  34894. }
  34895. else if (parsedInstance.rotation) {
  34896. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  34897. }
  34898. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  34899. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  34900. instance.checkCollisions = parsedInstance.checkCollisions;
  34901. }
  34902. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  34903. instance.isPickable = parsedInstance.pickable;
  34904. }
  34905. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  34906. instance.showBoundingBox = parsedInstance.showBoundingBox;
  34907. }
  34908. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34909. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  34910. }
  34911. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34912. instance.alphaIndex = parsedInstance.alphaIndex;
  34913. }
  34914. // Physics
  34915. if (parsedInstance.physicsImpostor) {
  34916. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  34917. mass: parsedInstance.physicsMass,
  34918. friction: parsedInstance.physicsFriction,
  34919. restitution: parsedInstance.physicsRestitution
  34920. }, scene);
  34921. }
  34922. // Animation
  34923. if (parsedInstance.animations) {
  34924. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  34925. parsedAnimation = parsedInstance.animations[animationIndex];
  34926. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34927. }
  34928. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  34929. if (parsedInstance.autoAnimate) {
  34930. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  34931. }
  34932. }
  34933. }
  34934. }
  34935. return mesh;
  34936. };
  34937. /**
  34938. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  34939. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34940. * @param name defines the name of the mesh to create
  34941. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  34942. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  34943. * @param closePath creates a seam between the first and the last points of each path of the path array
  34944. * @param offset is taken in account only if the `pathArray` is containing a single path
  34945. * @param scene defines the hosting scene
  34946. * @param updatable defines if the mesh must be flagged as updatable
  34947. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34948. * @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)
  34949. * @returns a new Mesh
  34950. */
  34951. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  34952. if (closeArray === void 0) { closeArray = false; }
  34953. if (updatable === void 0) { updatable = false; }
  34954. return BABYLON.MeshBuilder.CreateRibbon(name, {
  34955. pathArray: pathArray,
  34956. closeArray: closeArray,
  34957. closePath: closePath,
  34958. offset: offset,
  34959. updatable: updatable,
  34960. sideOrientation: sideOrientation,
  34961. instance: instance
  34962. }, scene);
  34963. };
  34964. /**
  34965. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  34966. * @param name defines the name of the mesh to create
  34967. * @param radius sets the radius size (float) of the polygon (default 0.5)
  34968. * @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
  34969. * @param scene defines the hosting scene
  34970. * @param updatable defines if the mesh must be flagged as updatable
  34971. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34972. * @returns a new Mesh
  34973. */
  34974. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  34975. if (scene === void 0) { scene = null; }
  34976. var options = {
  34977. radius: radius,
  34978. tessellation: tessellation,
  34979. sideOrientation: sideOrientation,
  34980. updatable: updatable
  34981. };
  34982. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  34983. };
  34984. /**
  34985. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  34986. * @param name defines the name of the mesh to create
  34987. * @param size sets the size (float) of each box side (default 1)
  34988. * @param scene defines the hosting scene
  34989. * @param updatable defines if the mesh must be flagged as updatable
  34990. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34991. * @returns a new Mesh
  34992. */
  34993. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  34994. if (scene === void 0) { scene = null; }
  34995. var options = {
  34996. size: size,
  34997. sideOrientation: sideOrientation,
  34998. updatable: updatable
  34999. };
  35000. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  35001. };
  35002. /**
  35003. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  35004. * @param name defines the name of the mesh to create
  35005. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  35006. * @param diameter sets the diameter size (float) of the sphere (default 1)
  35007. * @param scene defines the hosting scene
  35008. * @param updatable defines if the mesh must be flagged as updatable
  35009. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35010. * @returns a new Mesh
  35011. */
  35012. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  35013. var options = {
  35014. segments: segments,
  35015. diameterX: diameter,
  35016. diameterY: diameter,
  35017. diameterZ: diameter,
  35018. sideOrientation: sideOrientation,
  35019. updatable: updatable
  35020. };
  35021. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  35022. };
  35023. /**
  35024. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  35025. * @param name defines the name of the mesh to create
  35026. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  35027. * @param diameterTop set the top cap diameter (floats, default 1)
  35028. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  35029. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  35030. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  35031. * @param scene defines the hosting scene
  35032. * @param updatable defines if the mesh must be flagged as updatable
  35033. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35034. * @returns a new Mesh
  35035. */
  35036. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  35037. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  35038. if (scene !== undefined) {
  35039. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  35040. updatable = scene;
  35041. }
  35042. scene = subdivisions;
  35043. subdivisions = 1;
  35044. }
  35045. var options = {
  35046. height: height,
  35047. diameterTop: diameterTop,
  35048. diameterBottom: diameterBottom,
  35049. tessellation: tessellation,
  35050. subdivisions: subdivisions,
  35051. sideOrientation: sideOrientation,
  35052. updatable: updatable
  35053. };
  35054. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  35055. };
  35056. // Torus (Code from SharpDX.org)
  35057. /**
  35058. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  35059. * @param name defines the name of the mesh to create
  35060. * @param diameter sets the diameter size (float) of the torus (default 1)
  35061. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  35062. * @param tessellation sets the number of torus sides (postive integer, default 16)
  35063. * @param scene defines the hosting scene
  35064. * @param updatable defines if the mesh must be flagged as updatable
  35065. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35066. * @returns a new Mesh
  35067. */
  35068. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  35069. var options = {
  35070. diameter: diameter,
  35071. thickness: thickness,
  35072. tessellation: tessellation,
  35073. sideOrientation: sideOrientation,
  35074. updatable: updatable
  35075. };
  35076. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  35077. };
  35078. /**
  35079. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  35080. * @param name defines the name of the mesh to create
  35081. * @param radius sets the global radius size (float) of the torus knot (default 2)
  35082. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  35083. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  35084. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  35085. * @param p the number of windings on X axis (positive integers, default 2)
  35086. * @param q the number of windings on Y axis (positive integers, default 3)
  35087. * @param scene defines the hosting scene
  35088. * @param updatable defines if the mesh must be flagged as updatable
  35089. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35090. * @returns a new Mesh
  35091. */
  35092. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  35093. var options = {
  35094. radius: radius,
  35095. tube: tube,
  35096. radialSegments: radialSegments,
  35097. tubularSegments: tubularSegments,
  35098. p: p,
  35099. q: q,
  35100. sideOrientation: sideOrientation,
  35101. updatable: updatable
  35102. };
  35103. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  35104. };
  35105. /**
  35106. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  35107. * @param name defines the name of the mesh to create
  35108. * @param points is an array successive Vector3
  35109. * @param scene defines the hosting scene
  35110. * @param updatable defines if the mesh must be flagged as updatable
  35111. * @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).
  35112. * @returns a new Mesh
  35113. */
  35114. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  35115. if (scene === void 0) { scene = null; }
  35116. if (updatable === void 0) { updatable = false; }
  35117. if (instance === void 0) { instance = null; }
  35118. var options = {
  35119. points: points,
  35120. updatable: updatable,
  35121. instance: instance
  35122. };
  35123. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  35124. };
  35125. /**
  35126. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  35127. * @param name defines the name of the mesh to create
  35128. * @param points is an array successive Vector3
  35129. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  35130. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  35131. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  35132. * @param scene defines the hosting scene
  35133. * @param updatable defines if the mesh must be flagged as updatable
  35134. * @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)
  35135. * @returns a new Mesh
  35136. */
  35137. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  35138. if (scene === void 0) { scene = null; }
  35139. var options = {
  35140. points: points,
  35141. dashSize: dashSize,
  35142. gapSize: gapSize,
  35143. dashNb: dashNb,
  35144. updatable: updatable,
  35145. instance: instance
  35146. };
  35147. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  35148. };
  35149. /**
  35150. * Creates a polygon mesh.
  35151. * Please consider using the same method from the MeshBuilder class instead.
  35152. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  35153. * 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.
  35154. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35155. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  35156. * Remember you can only change the shape positions, not their number when updating a polygon.
  35157. */
  35158. /**
  35159. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  35160. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  35161. * @param name defines the name of the mesh to create
  35162. * @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
  35163. * @param scene defines the hosting scene
  35164. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  35165. * @param updatable defines if the mesh must be flagged as updatable
  35166. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35167. * @returns a new Mesh
  35168. */
  35169. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  35170. var options = {
  35171. shape: shape,
  35172. holes: holes,
  35173. updatable: updatable,
  35174. sideOrientation: sideOrientation
  35175. };
  35176. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  35177. };
  35178. /**
  35179. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  35180. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  35181. * @param name defines the name of the mesh to create
  35182. * @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
  35183. * @param depth defines the height of extrusion
  35184. * @param scene defines the hosting scene
  35185. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  35186. * @param updatable defines if the mesh must be flagged as updatable
  35187. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35188. * @returns a new Mesh
  35189. */
  35190. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  35191. var options = {
  35192. shape: shape,
  35193. holes: holes,
  35194. depth: depth,
  35195. updatable: updatable,
  35196. sideOrientation: sideOrientation
  35197. };
  35198. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  35199. };
  35200. /**
  35201. * Creates an extruded shape mesh.
  35202. * 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
  35203. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  35204. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  35205. * @param name defines the name of the mesh to create
  35206. * @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
  35207. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  35208. * @param scale is the value to scale the shape
  35209. * @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
  35210. * @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
  35211. * @param scene defines the hosting scene
  35212. * @param updatable defines if the mesh must be flagged as updatable
  35213. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35214. * @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)
  35215. * @returns a new Mesh
  35216. */
  35217. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  35218. if (scene === void 0) { scene = null; }
  35219. var options = {
  35220. shape: shape,
  35221. path: path,
  35222. scale: scale,
  35223. rotation: rotation,
  35224. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  35225. sideOrientation: sideOrientation,
  35226. instance: instance,
  35227. updatable: updatable
  35228. };
  35229. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  35230. };
  35231. /**
  35232. * Creates an custom extruded shape mesh.
  35233. * The custom extrusion is a parametric shape.
  35234. * It has no predefined shape. Its final shape will depend on the input parameters.
  35235. * Please consider using the same method from the MeshBuilder class instead
  35236. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  35237. * @param name defines the name of the mesh to create
  35238. * @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
  35239. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  35240. * @param scaleFunction is a custom Javascript function called on each path point
  35241. * @param rotationFunction is a custom Javascript function called on each path point
  35242. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  35243. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  35244. * @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
  35245. * @param scene defines the hosting scene
  35246. * @param updatable defines if the mesh must be flagged as updatable
  35247. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35248. * @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)
  35249. * @returns a new Mesh
  35250. */
  35251. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  35252. var options = {
  35253. shape: shape,
  35254. path: path,
  35255. scaleFunction: scaleFunction,
  35256. rotationFunction: rotationFunction,
  35257. ribbonCloseArray: ribbonCloseArray,
  35258. ribbonClosePath: ribbonClosePath,
  35259. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  35260. sideOrientation: sideOrientation,
  35261. instance: instance,
  35262. updatable: updatable
  35263. };
  35264. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  35265. };
  35266. /**
  35267. * Creates lathe mesh.
  35268. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  35269. * Please consider using the same method from the MeshBuilder class instead
  35270. * @param name defines the name of the mesh to create
  35271. * @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
  35272. * @param radius is the radius value of the lathe
  35273. * @param tessellation is the side number of the lathe.
  35274. * @param scene defines the hosting scene
  35275. * @param updatable defines if the mesh must be flagged as updatable
  35276. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35277. * @returns a new Mesh
  35278. */
  35279. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  35280. var options = {
  35281. shape: shape,
  35282. radius: radius,
  35283. tessellation: tessellation,
  35284. sideOrientation: sideOrientation,
  35285. updatable: updatable
  35286. };
  35287. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  35288. };
  35289. /**
  35290. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  35291. * @param name defines the name of the mesh to create
  35292. * @param size sets the size (float) of both sides of the plane at once (default 1)
  35293. * @param scene defines the hosting scene
  35294. * @param updatable defines if the mesh must be flagged as updatable
  35295. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35296. * @returns a new Mesh
  35297. */
  35298. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  35299. var options = {
  35300. size: size,
  35301. width: size,
  35302. height: size,
  35303. sideOrientation: sideOrientation,
  35304. updatable: updatable
  35305. };
  35306. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  35307. };
  35308. /**
  35309. * Creates a ground mesh.
  35310. * Please consider using the same method from the MeshBuilder class instead
  35311. * @param name defines the name of the mesh to create
  35312. * @param width set the width of the ground
  35313. * @param height set the height of the ground
  35314. * @param subdivisions sets the number of subdivisions per side
  35315. * @param scene defines the hosting scene
  35316. * @param updatable defines if the mesh must be flagged as updatable
  35317. * @returns a new Mesh
  35318. */
  35319. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  35320. var options = {
  35321. width: width,
  35322. height: height,
  35323. subdivisions: subdivisions,
  35324. updatable: updatable
  35325. };
  35326. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  35327. };
  35328. /**
  35329. * Creates a tiled ground mesh.
  35330. * Please consider using the same method from the MeshBuilder class instead
  35331. * @param name defines the name of the mesh to create
  35332. * @param xmin set the ground minimum X coordinate
  35333. * @param zmin set the ground minimum Y coordinate
  35334. * @param xmax set the ground maximum X coordinate
  35335. * @param zmax set the ground maximum Z coordinate
  35336. * @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
  35337. * @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
  35338. * @param scene defines the hosting scene
  35339. * @param updatable defines if the mesh must be flagged as updatable
  35340. * @returns a new Mesh
  35341. */
  35342. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  35343. var options = {
  35344. xmin: xmin,
  35345. zmin: zmin,
  35346. xmax: xmax,
  35347. zmax: zmax,
  35348. subdivisions: subdivisions,
  35349. precision: precision,
  35350. updatable: updatable
  35351. };
  35352. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  35353. };
  35354. /**
  35355. * Creates a ground mesh from a height map.
  35356. * Please consider using the same method from the MeshBuilder class instead
  35357. * @see http://doc.babylonjs.com/babylon101/height_map
  35358. * @param name defines the name of the mesh to create
  35359. * @param url sets the URL of the height map image resource
  35360. * @param width set the ground width size
  35361. * @param height set the ground height size
  35362. * @param subdivisions sets the number of subdivision per side
  35363. * @param minHeight is the minimum altitude on the ground
  35364. * @param maxHeight is the maximum altitude on the ground
  35365. * @param scene defines the hosting scene
  35366. * @param updatable defines if the mesh must be flagged as updatable
  35367. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  35368. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  35369. * @returns a new Mesh
  35370. */
  35371. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  35372. var options = {
  35373. width: width,
  35374. height: height,
  35375. subdivisions: subdivisions,
  35376. minHeight: minHeight,
  35377. maxHeight: maxHeight,
  35378. updatable: updatable,
  35379. onReady: onReady,
  35380. alphaFilter: alphaFilter
  35381. };
  35382. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  35383. };
  35384. /**
  35385. * Creates a tube mesh.
  35386. * The tube is a parametric shape.
  35387. * It has no predefined shape. Its final shape will depend on the input parameters.
  35388. * Please consider using the same method from the MeshBuilder class instead
  35389. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  35390. * @param name defines the name of the mesh to create
  35391. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  35392. * @param radius sets the tube radius size
  35393. * @param tessellation is the number of sides on the tubular surface
  35394. * @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
  35395. * @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
  35396. * @param scene defines the hosting scene
  35397. * @param updatable defines if the mesh must be flagged as updatable
  35398. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  35399. * @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)
  35400. * @returns a new Mesh
  35401. */
  35402. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  35403. var options = {
  35404. path: path,
  35405. radius: radius,
  35406. tessellation: tessellation,
  35407. radiusFunction: radiusFunction,
  35408. arc: 1,
  35409. cap: cap,
  35410. updatable: updatable,
  35411. sideOrientation: sideOrientation,
  35412. instance: instance
  35413. };
  35414. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  35415. };
  35416. /**
  35417. * Creates a polyhedron mesh.
  35418. * Please consider using the same method from the MeshBuilder class instead.
  35419. * * 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
  35420. * * The parameter `size` (positive float, default 1) sets the polygon size
  35421. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  35422. * * 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`
  35423. * * 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
  35424. * * 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)`)
  35425. * * 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
  35426. * * 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
  35427. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35428. * * 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
  35429. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  35430. * @param name defines the name of the mesh to create
  35431. * @param options defines the options used to create the mesh
  35432. * @param scene defines the hosting scene
  35433. * @returns a new Mesh
  35434. */
  35435. Mesh.CreatePolyhedron = function (name, options, scene) {
  35436. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  35437. };
  35438. /**
  35439. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  35440. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  35441. * * 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`)
  35442. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  35443. * * 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
  35444. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35445. * * 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
  35446. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  35447. * @param name defines the name of the mesh
  35448. * @param options defines the options used to create the mesh
  35449. * @param scene defines the hosting scene
  35450. * @returns a new Mesh
  35451. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  35452. */
  35453. Mesh.CreateIcoSphere = function (name, options, scene) {
  35454. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  35455. };
  35456. /**
  35457. * Creates a decal mesh.
  35458. * Please consider using the same method from the MeshBuilder class instead.
  35459. * A decal is a mesh usually applied as a model onto the surface of another mesh
  35460. * @param name defines the name of the mesh
  35461. * @param sourceMesh defines the mesh receiving the decal
  35462. * @param position sets the position of the decal in world coordinates
  35463. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  35464. * @param size sets the decal scaling
  35465. * @param angle sets the angle to rotate the decal
  35466. * @returns a new Mesh
  35467. */
  35468. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  35469. var options = {
  35470. position: position,
  35471. normal: normal,
  35472. size: size,
  35473. angle: angle
  35474. };
  35475. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  35476. };
  35477. // Skeletons
  35478. /**
  35479. * Prepare internal position array for software CPU skinning
  35480. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  35481. */
  35482. Mesh.prototype.setPositionsForCPUSkinning = function () {
  35483. if (!this._sourcePositions) {
  35484. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35485. if (!source) {
  35486. return this._sourcePositions;
  35487. }
  35488. this._sourcePositions = new Float32Array(source);
  35489. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35490. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  35491. }
  35492. }
  35493. return this._sourcePositions;
  35494. };
  35495. /**
  35496. * Prepare internal normal array for software CPU skinning
  35497. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  35498. */
  35499. Mesh.prototype.setNormalsForCPUSkinning = function () {
  35500. if (!this._sourceNormals) {
  35501. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35502. if (!source) {
  35503. return this._sourceNormals;
  35504. }
  35505. this._sourceNormals = new Float32Array(source);
  35506. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35507. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  35508. }
  35509. }
  35510. return this._sourceNormals;
  35511. };
  35512. /**
  35513. * Updates the vertex buffer by applying transformation from the bones
  35514. * @param skeleton defines the skeleton to apply to current mesh
  35515. * @returns the current mesh
  35516. */
  35517. Mesh.prototype.applySkeleton = function (skeleton) {
  35518. if (!this.geometry) {
  35519. return this;
  35520. }
  35521. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  35522. return this;
  35523. }
  35524. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  35525. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35526. return this;
  35527. }
  35528. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35529. return this;
  35530. }
  35531. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35532. return this;
  35533. }
  35534. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35535. return this;
  35536. }
  35537. if (!this._sourcePositions) {
  35538. var submeshes = this.subMeshes.slice();
  35539. this.setPositionsForCPUSkinning();
  35540. this.subMeshes = submeshes;
  35541. }
  35542. if (!this._sourceNormals) {
  35543. this.setNormalsForCPUSkinning();
  35544. }
  35545. // positionsData checks for not being Float32Array will only pass at most once
  35546. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35547. if (!positionsData) {
  35548. return this;
  35549. }
  35550. if (!(positionsData instanceof Float32Array)) {
  35551. positionsData = new Float32Array(positionsData);
  35552. }
  35553. // normalsData checks for not being Float32Array will only pass at most once
  35554. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35555. if (!normalsData) {
  35556. return this;
  35557. }
  35558. if (!(normalsData instanceof Float32Array)) {
  35559. normalsData = new Float32Array(normalsData);
  35560. }
  35561. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35562. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  35563. if (!matricesWeightsData || !matricesIndicesData) {
  35564. return this;
  35565. }
  35566. var needExtras = this.numBoneInfluencers > 4;
  35567. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  35568. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  35569. var skeletonMatrices = skeleton.getTransformMatrices(this);
  35570. var tempVector3 = BABYLON.Vector3.Zero();
  35571. var finalMatrix = new BABYLON.Matrix();
  35572. var tempMatrix = new BABYLON.Matrix();
  35573. var matWeightIdx = 0;
  35574. var inf;
  35575. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  35576. var weight;
  35577. for (inf = 0; inf < 4; inf++) {
  35578. weight = matricesWeightsData[matWeightIdx + inf];
  35579. if (weight > 0) {
  35580. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35581. finalMatrix.addToSelf(tempMatrix);
  35582. }
  35583. }
  35584. if (needExtras) {
  35585. for (inf = 0; inf < 4; inf++) {
  35586. weight = matricesWeightsExtraData[matWeightIdx + inf];
  35587. if (weight > 0) {
  35588. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35589. finalMatrix.addToSelf(tempMatrix);
  35590. }
  35591. }
  35592. }
  35593. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  35594. tempVector3.toArray(positionsData, index);
  35595. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  35596. tempVector3.toArray(normalsData, index);
  35597. finalMatrix.reset();
  35598. }
  35599. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  35600. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  35601. return this;
  35602. };
  35603. // Tools
  35604. /**
  35605. * 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
  35606. * @param meshes defines the list of meshes to scan
  35607. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  35608. */
  35609. Mesh.MinMax = function (meshes) {
  35610. var minVector = null;
  35611. var maxVector = null;
  35612. meshes.forEach(function (mesh, index, array) {
  35613. var boundingInfo = mesh.getBoundingInfo();
  35614. var boundingBox = boundingInfo.boundingBox;
  35615. if (!minVector || !maxVector) {
  35616. minVector = boundingBox.minimumWorld;
  35617. maxVector = boundingBox.maximumWorld;
  35618. }
  35619. else {
  35620. minVector.minimizeInPlace(boundingBox.minimumWorld);
  35621. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  35622. }
  35623. });
  35624. if (!minVector || !maxVector) {
  35625. return {
  35626. min: BABYLON.Vector3.Zero(),
  35627. max: BABYLON.Vector3.Zero()
  35628. };
  35629. }
  35630. return {
  35631. min: minVector,
  35632. max: maxVector
  35633. };
  35634. };
  35635. /**
  35636. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  35637. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  35638. * @returns a vector3
  35639. */
  35640. Mesh.Center = function (meshesOrMinMaxVector) {
  35641. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  35642. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  35643. };
  35644. /**
  35645. * Merge the array of meshes into a single mesh for performance reasons.
  35646. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  35647. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  35648. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  35649. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  35650. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  35651. * @returns a new mesh
  35652. */
  35653. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  35654. if (disposeSource === void 0) { disposeSource = true; }
  35655. var index;
  35656. if (!allow32BitsIndices) {
  35657. var totalVertices = 0;
  35658. // Counting vertices
  35659. for (index = 0; index < meshes.length; index++) {
  35660. if (meshes[index]) {
  35661. totalVertices += meshes[index].getTotalVertices();
  35662. if (totalVertices > 65536) {
  35663. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  35664. return null;
  35665. }
  35666. }
  35667. }
  35668. }
  35669. // Merge
  35670. var vertexData = null;
  35671. var otherVertexData;
  35672. var indiceArray = new Array();
  35673. var source = null;
  35674. for (index = 0; index < meshes.length; index++) {
  35675. if (meshes[index]) {
  35676. var wm = meshes[index].computeWorldMatrix(true);
  35677. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  35678. otherVertexData.transform(wm);
  35679. if (vertexData) {
  35680. vertexData.merge(otherVertexData, allow32BitsIndices);
  35681. }
  35682. else {
  35683. vertexData = otherVertexData;
  35684. source = meshes[index];
  35685. }
  35686. if (subdivideWithSubMeshes) {
  35687. indiceArray.push(meshes[index].getTotalIndices());
  35688. }
  35689. }
  35690. }
  35691. source = source;
  35692. if (!meshSubclass) {
  35693. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  35694. }
  35695. vertexData.applyToMesh(meshSubclass);
  35696. // Setting properties
  35697. meshSubclass.material = source.material;
  35698. meshSubclass.checkCollisions = source.checkCollisions;
  35699. // Cleaning
  35700. if (disposeSource) {
  35701. for (index = 0; index < meshes.length; index++) {
  35702. if (meshes[index]) {
  35703. meshes[index].dispose();
  35704. }
  35705. }
  35706. }
  35707. // Subdivide
  35708. if (subdivideWithSubMeshes) {
  35709. //-- removal of global submesh
  35710. meshSubclass.releaseSubMeshes();
  35711. index = 0;
  35712. var offset = 0;
  35713. //-- apply subdivision according to index table
  35714. while (index < indiceArray.length) {
  35715. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  35716. offset += indiceArray[index];
  35717. index++;
  35718. }
  35719. }
  35720. return meshSubclass;
  35721. };
  35722. /** @hidden */
  35723. Mesh.prototype.addInstance = function (instance) {
  35724. instance._indexInSourceMeshInstanceArray = this.instances.length;
  35725. this.instances.push(instance);
  35726. };
  35727. /** @hidden */
  35728. Mesh.prototype.removeInstance = function (instance) {
  35729. // Remove from mesh
  35730. var index = instance._indexInSourceMeshInstanceArray;
  35731. if (index != -1) {
  35732. if (index !== this.instances.length - 1) {
  35733. var last = this.instances[this.instances.length - 1];
  35734. this.instances[index] = last;
  35735. last._indexInSourceMeshInstanceArray = index;
  35736. }
  35737. instance._indexInSourceMeshInstanceArray = -1;
  35738. this.instances.pop();
  35739. }
  35740. };
  35741. // Consts
  35742. /**
  35743. * Mesh side orientation : usually the external or front surface
  35744. */
  35745. Mesh.FRONTSIDE = 0;
  35746. /**
  35747. * Mesh side orientation : usually the internal or back surface
  35748. */
  35749. Mesh.BACKSIDE = 1;
  35750. /**
  35751. * Mesh side orientation : both internal and external or front and back surfaces
  35752. */
  35753. Mesh.DOUBLESIDE = 2;
  35754. /**
  35755. * Mesh side orientation : by default, `FRONTSIDE`
  35756. */
  35757. Mesh.DEFAULTSIDE = 0;
  35758. /**
  35759. * Mesh cap setting : no cap
  35760. */
  35761. Mesh.NO_CAP = 0;
  35762. /**
  35763. * Mesh cap setting : one cap at the beginning of the mesh
  35764. */
  35765. Mesh.CAP_START = 1;
  35766. /**
  35767. * Mesh cap setting : one cap at the end of the mesh
  35768. */
  35769. Mesh.CAP_END = 2;
  35770. /**
  35771. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  35772. */
  35773. Mesh.CAP_ALL = 3;
  35774. return Mesh;
  35775. }(BABYLON.AbstractMesh));
  35776. BABYLON.Mesh = Mesh;
  35777. })(BABYLON || (BABYLON = {}));
  35778. //# sourceMappingURL=mesh.js.map
  35779. var BABYLON;
  35780. (function (BABYLON) {
  35781. /**
  35782. * Base class for submeshes
  35783. */
  35784. var BaseSubMesh = /** @class */ (function () {
  35785. function BaseSubMesh() {
  35786. }
  35787. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  35788. /**
  35789. * Gets associated effect
  35790. */
  35791. get: function () {
  35792. return this._materialEffect;
  35793. },
  35794. enumerable: true,
  35795. configurable: true
  35796. });
  35797. /**
  35798. * Sets associated effect (effect used to render this submesh)
  35799. * @param effect defines the effect to associate with
  35800. * @param defines defines the set of defines used to compile this effect
  35801. */
  35802. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  35803. if (defines === void 0) { defines = null; }
  35804. if (this._materialEffect === effect) {
  35805. if (!effect) {
  35806. this._materialDefines = null;
  35807. }
  35808. return;
  35809. }
  35810. this._materialDefines = defines;
  35811. this._materialEffect = effect;
  35812. };
  35813. return BaseSubMesh;
  35814. }());
  35815. BABYLON.BaseSubMesh = BaseSubMesh;
  35816. /**
  35817. * Defines a subdivision inside a mesh
  35818. */
  35819. var SubMesh = /** @class */ (function (_super) {
  35820. __extends(SubMesh, _super);
  35821. /**
  35822. * Creates a new submesh
  35823. * @param materialIndex defines the material index to use
  35824. * @param verticesStart defines vertex index start
  35825. * @param verticesCount defines vertices count
  35826. * @param indexStart defines index start
  35827. * @param indexCount defines indices count
  35828. * @param mesh defines the parent mesh
  35829. * @param renderingMesh defines an optional rendering mesh
  35830. * @param createBoundingBox defines if bounding box should be created for this submesh
  35831. */
  35832. function SubMesh(
  35833. /** the material index to use */
  35834. materialIndex,
  35835. /** vertex index start */
  35836. verticesStart,
  35837. /** vertices count */
  35838. verticesCount,
  35839. /** index start */
  35840. indexStart,
  35841. /** indices count */
  35842. indexCount, mesh, renderingMesh, createBoundingBox) {
  35843. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35844. var _this = _super.call(this) || this;
  35845. _this.materialIndex = materialIndex;
  35846. _this.verticesStart = verticesStart;
  35847. _this.verticesCount = verticesCount;
  35848. _this.indexStart = indexStart;
  35849. _this.indexCount = indexCount;
  35850. /** @hidden */
  35851. _this._renderId = 0;
  35852. _this._mesh = mesh;
  35853. _this._renderingMesh = renderingMesh || mesh;
  35854. mesh.subMeshes.push(_this);
  35855. _this._trianglePlanes = [];
  35856. _this._id = mesh.subMeshes.length - 1;
  35857. if (createBoundingBox) {
  35858. _this.refreshBoundingInfo();
  35859. mesh.computeWorldMatrix(true);
  35860. }
  35861. return _this;
  35862. }
  35863. /**
  35864. * Add a new submesh to a mesh
  35865. * @param materialIndex defines the material index to use
  35866. * @param verticesStart defines vertex index start
  35867. * @param verticesCount defines vertices count
  35868. * @param indexStart defines index start
  35869. * @param indexCount defines indices count
  35870. * @param mesh defines the parent mesh
  35871. * @param renderingMesh defines an optional rendering mesh
  35872. * @param createBoundingBox defines if bounding box should be created for this submesh
  35873. * @returns the new submesh
  35874. */
  35875. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  35876. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35877. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  35878. };
  35879. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  35880. /**
  35881. * Returns true if this submesh covers the entire parent mesh
  35882. * @ignorenaming
  35883. */
  35884. get: function () {
  35885. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  35886. },
  35887. enumerable: true,
  35888. configurable: true
  35889. });
  35890. /**
  35891. * Returns the submesh BoudingInfo object
  35892. * @returns current bounding info (or mesh's one if the submesh is global)
  35893. */
  35894. SubMesh.prototype.getBoundingInfo = function () {
  35895. if (this.IsGlobal) {
  35896. return this._mesh.getBoundingInfo();
  35897. }
  35898. return this._boundingInfo;
  35899. };
  35900. /**
  35901. * Sets the submesh BoundingInfo
  35902. * @param boundingInfo defines the new bounding info to use
  35903. * @returns the SubMesh
  35904. */
  35905. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  35906. this._boundingInfo = boundingInfo;
  35907. return this;
  35908. };
  35909. /**
  35910. * Returns the mesh of the current submesh
  35911. * @return the parent mesh
  35912. */
  35913. SubMesh.prototype.getMesh = function () {
  35914. return this._mesh;
  35915. };
  35916. /**
  35917. * Returns the rendering mesh of the submesh
  35918. * @returns the rendering mesh (could be different from parent mesh)
  35919. */
  35920. SubMesh.prototype.getRenderingMesh = function () {
  35921. return this._renderingMesh;
  35922. };
  35923. /**
  35924. * Returns the submesh material
  35925. * @returns null or the current material
  35926. */
  35927. SubMesh.prototype.getMaterial = function () {
  35928. var rootMaterial = this._renderingMesh.material;
  35929. if (rootMaterial === null || rootMaterial === undefined) {
  35930. return this._mesh.getScene().defaultMaterial;
  35931. }
  35932. else if (rootMaterial.getSubMaterial) {
  35933. var multiMaterial = rootMaterial;
  35934. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  35935. if (this._currentMaterial !== effectiveMaterial) {
  35936. this._currentMaterial = effectiveMaterial;
  35937. this._materialDefines = null;
  35938. }
  35939. return effectiveMaterial;
  35940. }
  35941. return rootMaterial;
  35942. };
  35943. // Methods
  35944. /**
  35945. * Sets a new updated BoundingInfo object to the submesh
  35946. * @returns the SubMesh
  35947. */
  35948. SubMesh.prototype.refreshBoundingInfo = function () {
  35949. this._lastColliderWorldVertices = null;
  35950. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  35951. return this;
  35952. }
  35953. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35954. if (!data) {
  35955. this._boundingInfo = this._mesh.getBoundingInfo();
  35956. return this;
  35957. }
  35958. var indices = this._renderingMesh.getIndices();
  35959. var extend;
  35960. //is this the only submesh?
  35961. if (this.indexStart === 0 && this.indexCount === indices.length) {
  35962. var boundingInfo = this._renderingMesh.getBoundingInfo();
  35963. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  35964. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  35965. }
  35966. else {
  35967. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  35968. }
  35969. if (this._boundingInfo) {
  35970. this._boundingInfo.reConstruct(extend.minimum, extend.maximum);
  35971. }
  35972. else {
  35973. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  35974. }
  35975. return this;
  35976. };
  35977. /** @hidden */
  35978. SubMesh.prototype._checkCollision = function (collider) {
  35979. var boundingInfo = this.getBoundingInfo();
  35980. return boundingInfo._checkCollision(collider);
  35981. };
  35982. /**
  35983. * Updates the submesh BoundingInfo
  35984. * @param world defines the world matrix to use to update the bounding info
  35985. * @returns the submesh
  35986. */
  35987. SubMesh.prototype.updateBoundingInfo = function (world) {
  35988. var boundingInfo = this.getBoundingInfo();
  35989. if (!boundingInfo) {
  35990. this.refreshBoundingInfo();
  35991. boundingInfo = this.getBoundingInfo();
  35992. }
  35993. boundingInfo.update(world);
  35994. return this;
  35995. };
  35996. /**
  35997. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  35998. * @param frustumPlanes defines the frustum planes
  35999. * @returns true if the submesh is intersecting with the frustum
  36000. */
  36001. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  36002. var boundingInfo = this.getBoundingInfo();
  36003. if (!boundingInfo) {
  36004. return false;
  36005. }
  36006. return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy);
  36007. };
  36008. /**
  36009. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
  36010. * @param frustumPlanes defines the frustum planes
  36011. * @returns true if the submesh is inside the frustum
  36012. */
  36013. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  36014. var boundingInfo = this.getBoundingInfo();
  36015. if (!boundingInfo) {
  36016. return false;
  36017. }
  36018. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  36019. };
  36020. /**
  36021. * Renders the submesh
  36022. * @param enableAlphaMode defines if alpha needs to be used
  36023. * @returns the submesh
  36024. */
  36025. SubMesh.prototype.render = function (enableAlphaMode) {
  36026. this._renderingMesh.render(this, enableAlphaMode);
  36027. return this;
  36028. };
  36029. /**
  36030. * @hidden
  36031. */
  36032. SubMesh.prototype._getLinesIndexBuffer = function (indices, engine) {
  36033. if (!this._linesIndexBuffer) {
  36034. var linesIndices = [];
  36035. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  36036. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  36037. }
  36038. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  36039. this._linesIndexCount = linesIndices.length;
  36040. }
  36041. return this._linesIndexBuffer;
  36042. };
  36043. /**
  36044. * Checks if the submesh intersects with a ray
  36045. * @param ray defines the ray to test
  36046. * @returns true is the passed ray intersects the submesh bounding box
  36047. */
  36048. SubMesh.prototype.canIntersects = function (ray) {
  36049. var boundingInfo = this.getBoundingInfo();
  36050. if (!boundingInfo) {
  36051. return false;
  36052. }
  36053. return ray.intersectsBox(boundingInfo.boundingBox);
  36054. };
  36055. /**
  36056. * Intersects current submesh with a ray
  36057. * @param ray defines the ray to test
  36058. * @param positions defines mesh's positions array
  36059. * @param indices defines mesh's indices array
  36060. * @param fastCheck defines if only bounding info should be used
  36061. * @returns intersection info or null if no intersection
  36062. */
  36063. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  36064. var material = this.getMaterial();
  36065. if (!material) {
  36066. return null;
  36067. }
  36068. switch (material.fillMode) {
  36069. case BABYLON.Material.PointListDrawMode:
  36070. case BABYLON.Material.LineListDrawMode:
  36071. case BABYLON.Material.LineLoopDrawMode:
  36072. case BABYLON.Material.LineStripDrawMode:
  36073. case BABYLON.Material.TriangleFanDrawMode:
  36074. case BABYLON.Material.TriangleStripDrawMode:
  36075. return null;
  36076. }
  36077. // LineMesh first as it's also a Mesh...
  36078. if (BABYLON.LinesMesh) {
  36079. var mesh = this._mesh instanceof BABYLON.InstancedMesh ? this._mesh.sourceMesh : this._mesh;
  36080. if (mesh instanceof BABYLON.LinesMesh) {
  36081. var linesMesh = mesh;
  36082. return this._intersectLines(ray, positions, indices, linesMesh.intersectionThreshold, fastCheck);
  36083. }
  36084. }
  36085. return this._intersectTriangles(ray, positions, indices, fastCheck);
  36086. };
  36087. /** @hidden */
  36088. SubMesh.prototype._intersectLines = function (ray, positions, indices, intersectionThreshold, fastCheck) {
  36089. var intersectInfo = null;
  36090. // Line test
  36091. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  36092. var p0 = positions[indices[index]];
  36093. var p1 = positions[indices[index + 1]];
  36094. var length = ray.intersectionSegment(p0, p1, intersectionThreshold);
  36095. if (length < 0) {
  36096. continue;
  36097. }
  36098. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  36099. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  36100. if (fastCheck) {
  36101. break;
  36102. }
  36103. }
  36104. }
  36105. return intersectInfo;
  36106. };
  36107. /** @hidden */
  36108. SubMesh.prototype._intersectTriangles = function (ray, positions, indices, fastCheck) {
  36109. var intersectInfo = null;
  36110. // Triangles test
  36111. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  36112. var p0 = positions[indices[index]];
  36113. var p1 = positions[indices[index + 1]];
  36114. var p2 = positions[indices[index + 2]];
  36115. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  36116. if (currentIntersectInfo) {
  36117. if (currentIntersectInfo.distance < 0) {
  36118. continue;
  36119. }
  36120. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  36121. intersectInfo = currentIntersectInfo;
  36122. intersectInfo.faceId = index / 3;
  36123. if (fastCheck) {
  36124. break;
  36125. }
  36126. }
  36127. }
  36128. }
  36129. return intersectInfo;
  36130. };
  36131. /** @hidden */
  36132. SubMesh.prototype._rebuild = function () {
  36133. if (this._linesIndexBuffer) {
  36134. this._linesIndexBuffer = null;
  36135. }
  36136. };
  36137. // Clone
  36138. /**
  36139. * Creates a new submesh from the passed mesh
  36140. * @param newMesh defines the new hosting mesh
  36141. * @param newRenderingMesh defines an optional rendering mesh
  36142. * @returns the new submesh
  36143. */
  36144. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  36145. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  36146. if (!this.IsGlobal) {
  36147. var boundingInfo = this.getBoundingInfo();
  36148. if (!boundingInfo) {
  36149. return result;
  36150. }
  36151. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  36152. }
  36153. return result;
  36154. };
  36155. // Dispose
  36156. /**
  36157. * Release associated resources
  36158. */
  36159. SubMesh.prototype.dispose = function () {
  36160. if (this._linesIndexBuffer) {
  36161. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  36162. this._linesIndexBuffer = null;
  36163. }
  36164. // Remove from mesh
  36165. var index = this._mesh.subMeshes.indexOf(this);
  36166. this._mesh.subMeshes.splice(index, 1);
  36167. };
  36168. // Statics
  36169. /**
  36170. * Creates a new submesh from indices data
  36171. * @param materialIndex the index of the main mesh material
  36172. * @param startIndex the index where to start the copy in the mesh indices array
  36173. * @param indexCount the number of indices to copy then from the startIndex
  36174. * @param mesh the main mesh to create the submesh from
  36175. * @param renderingMesh the optional rendering mesh
  36176. * @returns a new submesh
  36177. */
  36178. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  36179. var minVertexIndex = Number.MAX_VALUE;
  36180. var maxVertexIndex = -Number.MAX_VALUE;
  36181. renderingMesh = (renderingMesh || mesh);
  36182. var indices = renderingMesh.getIndices();
  36183. for (var index = startIndex; index < startIndex + indexCount; index++) {
  36184. var vertexIndex = indices[index];
  36185. if (vertexIndex < minVertexIndex) {
  36186. minVertexIndex = vertexIndex;
  36187. }
  36188. if (vertexIndex > maxVertexIndex) {
  36189. maxVertexIndex = vertexIndex;
  36190. }
  36191. }
  36192. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  36193. };
  36194. return SubMesh;
  36195. }(BaseSubMesh));
  36196. BABYLON.SubMesh = SubMesh;
  36197. })(BABYLON || (BABYLON = {}));
  36198. //# sourceMappingURL=subMesh.js.map
  36199. var __assign = (this && this.__assign) || function () {
  36200. __assign = Object.assign || function(t) {
  36201. for (var s, i = 1, n = arguments.length; i < n; i++) {
  36202. s = arguments[i];
  36203. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  36204. t[p] = s[p];
  36205. }
  36206. return t;
  36207. };
  36208. return __assign.apply(this, arguments);
  36209. };
  36210. var BABYLON;
  36211. (function (BABYLON) {
  36212. /**
  36213. * Manages the defines for the Material
  36214. */
  36215. var MaterialDefines = /** @class */ (function () {
  36216. function MaterialDefines() {
  36217. this._isDirty = true;
  36218. /** @hidden */
  36219. this._areLightsDirty = true;
  36220. /** @hidden */
  36221. this._areAttributesDirty = true;
  36222. /** @hidden */
  36223. this._areTexturesDirty = true;
  36224. /** @hidden */
  36225. this._areFresnelDirty = true;
  36226. /** @hidden */
  36227. this._areMiscDirty = true;
  36228. /** @hidden */
  36229. this._areImageProcessingDirty = true;
  36230. /** @hidden */
  36231. this._normals = false;
  36232. /** @hidden */
  36233. this._uvs = false;
  36234. /** @hidden */
  36235. this._needNormals = false;
  36236. /** @hidden */
  36237. this._needUVs = false;
  36238. }
  36239. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  36240. /**
  36241. * Specifies if the material needs to be re-calculated
  36242. */
  36243. get: function () {
  36244. return this._isDirty;
  36245. },
  36246. enumerable: true,
  36247. configurable: true
  36248. });
  36249. /**
  36250. * Marks the material to indicate that it has been re-calculated
  36251. */
  36252. MaterialDefines.prototype.markAsProcessed = function () {
  36253. this._isDirty = false;
  36254. this._areAttributesDirty = false;
  36255. this._areTexturesDirty = false;
  36256. this._areFresnelDirty = false;
  36257. this._areLightsDirty = false;
  36258. this._areMiscDirty = false;
  36259. this._areImageProcessingDirty = false;
  36260. };
  36261. /**
  36262. * Marks the material to indicate that it needs to be re-calculated
  36263. */
  36264. MaterialDefines.prototype.markAsUnprocessed = function () {
  36265. this._isDirty = true;
  36266. };
  36267. /**
  36268. * Marks the material to indicate all of its defines need to be re-calculated
  36269. */
  36270. MaterialDefines.prototype.markAllAsDirty = function () {
  36271. this._areTexturesDirty = true;
  36272. this._areAttributesDirty = true;
  36273. this._areLightsDirty = true;
  36274. this._areFresnelDirty = true;
  36275. this._areMiscDirty = true;
  36276. this._areImageProcessingDirty = true;
  36277. this._isDirty = true;
  36278. };
  36279. /**
  36280. * Marks the material to indicate that image processing needs to be re-calculated
  36281. */
  36282. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  36283. this._areImageProcessingDirty = true;
  36284. this._isDirty = true;
  36285. };
  36286. /**
  36287. * Marks the material to indicate the lights need to be re-calculated
  36288. */
  36289. MaterialDefines.prototype.markAsLightDirty = function () {
  36290. this._areLightsDirty = true;
  36291. this._isDirty = true;
  36292. };
  36293. /**
  36294. * Marks the attribute state as changed
  36295. */
  36296. MaterialDefines.prototype.markAsAttributesDirty = function () {
  36297. this._areAttributesDirty = true;
  36298. this._isDirty = true;
  36299. };
  36300. /**
  36301. * Marks the texture state as changed
  36302. */
  36303. MaterialDefines.prototype.markAsTexturesDirty = function () {
  36304. this._areTexturesDirty = true;
  36305. this._isDirty = true;
  36306. };
  36307. /**
  36308. * Marks the fresnel state as changed
  36309. */
  36310. MaterialDefines.prototype.markAsFresnelDirty = function () {
  36311. this._areFresnelDirty = true;
  36312. this._isDirty = true;
  36313. };
  36314. /**
  36315. * Marks the misc state as changed
  36316. */
  36317. MaterialDefines.prototype.markAsMiscDirty = function () {
  36318. this._areMiscDirty = true;
  36319. this._isDirty = true;
  36320. };
  36321. /**
  36322. * Rebuilds the material defines
  36323. */
  36324. MaterialDefines.prototype.rebuild = function () {
  36325. if (this._keys) {
  36326. delete this._keys;
  36327. }
  36328. this._keys = [];
  36329. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  36330. var key = _a[_i];
  36331. if (key[0] === "_") {
  36332. continue;
  36333. }
  36334. this._keys.push(key);
  36335. }
  36336. };
  36337. /**
  36338. * Specifies if two material defines are equal
  36339. * @param other - A material define instance to compare to
  36340. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  36341. */
  36342. MaterialDefines.prototype.isEqual = function (other) {
  36343. if (this._keys.length !== other._keys.length) {
  36344. return false;
  36345. }
  36346. for (var index = 0; index < this._keys.length; index++) {
  36347. var prop = this._keys[index];
  36348. if (this[prop] !== other[prop]) {
  36349. return false;
  36350. }
  36351. }
  36352. return true;
  36353. };
  36354. /**
  36355. * Clones this instance's defines to another instance
  36356. * @param other - material defines to clone values to
  36357. */
  36358. MaterialDefines.prototype.cloneTo = function (other) {
  36359. if (this._keys.length !== other._keys.length) {
  36360. other._keys = this._keys.slice(0);
  36361. }
  36362. for (var index = 0; index < this._keys.length; index++) {
  36363. var prop = this._keys[index];
  36364. other[prop] = this[prop];
  36365. }
  36366. };
  36367. /**
  36368. * Resets the material define values
  36369. */
  36370. MaterialDefines.prototype.reset = function () {
  36371. for (var index = 0; index < this._keys.length; index++) {
  36372. var prop = this._keys[index];
  36373. var type = typeof this[prop];
  36374. switch (type) {
  36375. case "number":
  36376. this[prop] = 0;
  36377. break;
  36378. case "string":
  36379. this[prop] = "";
  36380. break;
  36381. default:
  36382. this[prop] = false;
  36383. break;
  36384. }
  36385. }
  36386. };
  36387. /**
  36388. * Converts the material define values to a string
  36389. * @returns - String of material define information
  36390. */
  36391. MaterialDefines.prototype.toString = function () {
  36392. var result = "";
  36393. for (var index = 0; index < this._keys.length; index++) {
  36394. var prop = this._keys[index];
  36395. var value = this[prop];
  36396. var type = typeof value;
  36397. switch (type) {
  36398. case "number":
  36399. case "string":
  36400. result += "#define " + prop + " " + value + "\n";
  36401. break;
  36402. default:
  36403. if (value) {
  36404. result += "#define " + prop + "\n";
  36405. }
  36406. break;
  36407. }
  36408. }
  36409. return result;
  36410. };
  36411. return MaterialDefines;
  36412. }());
  36413. BABYLON.MaterialDefines = MaterialDefines;
  36414. /**
  36415. * Base class for the main features of a material in Babylon.js
  36416. */
  36417. var Material = /** @class */ (function () {
  36418. /**
  36419. * Creates a material instance
  36420. * @param name defines the name of the material
  36421. * @param scene defines the scene to reference
  36422. * @param doNotAdd specifies if the material should be added to the scene
  36423. */
  36424. function Material(name, scene, doNotAdd) {
  36425. /**
  36426. * Specifies if the ready state should be checked on each call
  36427. */
  36428. this.checkReadyOnEveryCall = false;
  36429. /**
  36430. * Specifies if the ready state should be checked once
  36431. */
  36432. this.checkReadyOnlyOnce = false;
  36433. /**
  36434. * The state of the material
  36435. */
  36436. this.state = "";
  36437. /**
  36438. * The alpha value of the material
  36439. */
  36440. this._alpha = 1.0;
  36441. /**
  36442. * Specifies if back face culling is enabled
  36443. */
  36444. this._backFaceCulling = true;
  36445. /**
  36446. * Specifies if the material should be serialized
  36447. */
  36448. this.doNotSerialize = false;
  36449. /**
  36450. * @hidden
  36451. */
  36452. this._storeEffectOnSubMeshes = false;
  36453. /**
  36454. * An event triggered when the material is disposed
  36455. */
  36456. this.onDisposeObservable = new BABYLON.Observable();
  36457. /**
  36458. * Stores the value of the alpha mode
  36459. */
  36460. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  36461. /**
  36462. * Stores the state of the need depth pre-pass value
  36463. */
  36464. this._needDepthPrePass = false;
  36465. /**
  36466. * Specifies if depth writing should be disabled
  36467. */
  36468. this.disableDepthWrite = false;
  36469. /**
  36470. * Specifies if depth writing should be forced
  36471. */
  36472. this.forceDepthWrite = false;
  36473. /**
  36474. * Specifies if there should be a separate pass for culling
  36475. */
  36476. this.separateCullingPass = false;
  36477. /**
  36478. * Stores the state specifing if fog should be enabled
  36479. */
  36480. this._fogEnabled = true;
  36481. /**
  36482. * Stores the size of points
  36483. */
  36484. this.pointSize = 1.0;
  36485. /**
  36486. * Stores the z offset value
  36487. */
  36488. this.zOffset = 0;
  36489. /**
  36490. * @hidden
  36491. * Specifies if the material was previously ready
  36492. */
  36493. this._wasPreviouslyReady = false;
  36494. /**
  36495. * Stores the fill mode state
  36496. */
  36497. this._fillMode = Material.TriangleFillMode;
  36498. /** @hidden */
  36499. this._indexInSceneMaterialArray = -1;
  36500. this.name = name;
  36501. this.id = name || BABYLON.Tools.RandomId();
  36502. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  36503. this.uniqueId = this._scene.getUniqueId();
  36504. if (this._scene.useRightHandedSystem) {
  36505. this.sideOrientation = Material.ClockWiseSideOrientation;
  36506. }
  36507. else {
  36508. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  36509. }
  36510. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  36511. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  36512. if (!doNotAdd) {
  36513. this._scene.addMaterial(this);
  36514. }
  36515. if (this._scene.useMaterialMeshMap) {
  36516. this.meshMap = {};
  36517. }
  36518. }
  36519. Object.defineProperty(Material, "TriangleFillMode", {
  36520. /**
  36521. * Returns the triangle fill mode
  36522. */
  36523. get: function () {
  36524. return Material._TriangleFillMode;
  36525. },
  36526. enumerable: true,
  36527. configurable: true
  36528. });
  36529. Object.defineProperty(Material, "WireFrameFillMode", {
  36530. /**
  36531. * Returns the wireframe mode
  36532. */
  36533. get: function () {
  36534. return Material._WireFrameFillMode;
  36535. },
  36536. enumerable: true,
  36537. configurable: true
  36538. });
  36539. Object.defineProperty(Material, "PointFillMode", {
  36540. /**
  36541. * Returns the point fill mode
  36542. */
  36543. get: function () {
  36544. return Material._PointFillMode;
  36545. },
  36546. enumerable: true,
  36547. configurable: true
  36548. });
  36549. Object.defineProperty(Material, "PointListDrawMode", {
  36550. /**
  36551. * Returns the point list draw mode
  36552. */
  36553. get: function () {
  36554. return Material._PointListDrawMode;
  36555. },
  36556. enumerable: true,
  36557. configurable: true
  36558. });
  36559. Object.defineProperty(Material, "LineListDrawMode", {
  36560. /**
  36561. * Returns the line list draw mode
  36562. */
  36563. get: function () {
  36564. return Material._LineListDrawMode;
  36565. },
  36566. enumerable: true,
  36567. configurable: true
  36568. });
  36569. Object.defineProperty(Material, "LineLoopDrawMode", {
  36570. /**
  36571. * Returns the line loop draw mode
  36572. */
  36573. get: function () {
  36574. return Material._LineLoopDrawMode;
  36575. },
  36576. enumerable: true,
  36577. configurable: true
  36578. });
  36579. Object.defineProperty(Material, "LineStripDrawMode", {
  36580. /**
  36581. * Returns the line strip draw mode
  36582. */
  36583. get: function () {
  36584. return Material._LineStripDrawMode;
  36585. },
  36586. enumerable: true,
  36587. configurable: true
  36588. });
  36589. Object.defineProperty(Material, "TriangleStripDrawMode", {
  36590. /**
  36591. * Returns the triangle strip draw mode
  36592. */
  36593. get: function () {
  36594. return Material._TriangleStripDrawMode;
  36595. },
  36596. enumerable: true,
  36597. configurable: true
  36598. });
  36599. Object.defineProperty(Material, "TriangleFanDrawMode", {
  36600. /**
  36601. * Returns the triangle fan draw mode
  36602. */
  36603. get: function () {
  36604. return Material._TriangleFanDrawMode;
  36605. },
  36606. enumerable: true,
  36607. configurable: true
  36608. });
  36609. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  36610. /**
  36611. * Returns the clock-wise side orientation
  36612. */
  36613. get: function () {
  36614. return Material._ClockWiseSideOrientation;
  36615. },
  36616. enumerable: true,
  36617. configurable: true
  36618. });
  36619. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  36620. /**
  36621. * Returns the counter clock-wise side orientation
  36622. */
  36623. get: function () {
  36624. return Material._CounterClockWiseSideOrientation;
  36625. },
  36626. enumerable: true,
  36627. configurable: true
  36628. });
  36629. Object.defineProperty(Material.prototype, "alpha", {
  36630. /**
  36631. * Gets the alpha value of the material
  36632. */
  36633. get: function () {
  36634. return this._alpha;
  36635. },
  36636. /**
  36637. * Sets the alpha value of the material
  36638. */
  36639. set: function (value) {
  36640. if (this._alpha === value) {
  36641. return;
  36642. }
  36643. this._alpha = value;
  36644. this.markAsDirty(Material.MiscDirtyFlag);
  36645. },
  36646. enumerable: true,
  36647. configurable: true
  36648. });
  36649. Object.defineProperty(Material.prototype, "backFaceCulling", {
  36650. /**
  36651. * Gets the back-face culling state
  36652. */
  36653. get: function () {
  36654. return this._backFaceCulling;
  36655. },
  36656. /**
  36657. * Sets the back-face culling state
  36658. */
  36659. set: function (value) {
  36660. if (this._backFaceCulling === value) {
  36661. return;
  36662. }
  36663. this._backFaceCulling = value;
  36664. this.markAsDirty(Material.TextureDirtyFlag);
  36665. },
  36666. enumerable: true,
  36667. configurable: true
  36668. });
  36669. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  36670. /**
  36671. * Gets a boolean indicating that current material needs to register RTT
  36672. */
  36673. get: function () {
  36674. return false;
  36675. },
  36676. enumerable: true,
  36677. configurable: true
  36678. });
  36679. Object.defineProperty(Material.prototype, "onDispose", {
  36680. /**
  36681. * Called during a dispose event
  36682. */
  36683. set: function (callback) {
  36684. if (this._onDisposeObserver) {
  36685. this.onDisposeObservable.remove(this._onDisposeObserver);
  36686. }
  36687. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  36688. },
  36689. enumerable: true,
  36690. configurable: true
  36691. });
  36692. Object.defineProperty(Material.prototype, "onBindObservable", {
  36693. /**
  36694. * An event triggered when the material is bound
  36695. */
  36696. get: function () {
  36697. if (!this._onBindObservable) {
  36698. this._onBindObservable = new BABYLON.Observable();
  36699. }
  36700. return this._onBindObservable;
  36701. },
  36702. enumerable: true,
  36703. configurable: true
  36704. });
  36705. Object.defineProperty(Material.prototype, "onBind", {
  36706. /**
  36707. * Called during a bind event
  36708. */
  36709. set: function (callback) {
  36710. if (this._onBindObserver) {
  36711. this.onBindObservable.remove(this._onBindObserver);
  36712. }
  36713. this._onBindObserver = this.onBindObservable.add(callback);
  36714. },
  36715. enumerable: true,
  36716. configurable: true
  36717. });
  36718. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  36719. /**
  36720. * An event triggered when the material is unbound
  36721. */
  36722. get: function () {
  36723. if (!this._onUnBindObservable) {
  36724. this._onUnBindObservable = new BABYLON.Observable();
  36725. }
  36726. return this._onUnBindObservable;
  36727. },
  36728. enumerable: true,
  36729. configurable: true
  36730. });
  36731. Object.defineProperty(Material.prototype, "alphaMode", {
  36732. /**
  36733. * Gets the value of the alpha mode
  36734. */
  36735. get: function () {
  36736. return this._alphaMode;
  36737. },
  36738. /**
  36739. * Sets the value of the alpha mode.
  36740. *
  36741. * | Value | Type | Description |
  36742. * | --- | --- | --- |
  36743. * | 0 | ALPHA_DISABLE | |
  36744. * | 1 | ALPHA_ADD | |
  36745. * | 2 | ALPHA_COMBINE | |
  36746. * | 3 | ALPHA_SUBTRACT | |
  36747. * | 4 | ALPHA_MULTIPLY | |
  36748. * | 5 | ALPHA_MAXIMIZED | |
  36749. * | 6 | ALPHA_ONEONE | |
  36750. * | 7 | ALPHA_PREMULTIPLIED | |
  36751. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  36752. * | 9 | ALPHA_INTERPOLATE | |
  36753. * | 10 | ALPHA_SCREENMODE | |
  36754. *
  36755. */
  36756. set: function (value) {
  36757. if (this._alphaMode === value) {
  36758. return;
  36759. }
  36760. this._alphaMode = value;
  36761. this.markAsDirty(Material.TextureDirtyFlag);
  36762. },
  36763. enumerable: true,
  36764. configurable: true
  36765. });
  36766. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  36767. /**
  36768. * Gets the depth pre-pass value
  36769. */
  36770. get: function () {
  36771. return this._needDepthPrePass;
  36772. },
  36773. /**
  36774. * Sets the need depth pre-pass value
  36775. */
  36776. set: function (value) {
  36777. if (this._needDepthPrePass === value) {
  36778. return;
  36779. }
  36780. this._needDepthPrePass = value;
  36781. if (this._needDepthPrePass) {
  36782. this.checkReadyOnEveryCall = true;
  36783. }
  36784. },
  36785. enumerable: true,
  36786. configurable: true
  36787. });
  36788. Object.defineProperty(Material.prototype, "fogEnabled", {
  36789. /**
  36790. * Gets the value of the fog enabled state
  36791. */
  36792. get: function () {
  36793. return this._fogEnabled;
  36794. },
  36795. /**
  36796. * Sets the state for enabling fog
  36797. */
  36798. set: function (value) {
  36799. if (this._fogEnabled === value) {
  36800. return;
  36801. }
  36802. this._fogEnabled = value;
  36803. this.markAsDirty(Material.MiscDirtyFlag);
  36804. },
  36805. enumerable: true,
  36806. configurable: true
  36807. });
  36808. Object.defineProperty(Material.prototype, "wireframe", {
  36809. /**
  36810. * Gets a value specifying if wireframe mode is enabled
  36811. */
  36812. get: function () {
  36813. switch (this._fillMode) {
  36814. case Material.WireFrameFillMode:
  36815. case Material.LineListDrawMode:
  36816. case Material.LineLoopDrawMode:
  36817. case Material.LineStripDrawMode:
  36818. return true;
  36819. }
  36820. return this._scene.forceWireframe;
  36821. },
  36822. /**
  36823. * Sets the state of wireframe mode
  36824. */
  36825. set: function (value) {
  36826. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  36827. },
  36828. enumerable: true,
  36829. configurable: true
  36830. });
  36831. Object.defineProperty(Material.prototype, "pointsCloud", {
  36832. /**
  36833. * Gets the value specifying if point clouds are enabled
  36834. */
  36835. get: function () {
  36836. switch (this._fillMode) {
  36837. case Material.PointFillMode:
  36838. case Material.PointListDrawMode:
  36839. return true;
  36840. }
  36841. return this._scene.forcePointsCloud;
  36842. },
  36843. /**
  36844. * Sets the state of point cloud mode
  36845. */
  36846. set: function (value) {
  36847. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  36848. },
  36849. enumerable: true,
  36850. configurable: true
  36851. });
  36852. Object.defineProperty(Material.prototype, "fillMode", {
  36853. /**
  36854. * Gets the material fill mode
  36855. */
  36856. get: function () {
  36857. return this._fillMode;
  36858. },
  36859. /**
  36860. * Sets the material fill mode
  36861. */
  36862. set: function (value) {
  36863. if (this._fillMode === value) {
  36864. return;
  36865. }
  36866. this._fillMode = value;
  36867. this.markAsDirty(Material.MiscDirtyFlag);
  36868. },
  36869. enumerable: true,
  36870. configurable: true
  36871. });
  36872. /**
  36873. * Returns a string representation of the current material
  36874. * @param fullDetails defines a boolean indicating which levels of logging is desired
  36875. * @returns a string with material information
  36876. */
  36877. Material.prototype.toString = function (fullDetails) {
  36878. var ret = "Name: " + this.name;
  36879. if (fullDetails) {
  36880. }
  36881. return ret;
  36882. };
  36883. /**
  36884. * Gets the class name of the material
  36885. * @returns a string with the class name of the material
  36886. */
  36887. Material.prototype.getClassName = function () {
  36888. return "Material";
  36889. };
  36890. Object.defineProperty(Material.prototype, "isFrozen", {
  36891. /**
  36892. * Specifies if updates for the material been locked
  36893. */
  36894. get: function () {
  36895. return this.checkReadyOnlyOnce;
  36896. },
  36897. enumerable: true,
  36898. configurable: true
  36899. });
  36900. /**
  36901. * Locks updates for the material
  36902. */
  36903. Material.prototype.freeze = function () {
  36904. this.checkReadyOnlyOnce = true;
  36905. };
  36906. /**
  36907. * Unlocks updates for the material
  36908. */
  36909. Material.prototype.unfreeze = function () {
  36910. this.checkReadyOnlyOnce = false;
  36911. };
  36912. /**
  36913. * Specifies if the material is ready to be used
  36914. * @param mesh defines the mesh to check
  36915. * @param useInstances specifies if instances should be used
  36916. * @returns a boolean indicating if the material is ready to be used
  36917. */
  36918. Material.prototype.isReady = function (mesh, useInstances) {
  36919. return true;
  36920. };
  36921. /**
  36922. * Specifies that the submesh is ready to be used
  36923. * @param mesh defines the mesh to check
  36924. * @param subMesh defines which submesh to check
  36925. * @param useInstances specifies that instances should be used
  36926. * @returns a boolean indicating that the submesh is ready or not
  36927. */
  36928. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36929. return false;
  36930. };
  36931. /**
  36932. * Returns the material effect
  36933. * @returns the effect associated with the material
  36934. */
  36935. Material.prototype.getEffect = function () {
  36936. return this._effect;
  36937. };
  36938. /**
  36939. * Returns the current scene
  36940. * @returns a Scene
  36941. */
  36942. Material.prototype.getScene = function () {
  36943. return this._scene;
  36944. };
  36945. /**
  36946. * Specifies if the material will require alpha blending
  36947. * @returns a boolean specifying if alpha blending is needed
  36948. */
  36949. Material.prototype.needAlphaBlending = function () {
  36950. return (this.alpha < 1.0);
  36951. };
  36952. /**
  36953. * Specifies if the mesh will require alpha blending
  36954. * @param mesh defines the mesh to check
  36955. * @returns a boolean specifying if alpha blending is needed for the mesh
  36956. */
  36957. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  36958. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  36959. };
  36960. /**
  36961. * Specifies if this material should be rendered in alpha test mode
  36962. * @returns a boolean specifying if an alpha test is needed.
  36963. */
  36964. Material.prototype.needAlphaTesting = function () {
  36965. return false;
  36966. };
  36967. /**
  36968. * Gets the texture used for the alpha test
  36969. * @returns the texture to use for alpha testing
  36970. */
  36971. Material.prototype.getAlphaTestTexture = function () {
  36972. return null;
  36973. };
  36974. /**
  36975. * Marks the material to indicate that it needs to be re-calculated
  36976. */
  36977. Material.prototype.markDirty = function () {
  36978. this._wasPreviouslyReady = false;
  36979. };
  36980. /** @hidden */
  36981. Material.prototype._preBind = function (effect, overrideOrientation) {
  36982. if (overrideOrientation === void 0) { overrideOrientation = null; }
  36983. var engine = this._scene.getEngine();
  36984. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  36985. var reverse = orientation === Material.ClockWiseSideOrientation;
  36986. engine.enableEffect(effect ? effect : this._effect);
  36987. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  36988. return reverse;
  36989. };
  36990. /**
  36991. * Binds the material to the mesh
  36992. * @param world defines the world transformation matrix
  36993. * @param mesh defines the mesh to bind the material to
  36994. */
  36995. Material.prototype.bind = function (world, mesh) {
  36996. };
  36997. /**
  36998. * Binds the submesh to the material
  36999. * @param world defines the world transformation matrix
  37000. * @param mesh defines the mesh containing the submesh
  37001. * @param subMesh defines the submesh to bind the material to
  37002. */
  37003. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37004. };
  37005. /**
  37006. * Binds the world matrix to the material
  37007. * @param world defines the world transformation matrix
  37008. */
  37009. Material.prototype.bindOnlyWorldMatrix = function (world) {
  37010. };
  37011. /**
  37012. * Binds the scene's uniform buffer to the effect.
  37013. * @param effect defines the effect to bind to the scene uniform buffer
  37014. * @param sceneUbo defines the uniform buffer storing scene data
  37015. */
  37016. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  37017. sceneUbo.bindToEffect(effect, "Scene");
  37018. };
  37019. /**
  37020. * Binds the view matrix to the effect
  37021. * @param effect defines the effect to bind the view matrix to
  37022. */
  37023. Material.prototype.bindView = function (effect) {
  37024. if (!this._useUBO) {
  37025. effect.setMatrix("view", this.getScene().getViewMatrix());
  37026. }
  37027. else {
  37028. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  37029. }
  37030. };
  37031. /**
  37032. * Binds the view projection matrix to the effect
  37033. * @param effect defines the effect to bind the view projection matrix to
  37034. */
  37035. Material.prototype.bindViewProjection = function (effect) {
  37036. if (!this._useUBO) {
  37037. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  37038. }
  37039. else {
  37040. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  37041. }
  37042. };
  37043. /**
  37044. * Specifies if material alpha testing should be turned on for the mesh
  37045. * @param mesh defines the mesh to check
  37046. */
  37047. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  37048. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  37049. };
  37050. /**
  37051. * Processes to execute after binding the material to a mesh
  37052. * @param mesh defines the rendered mesh
  37053. */
  37054. Material.prototype._afterBind = function (mesh) {
  37055. this._scene._cachedMaterial = this;
  37056. if (mesh) {
  37057. this._scene._cachedVisibility = mesh.visibility;
  37058. }
  37059. else {
  37060. this._scene._cachedVisibility = 1;
  37061. }
  37062. if (this._onBindObservable && mesh) {
  37063. this._onBindObservable.notifyObservers(mesh);
  37064. }
  37065. if (this.disableDepthWrite) {
  37066. var engine = this._scene.getEngine();
  37067. this._cachedDepthWriteState = engine.getDepthWrite();
  37068. engine.setDepthWrite(false);
  37069. }
  37070. };
  37071. /**
  37072. * Unbinds the material from the mesh
  37073. */
  37074. Material.prototype.unbind = function () {
  37075. if (this._onUnBindObservable) {
  37076. this._onUnBindObservable.notifyObservers(this);
  37077. }
  37078. if (this.disableDepthWrite) {
  37079. var engine = this._scene.getEngine();
  37080. engine.setDepthWrite(this._cachedDepthWriteState);
  37081. }
  37082. };
  37083. /**
  37084. * Gets the active textures from the material
  37085. * @returns an array of textures
  37086. */
  37087. Material.prototype.getActiveTextures = function () {
  37088. return [];
  37089. };
  37090. /**
  37091. * Specifies if the material uses a texture
  37092. * @param texture defines the texture to check against the material
  37093. * @returns a boolean specifying if the material uses the texture
  37094. */
  37095. Material.prototype.hasTexture = function (texture) {
  37096. return false;
  37097. };
  37098. /**
  37099. * Makes a duplicate of the material, and gives it a new name
  37100. * @param name defines the new name for the duplicated material
  37101. * @returns the cloned material
  37102. */
  37103. Material.prototype.clone = function (name) {
  37104. return null;
  37105. };
  37106. /**
  37107. * Gets the meshes bound to the material
  37108. * @returns an array of meshes bound to the material
  37109. */
  37110. Material.prototype.getBindedMeshes = function () {
  37111. var _this = this;
  37112. if (this.meshMap) {
  37113. var result = new Array();
  37114. for (var meshId in this.meshMap) {
  37115. var mesh = this.meshMap[meshId];
  37116. if (mesh) {
  37117. result.push(mesh);
  37118. }
  37119. }
  37120. return result;
  37121. }
  37122. else {
  37123. var meshes = this._scene.meshes;
  37124. return meshes.filter(function (mesh) { return mesh.material === _this; });
  37125. }
  37126. };
  37127. /**
  37128. * Force shader compilation
  37129. * @param mesh defines the mesh associated with this material
  37130. * @param onCompiled defines a function to execute once the material is compiled
  37131. * @param options defines the options to configure the compilation
  37132. */
  37133. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  37134. var _this = this;
  37135. var localOptions = __assign({ clipPlane: false }, options);
  37136. var subMesh = new BABYLON.BaseSubMesh();
  37137. var scene = this.getScene();
  37138. var checkReady = function () {
  37139. if (!_this._scene || !_this._scene.getEngine()) {
  37140. return;
  37141. }
  37142. if (subMesh._materialDefines) {
  37143. subMesh._materialDefines._renderId = -1;
  37144. }
  37145. var clipPlaneState = scene.clipPlane;
  37146. if (localOptions.clipPlane) {
  37147. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  37148. }
  37149. if (_this._storeEffectOnSubMeshes) {
  37150. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  37151. if (onCompiled) {
  37152. onCompiled(_this);
  37153. }
  37154. }
  37155. else {
  37156. setTimeout(checkReady, 16);
  37157. }
  37158. }
  37159. else {
  37160. if (_this.isReady(mesh)) {
  37161. if (onCompiled) {
  37162. onCompiled(_this);
  37163. }
  37164. }
  37165. else {
  37166. setTimeout(checkReady, 16);
  37167. }
  37168. }
  37169. if (localOptions.clipPlane) {
  37170. scene.clipPlane = clipPlaneState;
  37171. }
  37172. };
  37173. checkReady();
  37174. };
  37175. /**
  37176. * Force shader compilation
  37177. * @param mesh defines the mesh that will use this material
  37178. * @param options defines additional options for compiling the shaders
  37179. * @returns a promise that resolves when the compilation completes
  37180. */
  37181. Material.prototype.forceCompilationAsync = function (mesh, options) {
  37182. var _this = this;
  37183. return new Promise(function (resolve) {
  37184. _this.forceCompilation(mesh, function () {
  37185. resolve();
  37186. }, options);
  37187. });
  37188. };
  37189. /**
  37190. * Marks a define in the material to indicate that it needs to be re-computed
  37191. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  37192. */
  37193. Material.prototype.markAsDirty = function (flag) {
  37194. if (this.getScene().blockMaterialDirtyMechanism) {
  37195. return;
  37196. }
  37197. Material._DirtyCallbackArray.length = 0;
  37198. if (flag & Material.TextureDirtyFlag) {
  37199. Material._DirtyCallbackArray.push(Material._TextureDirtyCallBack);
  37200. }
  37201. if (flag & Material.LightDirtyFlag) {
  37202. Material._DirtyCallbackArray.push(Material._LightsDirtyCallBack);
  37203. }
  37204. if (flag & Material.FresnelDirtyFlag) {
  37205. Material._DirtyCallbackArray.push(Material._FresnelDirtyCallBack);
  37206. }
  37207. if (flag & Material.AttributesDirtyFlag) {
  37208. Material._DirtyCallbackArray.push(Material._AttributeDirtyCallBack);
  37209. }
  37210. if (flag & Material.MiscDirtyFlag) {
  37211. Material._DirtyCallbackArray.push(Material._MiscDirtyCallBack);
  37212. }
  37213. if (Material._DirtyCallbackArray.length) {
  37214. this._markAllSubMeshesAsDirty(Material._RunDirtyCallBacks);
  37215. }
  37216. this.getScene().resetCachedMaterial();
  37217. };
  37218. /**
  37219. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  37220. * @param func defines a function which checks material defines against the submeshes
  37221. */
  37222. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  37223. if (this.getScene().blockMaterialDirtyMechanism) {
  37224. return;
  37225. }
  37226. var meshes = this.getScene().meshes;
  37227. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  37228. var mesh = meshes_1[_i];
  37229. if (!mesh.subMeshes) {
  37230. continue;
  37231. }
  37232. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  37233. var subMesh = _b[_a];
  37234. if (subMesh.getMaterial() !== this) {
  37235. continue;
  37236. }
  37237. if (!subMesh._materialDefines) {
  37238. continue;
  37239. }
  37240. func(subMesh._materialDefines);
  37241. }
  37242. }
  37243. };
  37244. /**
  37245. * Indicates that image processing needs to be re-calculated for all submeshes
  37246. */
  37247. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  37248. this._markAllSubMeshesAsDirty(Material._ImageProcessingDirtyCallBack);
  37249. };
  37250. /**
  37251. * Indicates that textures need to be re-calculated for all submeshes
  37252. */
  37253. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  37254. this._markAllSubMeshesAsDirty(Material._TextureDirtyCallBack);
  37255. };
  37256. /**
  37257. * Indicates that fresnel needs to be re-calculated for all submeshes
  37258. */
  37259. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  37260. this._markAllSubMeshesAsDirty(Material._FresnelDirtyCallBack);
  37261. };
  37262. /**
  37263. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  37264. */
  37265. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  37266. this._markAllSubMeshesAsDirty(Material._FresnelAndMiscDirtyCallBack);
  37267. };
  37268. /**
  37269. * Indicates that lights need to be re-calculated for all submeshes
  37270. */
  37271. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  37272. this._markAllSubMeshesAsDirty(Material._LightsDirtyCallBack);
  37273. };
  37274. /**
  37275. * Indicates that attributes need to be re-calculated for all submeshes
  37276. */
  37277. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  37278. this._markAllSubMeshesAsDirty(Material._AttributeDirtyCallBack);
  37279. };
  37280. /**
  37281. * Indicates that misc needs to be re-calculated for all submeshes
  37282. */
  37283. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  37284. this._markAllSubMeshesAsDirty(Material._MiscDirtyCallBack);
  37285. };
  37286. /**
  37287. * Indicates that textures and misc need to be re-calculated for all submeshes
  37288. */
  37289. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  37290. this._markAllSubMeshesAsDirty(Material._TextureAndMiscDirtyCallBack);
  37291. };
  37292. /**
  37293. * Disposes the material
  37294. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  37295. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  37296. * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh
  37297. */
  37298. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {
  37299. var scene = this.getScene();
  37300. // Animations
  37301. scene.stopAnimation(this);
  37302. scene.freeProcessedMaterials();
  37303. // Remove from scene
  37304. scene.removeMaterial(this);
  37305. if (notBoundToMesh !== true) {
  37306. // Remove from meshes
  37307. if (this.meshMap) {
  37308. for (var meshId in this.meshMap) {
  37309. var mesh = this.meshMap[meshId];
  37310. if (mesh) {
  37311. mesh.material = null; // will set the entry in the map to undefined
  37312. this.releaseVertexArrayObject(mesh, forceDisposeEffect);
  37313. }
  37314. }
  37315. }
  37316. else {
  37317. var meshes = scene.meshes;
  37318. for (var _i = 0, meshes_2 = meshes; _i < meshes_2.length; _i++) {
  37319. var mesh = meshes_2[_i];
  37320. if (mesh.material === this) {
  37321. mesh.material = null;
  37322. this.releaseVertexArrayObject(mesh, forceDisposeEffect);
  37323. }
  37324. }
  37325. }
  37326. }
  37327. this._uniformBuffer.dispose();
  37328. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  37329. if (forceDisposeEffect && this._effect) {
  37330. if (!this._storeEffectOnSubMeshes) {
  37331. scene.getEngine()._releaseEffect(this._effect);
  37332. }
  37333. this._effect = null;
  37334. }
  37335. // Callback
  37336. this.onDisposeObservable.notifyObservers(this);
  37337. this.onDisposeObservable.clear();
  37338. if (this._onBindObservable) {
  37339. this._onBindObservable.clear();
  37340. }
  37341. if (this._onUnBindObservable) {
  37342. this._onUnBindObservable.clear();
  37343. }
  37344. };
  37345. /** @hidden */
  37346. Material.prototype.releaseVertexArrayObject = function (mesh, forceDisposeEffect) {
  37347. if (mesh.geometry) {
  37348. var geometry = (mesh.geometry);
  37349. var scene = this.getScene();
  37350. if (this._storeEffectOnSubMeshes) {
  37351. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  37352. var subMesh = _a[_i];
  37353. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  37354. if (forceDisposeEffect && subMesh._materialEffect) {
  37355. scene.getEngine()._releaseEffect(subMesh._materialEffect);
  37356. }
  37357. }
  37358. }
  37359. else {
  37360. geometry._releaseVertexArrayObject(this._effect);
  37361. }
  37362. }
  37363. };
  37364. /**
  37365. * Serializes this material
  37366. * @returns the serialized material object
  37367. */
  37368. Material.prototype.serialize = function () {
  37369. return BABYLON.SerializationHelper.Serialize(this);
  37370. };
  37371. /**
  37372. * Creates a MultiMaterial from parsed MultiMaterial data.
  37373. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  37374. * @param scene defines the hosting scene
  37375. * @returns a new MultiMaterial
  37376. */
  37377. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  37378. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  37379. multiMaterial.id = parsedMultiMaterial.id;
  37380. if (BABYLON.Tags) {
  37381. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  37382. }
  37383. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  37384. var subMatId = parsedMultiMaterial.materials[matIndex];
  37385. if (subMatId) {
  37386. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  37387. }
  37388. else {
  37389. multiMaterial.subMaterials.push(null);
  37390. }
  37391. }
  37392. return multiMaterial;
  37393. };
  37394. /**
  37395. * Creates a material from parsed material data
  37396. * @param parsedMaterial defines parsed material data
  37397. * @param scene defines the hosting scene
  37398. * @param rootUrl defines the root URL to use to load textures
  37399. * @returns a new material
  37400. */
  37401. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  37402. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  37403. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  37404. }
  37405. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  37406. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  37407. if (!BABYLON.LegacyPBRMaterial) {
  37408. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  37409. return;
  37410. }
  37411. }
  37412. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  37413. return materialType.Parse(parsedMaterial, scene, rootUrl);
  37414. };
  37415. // Triangle views
  37416. Material._TriangleFillMode = 0;
  37417. Material._WireFrameFillMode = 1;
  37418. Material._PointFillMode = 2;
  37419. // Draw modes
  37420. Material._PointListDrawMode = 3;
  37421. Material._LineListDrawMode = 4;
  37422. Material._LineLoopDrawMode = 5;
  37423. Material._LineStripDrawMode = 6;
  37424. Material._TriangleStripDrawMode = 7;
  37425. Material._TriangleFanDrawMode = 8;
  37426. /**
  37427. * Stores the clock-wise side orientation
  37428. */
  37429. Material._ClockWiseSideOrientation = 0;
  37430. /**
  37431. * Stores the counter clock-wise side orientation
  37432. */
  37433. Material._CounterClockWiseSideOrientation = 1;
  37434. /**
  37435. * The dirty texture flag value
  37436. */
  37437. Material.TextureDirtyFlag = 1;
  37438. /**
  37439. * The dirty light flag value
  37440. */
  37441. Material.LightDirtyFlag = 2;
  37442. /**
  37443. * The dirty fresnel flag value
  37444. */
  37445. Material.FresnelDirtyFlag = 4;
  37446. /**
  37447. * The dirty attribute flag value
  37448. */
  37449. Material.AttributesDirtyFlag = 8;
  37450. /**
  37451. * The dirty misc flag value
  37452. */
  37453. Material.MiscDirtyFlag = 16;
  37454. /**
  37455. * The all dirty flag value
  37456. */
  37457. Material.AllDirtyFlag = 31;
  37458. Material._ImageProcessingDirtyCallBack = function (defines) { return defines.markAsImageProcessingDirty(); };
  37459. Material._TextureDirtyCallBack = function (defines) { return defines.markAsTexturesDirty(); };
  37460. Material._FresnelDirtyCallBack = function (defines) { return defines.markAsFresnelDirty(); };
  37461. Material._MiscDirtyCallBack = function (defines) { return defines.markAsMiscDirty(); };
  37462. Material._LightsDirtyCallBack = function (defines) { return defines.markAsLightDirty(); };
  37463. Material._AttributeDirtyCallBack = function (defines) { return defines.markAsAttributesDirty(); };
  37464. Material._FresnelAndMiscDirtyCallBack = function (defines) {
  37465. Material._FresnelDirtyCallBack(defines);
  37466. Material._MiscDirtyCallBack(defines);
  37467. };
  37468. Material._TextureAndMiscDirtyCallBack = function (defines) {
  37469. Material._TextureDirtyCallBack(defines);
  37470. Material._MiscDirtyCallBack(defines);
  37471. };
  37472. Material._DirtyCallbackArray = [];
  37473. Material._RunDirtyCallBacks = function (defines) {
  37474. for (var _i = 0, _a = Material._DirtyCallbackArray; _i < _a.length; _i++) {
  37475. var cb = _a[_i];
  37476. cb(defines);
  37477. }
  37478. };
  37479. __decorate([
  37480. BABYLON.serialize()
  37481. ], Material.prototype, "id", void 0);
  37482. __decorate([
  37483. BABYLON.serialize()
  37484. ], Material.prototype, "uniqueId", void 0);
  37485. __decorate([
  37486. BABYLON.serialize()
  37487. ], Material.prototype, "name", void 0);
  37488. __decorate([
  37489. BABYLON.serialize()
  37490. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  37491. __decorate([
  37492. BABYLON.serialize()
  37493. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  37494. __decorate([
  37495. BABYLON.serialize()
  37496. ], Material.prototype, "state", void 0);
  37497. __decorate([
  37498. BABYLON.serialize("alpha")
  37499. ], Material.prototype, "_alpha", void 0);
  37500. __decorate([
  37501. BABYLON.serialize("backFaceCulling")
  37502. ], Material.prototype, "_backFaceCulling", void 0);
  37503. __decorate([
  37504. BABYLON.serialize()
  37505. ], Material.prototype, "sideOrientation", void 0);
  37506. __decorate([
  37507. BABYLON.serialize("alphaMode")
  37508. ], Material.prototype, "_alphaMode", void 0);
  37509. __decorate([
  37510. BABYLON.serialize()
  37511. ], Material.prototype, "_needDepthPrePass", void 0);
  37512. __decorate([
  37513. BABYLON.serialize()
  37514. ], Material.prototype, "disableDepthWrite", void 0);
  37515. __decorate([
  37516. BABYLON.serialize()
  37517. ], Material.prototype, "forceDepthWrite", void 0);
  37518. __decorate([
  37519. BABYLON.serialize()
  37520. ], Material.prototype, "separateCullingPass", void 0);
  37521. __decorate([
  37522. BABYLON.serialize("fogEnabled")
  37523. ], Material.prototype, "_fogEnabled", void 0);
  37524. __decorate([
  37525. BABYLON.serialize()
  37526. ], Material.prototype, "pointSize", void 0);
  37527. __decorate([
  37528. BABYLON.serialize()
  37529. ], Material.prototype, "zOffset", void 0);
  37530. __decorate([
  37531. BABYLON.serialize()
  37532. ], Material.prototype, "wireframe", null);
  37533. __decorate([
  37534. BABYLON.serialize()
  37535. ], Material.prototype, "pointsCloud", null);
  37536. __decorate([
  37537. BABYLON.serialize()
  37538. ], Material.prototype, "fillMode", null);
  37539. return Material;
  37540. }());
  37541. BABYLON.Material = Material;
  37542. })(BABYLON || (BABYLON = {}));
  37543. //# sourceMappingURL=material.js.map
  37544. var BABYLON;
  37545. (function (BABYLON) {
  37546. /**
  37547. * Uniform buffer objects.
  37548. *
  37549. * Handles blocks of uniform on the GPU.
  37550. *
  37551. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37552. *
  37553. * For more information, please refer to :
  37554. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37555. */
  37556. var UniformBuffer = /** @class */ (function () {
  37557. /**
  37558. * Instantiates a new Uniform buffer objects.
  37559. *
  37560. * Handles blocks of uniform on the GPU.
  37561. *
  37562. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37563. *
  37564. * For more information, please refer to :
  37565. * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37566. * @param engine Define the engine the buffer is associated with
  37567. * @param data Define the data contained in the buffer
  37568. * @param dynamic Define if the buffer is updatable
  37569. */
  37570. function UniformBuffer(engine, data, dynamic) {
  37571. this._engine = engine;
  37572. this._noUBO = !engine.supportsUniformBuffers;
  37573. this._dynamic = dynamic;
  37574. this._data = data || [];
  37575. this._uniformLocations = {};
  37576. this._uniformSizes = {};
  37577. this._uniformLocationPointer = 0;
  37578. this._needSync = false;
  37579. if (this._noUBO) {
  37580. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  37581. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  37582. this.updateFloat = this._updateFloatForEffect;
  37583. this.updateFloat2 = this._updateFloat2ForEffect;
  37584. this.updateFloat3 = this._updateFloat3ForEffect;
  37585. this.updateFloat4 = this._updateFloat4ForEffect;
  37586. this.updateMatrix = this._updateMatrixForEffect;
  37587. this.updateVector3 = this._updateVector3ForEffect;
  37588. this.updateVector4 = this._updateVector4ForEffect;
  37589. this.updateColor3 = this._updateColor3ForEffect;
  37590. this.updateColor4 = this._updateColor4ForEffect;
  37591. }
  37592. else {
  37593. this._engine._uniformBuffers.push(this);
  37594. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  37595. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  37596. this.updateFloat = this._updateFloatForUniform;
  37597. this.updateFloat2 = this._updateFloat2ForUniform;
  37598. this.updateFloat3 = this._updateFloat3ForUniform;
  37599. this.updateFloat4 = this._updateFloat4ForUniform;
  37600. this.updateMatrix = this._updateMatrixForUniform;
  37601. this.updateVector3 = this._updateVector3ForUniform;
  37602. this.updateVector4 = this._updateVector4ForUniform;
  37603. this.updateColor3 = this._updateColor3ForUniform;
  37604. this.updateColor4 = this._updateColor4ForUniform;
  37605. }
  37606. }
  37607. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  37608. /**
  37609. * Indicates if the buffer is using the WebGL2 UBO implementation,
  37610. * or just falling back on setUniformXXX calls.
  37611. */
  37612. get: function () {
  37613. return !this._noUBO;
  37614. },
  37615. enumerable: true,
  37616. configurable: true
  37617. });
  37618. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  37619. /**
  37620. * Indicates if the WebGL underlying uniform buffer is in sync
  37621. * with the javascript cache data.
  37622. */
  37623. get: function () {
  37624. return !this._needSync;
  37625. },
  37626. enumerable: true,
  37627. configurable: true
  37628. });
  37629. /**
  37630. * Indicates if the WebGL underlying uniform buffer is dynamic.
  37631. * Also, a dynamic UniformBuffer will disable cache verification and always
  37632. * update the underlying WebGL uniform buffer to the GPU.
  37633. * @returns if Dynamic, otherwise false
  37634. */
  37635. UniformBuffer.prototype.isDynamic = function () {
  37636. return this._dynamic !== undefined;
  37637. };
  37638. /**
  37639. * The data cache on JS side.
  37640. * @returns the underlying data as a float array
  37641. */
  37642. UniformBuffer.prototype.getData = function () {
  37643. return this._bufferData;
  37644. };
  37645. /**
  37646. * The underlying WebGL Uniform buffer.
  37647. * @returns the webgl buffer
  37648. */
  37649. UniformBuffer.prototype.getBuffer = function () {
  37650. return this._buffer;
  37651. };
  37652. /**
  37653. * std140 layout specifies how to align data within an UBO structure.
  37654. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  37655. * for specs.
  37656. */
  37657. UniformBuffer.prototype._fillAlignment = function (size) {
  37658. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  37659. // and 4x4 matrices
  37660. // TODO : change if other types are used
  37661. var alignment;
  37662. if (size <= 2) {
  37663. alignment = size;
  37664. }
  37665. else {
  37666. alignment = 4;
  37667. }
  37668. if ((this._uniformLocationPointer % alignment) !== 0) {
  37669. var oldPointer = this._uniformLocationPointer;
  37670. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  37671. var diff = this._uniformLocationPointer - oldPointer;
  37672. for (var i = 0; i < diff; i++) {
  37673. this._data.push(0);
  37674. }
  37675. }
  37676. };
  37677. /**
  37678. * Adds an uniform in the buffer.
  37679. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  37680. * for the layout to be correct !
  37681. * @param name Name of the uniform, as used in the uniform block in the shader.
  37682. * @param size Data size, or data directly.
  37683. */
  37684. UniformBuffer.prototype.addUniform = function (name, size) {
  37685. if (this._noUBO) {
  37686. return;
  37687. }
  37688. if (this._uniformLocations[name] !== undefined) {
  37689. // Already existing uniform
  37690. return;
  37691. }
  37692. // This function must be called in the order of the shader layout !
  37693. // size can be the size of the uniform, or data directly
  37694. var data;
  37695. if (size instanceof Array) {
  37696. data = size;
  37697. size = data.length;
  37698. }
  37699. else {
  37700. size = size;
  37701. data = [];
  37702. // Fill with zeros
  37703. for (var i = 0; i < size; i++) {
  37704. data.push(0);
  37705. }
  37706. }
  37707. this._fillAlignment(size);
  37708. this._uniformSizes[name] = size;
  37709. this._uniformLocations[name] = this._uniformLocationPointer;
  37710. this._uniformLocationPointer += size;
  37711. for (var i = 0; i < size; i++) {
  37712. this._data.push(data[i]);
  37713. }
  37714. this._needSync = true;
  37715. };
  37716. /**
  37717. * Adds a Matrix 4x4 to the uniform buffer.
  37718. * @param name Name of the uniform, as used in the uniform block in the shader.
  37719. * @param mat A 4x4 matrix.
  37720. */
  37721. UniformBuffer.prototype.addMatrix = function (name, mat) {
  37722. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  37723. };
  37724. /**
  37725. * Adds a vec2 to the uniform buffer.
  37726. * @param name Name of the uniform, as used in the uniform block in the shader.
  37727. * @param x Define the x component value of the vec2
  37728. * @param y Define the y component value of the vec2
  37729. */
  37730. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  37731. var temp = [x, y];
  37732. this.addUniform(name, temp);
  37733. };
  37734. /**
  37735. * Adds a vec3 to the uniform buffer.
  37736. * @param name Name of the uniform, as used in the uniform block in the shader.
  37737. * @param x Define the x component value of the vec3
  37738. * @param y Define the y component value of the vec3
  37739. * @param z Define the z component value of the vec3
  37740. */
  37741. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  37742. var temp = [x, y, z];
  37743. this.addUniform(name, temp);
  37744. };
  37745. /**
  37746. * Adds a vec3 to the uniform buffer.
  37747. * @param name Name of the uniform, as used in the uniform block in the shader.
  37748. * @param color Define the vec3 from a Color
  37749. */
  37750. UniformBuffer.prototype.addColor3 = function (name, color) {
  37751. var temp = new Array();
  37752. color.toArray(temp);
  37753. this.addUniform(name, temp);
  37754. };
  37755. /**
  37756. * Adds a vec4 to the uniform buffer.
  37757. * @param name Name of the uniform, as used in the uniform block in the shader.
  37758. * @param color Define the rgb components from a Color
  37759. * @param alpha Define the a component of the vec4
  37760. */
  37761. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  37762. var temp = new Array();
  37763. color.toArray(temp);
  37764. temp.push(alpha);
  37765. this.addUniform(name, temp);
  37766. };
  37767. /**
  37768. * Adds a vec3 to the uniform buffer.
  37769. * @param name Name of the uniform, as used in the uniform block in the shader.
  37770. * @param vector Define the vec3 components from a Vector
  37771. */
  37772. UniformBuffer.prototype.addVector3 = function (name, vector) {
  37773. var temp = new Array();
  37774. vector.toArray(temp);
  37775. this.addUniform(name, temp);
  37776. };
  37777. /**
  37778. * Adds a Matrix 3x3 to the uniform buffer.
  37779. * @param name Name of the uniform, as used in the uniform block in the shader.
  37780. */
  37781. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  37782. this.addUniform(name, 12);
  37783. };
  37784. /**
  37785. * Adds a Matrix 2x2 to the uniform buffer.
  37786. * @param name Name of the uniform, as used in the uniform block in the shader.
  37787. */
  37788. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  37789. this.addUniform(name, 8);
  37790. };
  37791. /**
  37792. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  37793. */
  37794. UniformBuffer.prototype.create = function () {
  37795. if (this._noUBO) {
  37796. return;
  37797. }
  37798. if (this._buffer) {
  37799. return; // nothing to do
  37800. }
  37801. // See spec, alignment must be filled as a vec4
  37802. this._fillAlignment(4);
  37803. this._bufferData = new Float32Array(this._data);
  37804. this._rebuild();
  37805. this._needSync = true;
  37806. };
  37807. /** @hidden */
  37808. UniformBuffer.prototype._rebuild = function () {
  37809. if (this._noUBO) {
  37810. return;
  37811. }
  37812. if (this._dynamic) {
  37813. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  37814. }
  37815. else {
  37816. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  37817. }
  37818. };
  37819. /**
  37820. * Updates the WebGL Uniform Buffer on the GPU.
  37821. * If the `dynamic` flag is set to true, no cache comparison is done.
  37822. * Otherwise, the buffer will be updated only if the cache differs.
  37823. */
  37824. UniformBuffer.prototype.update = function () {
  37825. if (!this._buffer) {
  37826. this.create();
  37827. return;
  37828. }
  37829. if (!this._dynamic && !this._needSync) {
  37830. return;
  37831. }
  37832. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  37833. this._needSync = false;
  37834. };
  37835. /**
  37836. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  37837. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37838. * @param data Define the flattened data
  37839. * @param size Define the size of the data.
  37840. */
  37841. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  37842. var location = this._uniformLocations[uniformName];
  37843. if (location === undefined) {
  37844. if (this._buffer) {
  37845. // Cannot add an uniform if the buffer is already created
  37846. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  37847. return;
  37848. }
  37849. this.addUniform(uniformName, size);
  37850. location = this._uniformLocations[uniformName];
  37851. }
  37852. if (!this._buffer) {
  37853. this.create();
  37854. }
  37855. if (!this._dynamic) {
  37856. // Cache for static uniform buffers
  37857. var changed = false;
  37858. for (var i = 0; i < size; i++) {
  37859. if (this._bufferData[location + i] !== data[i]) {
  37860. changed = true;
  37861. this._bufferData[location + i] = data[i];
  37862. }
  37863. }
  37864. this._needSync = this._needSync || changed;
  37865. }
  37866. else {
  37867. // No cache for dynamic
  37868. for (var i = 0; i < size; i++) {
  37869. this._bufferData[location + i] = data[i];
  37870. }
  37871. }
  37872. };
  37873. // Update methods
  37874. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  37875. // To match std140, matrix must be realigned
  37876. for (var i = 0; i < 3; i++) {
  37877. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  37878. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  37879. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  37880. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  37881. }
  37882. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  37883. };
  37884. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  37885. this._currentEffect.setMatrix3x3(name, matrix);
  37886. };
  37887. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  37888. this._currentEffect.setMatrix2x2(name, matrix);
  37889. };
  37890. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  37891. // To match std140, matrix must be realigned
  37892. for (var i = 0; i < 2; i++) {
  37893. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  37894. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  37895. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  37896. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  37897. }
  37898. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  37899. };
  37900. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  37901. this._currentEffect.setFloat(name, x);
  37902. };
  37903. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  37904. UniformBuffer._tempBuffer[0] = x;
  37905. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  37906. };
  37907. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  37908. if (suffix === void 0) { suffix = ""; }
  37909. this._currentEffect.setFloat2(name + suffix, x, y);
  37910. };
  37911. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  37912. if (suffix === void 0) { suffix = ""; }
  37913. UniformBuffer._tempBuffer[0] = x;
  37914. UniformBuffer._tempBuffer[1] = y;
  37915. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  37916. };
  37917. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  37918. if (suffix === void 0) { suffix = ""; }
  37919. this._currentEffect.setFloat3(name + suffix, x, y, z);
  37920. };
  37921. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  37922. if (suffix === void 0) { suffix = ""; }
  37923. UniformBuffer._tempBuffer[0] = x;
  37924. UniformBuffer._tempBuffer[1] = y;
  37925. UniformBuffer._tempBuffer[2] = z;
  37926. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37927. };
  37928. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  37929. if (suffix === void 0) { suffix = ""; }
  37930. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  37931. };
  37932. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  37933. if (suffix === void 0) { suffix = ""; }
  37934. UniformBuffer._tempBuffer[0] = x;
  37935. UniformBuffer._tempBuffer[1] = y;
  37936. UniformBuffer._tempBuffer[2] = z;
  37937. UniformBuffer._tempBuffer[3] = w;
  37938. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37939. };
  37940. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  37941. this._currentEffect.setMatrix(name, mat);
  37942. };
  37943. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  37944. this.updateUniform(name, mat.toArray(), 16);
  37945. };
  37946. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  37947. this._currentEffect.setVector3(name, vector);
  37948. };
  37949. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  37950. vector.toArray(UniformBuffer._tempBuffer);
  37951. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37952. };
  37953. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  37954. this._currentEffect.setVector4(name, vector);
  37955. };
  37956. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  37957. vector.toArray(UniformBuffer._tempBuffer);
  37958. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37959. };
  37960. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  37961. if (suffix === void 0) { suffix = ""; }
  37962. this._currentEffect.setColor3(name + suffix, color);
  37963. };
  37964. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  37965. if (suffix === void 0) { suffix = ""; }
  37966. color.toArray(UniformBuffer._tempBuffer);
  37967. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37968. };
  37969. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  37970. if (suffix === void 0) { suffix = ""; }
  37971. this._currentEffect.setColor4(name + suffix, color, alpha);
  37972. };
  37973. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  37974. if (suffix === void 0) { suffix = ""; }
  37975. color.toArray(UniformBuffer._tempBuffer);
  37976. UniformBuffer._tempBuffer[3] = alpha;
  37977. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37978. };
  37979. /**
  37980. * Sets a sampler uniform on the effect.
  37981. * @param name Define the name of the sampler.
  37982. * @param texture Define the texture to set in the sampler
  37983. */
  37984. UniformBuffer.prototype.setTexture = function (name, texture) {
  37985. this._currentEffect.setTexture(name, texture);
  37986. };
  37987. /**
  37988. * Directly updates the value of the uniform in the cache AND on the GPU.
  37989. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37990. * @param data Define the flattened data
  37991. */
  37992. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  37993. this.updateUniform(uniformName, data, data.length);
  37994. this.update();
  37995. };
  37996. /**
  37997. * Binds this uniform buffer to an effect.
  37998. * @param effect Define the effect to bind the buffer to
  37999. * @param name Name of the uniform block in the shader.
  38000. */
  38001. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  38002. this._currentEffect = effect;
  38003. if (this._noUBO || !this._buffer) {
  38004. return;
  38005. }
  38006. effect.bindUniformBuffer(this._buffer, name);
  38007. };
  38008. /**
  38009. * Disposes the uniform buffer.
  38010. */
  38011. UniformBuffer.prototype.dispose = function () {
  38012. if (this._noUBO) {
  38013. return;
  38014. }
  38015. var uniformBuffers = this._engine._uniformBuffers;
  38016. var index = uniformBuffers.indexOf(this);
  38017. if (index !== -1) {
  38018. uniformBuffers[index] = uniformBuffers[uniformBuffers.length - 1];
  38019. uniformBuffers.pop();
  38020. }
  38021. if (!this._buffer) {
  38022. return;
  38023. }
  38024. if (this._engine._releaseBuffer(this._buffer)) {
  38025. this._buffer = null;
  38026. }
  38027. };
  38028. // Pool for avoiding memory leaks
  38029. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  38030. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  38031. return UniformBuffer;
  38032. }());
  38033. BABYLON.UniformBuffer = UniformBuffer;
  38034. })(BABYLON || (BABYLON = {}));
  38035. //# sourceMappingURL=uniformBuffer.js.map
  38036. var BABYLON;
  38037. (function (BABYLON) {
  38038. /**
  38039. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  38040. */
  38041. var VertexData = /** @class */ (function () {
  38042. function VertexData() {
  38043. }
  38044. /**
  38045. * Uses the passed data array to set the set the values for the specified kind of data
  38046. * @param data a linear array of floating numbers
  38047. * @param kind the type of data that is being set, eg positions, colors etc
  38048. */
  38049. VertexData.prototype.set = function (data, kind) {
  38050. switch (kind) {
  38051. case BABYLON.VertexBuffer.PositionKind:
  38052. this.positions = data;
  38053. break;
  38054. case BABYLON.VertexBuffer.NormalKind:
  38055. this.normals = data;
  38056. break;
  38057. case BABYLON.VertexBuffer.TangentKind:
  38058. this.tangents = data;
  38059. break;
  38060. case BABYLON.VertexBuffer.UVKind:
  38061. this.uvs = data;
  38062. break;
  38063. case BABYLON.VertexBuffer.UV2Kind:
  38064. this.uvs2 = data;
  38065. break;
  38066. case BABYLON.VertexBuffer.UV3Kind:
  38067. this.uvs3 = data;
  38068. break;
  38069. case BABYLON.VertexBuffer.UV4Kind:
  38070. this.uvs4 = data;
  38071. break;
  38072. case BABYLON.VertexBuffer.UV5Kind:
  38073. this.uvs5 = data;
  38074. break;
  38075. case BABYLON.VertexBuffer.UV6Kind:
  38076. this.uvs6 = data;
  38077. break;
  38078. case BABYLON.VertexBuffer.ColorKind:
  38079. this.colors = data;
  38080. break;
  38081. case BABYLON.VertexBuffer.MatricesIndicesKind:
  38082. this.matricesIndices = data;
  38083. break;
  38084. case BABYLON.VertexBuffer.MatricesWeightsKind:
  38085. this.matricesWeights = data;
  38086. break;
  38087. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  38088. this.matricesIndicesExtra = data;
  38089. break;
  38090. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  38091. this.matricesWeightsExtra = data;
  38092. break;
  38093. }
  38094. };
  38095. /**
  38096. * Associates the vertexData to the passed Mesh.
  38097. * Sets it as updatable or not (default `false`)
  38098. * @param mesh the mesh the vertexData is applied to
  38099. * @param updatable when used and having the value true allows new data to update the vertexData
  38100. * @returns the VertexData
  38101. */
  38102. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  38103. this._applyTo(mesh, updatable);
  38104. return this;
  38105. };
  38106. /**
  38107. * Associates the vertexData to the passed Geometry.
  38108. * Sets it as updatable or not (default `false`)
  38109. * @param geometry the geometry the vertexData is applied to
  38110. * @param updatable when used and having the value true allows new data to update the vertexData
  38111. * @returns VertexData
  38112. */
  38113. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  38114. this._applyTo(geometry, updatable);
  38115. return this;
  38116. };
  38117. /**
  38118. * Updates the associated mesh
  38119. * @param mesh the mesh to be updated
  38120. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  38121. * @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
  38122. * @returns VertexData
  38123. */
  38124. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  38125. this._update(mesh);
  38126. return this;
  38127. };
  38128. /**
  38129. * Updates the associated geometry
  38130. * @param geometry the geometry to be updated
  38131. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  38132. * @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
  38133. * @returns VertexData.
  38134. */
  38135. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  38136. this._update(geometry);
  38137. return this;
  38138. };
  38139. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  38140. if (updatable === void 0) { updatable = false; }
  38141. if (this.positions) {
  38142. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  38143. }
  38144. if (this.normals) {
  38145. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  38146. }
  38147. if (this.tangents) {
  38148. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  38149. }
  38150. if (this.uvs) {
  38151. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  38152. }
  38153. if (this.uvs2) {
  38154. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  38155. }
  38156. if (this.uvs3) {
  38157. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  38158. }
  38159. if (this.uvs4) {
  38160. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  38161. }
  38162. if (this.uvs5) {
  38163. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  38164. }
  38165. if (this.uvs6) {
  38166. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  38167. }
  38168. if (this.colors) {
  38169. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  38170. }
  38171. if (this.matricesIndices) {
  38172. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  38173. }
  38174. if (this.matricesWeights) {
  38175. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  38176. }
  38177. if (this.matricesIndicesExtra) {
  38178. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  38179. }
  38180. if (this.matricesWeightsExtra) {
  38181. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  38182. }
  38183. if (this.indices) {
  38184. meshOrGeometry.setIndices(this.indices, null, updatable);
  38185. }
  38186. else {
  38187. meshOrGeometry.setIndices([], null);
  38188. }
  38189. return this;
  38190. };
  38191. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  38192. if (this.positions) {
  38193. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  38194. }
  38195. if (this.normals) {
  38196. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  38197. }
  38198. if (this.tangents) {
  38199. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  38200. }
  38201. if (this.uvs) {
  38202. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  38203. }
  38204. if (this.uvs2) {
  38205. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  38206. }
  38207. if (this.uvs3) {
  38208. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  38209. }
  38210. if (this.uvs4) {
  38211. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  38212. }
  38213. if (this.uvs5) {
  38214. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  38215. }
  38216. if (this.uvs6) {
  38217. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  38218. }
  38219. if (this.colors) {
  38220. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  38221. }
  38222. if (this.matricesIndices) {
  38223. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  38224. }
  38225. if (this.matricesWeights) {
  38226. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  38227. }
  38228. if (this.matricesIndicesExtra) {
  38229. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  38230. }
  38231. if (this.matricesWeightsExtra) {
  38232. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  38233. }
  38234. if (this.indices) {
  38235. meshOrGeometry.setIndices(this.indices, null);
  38236. }
  38237. return this;
  38238. };
  38239. /**
  38240. * Transforms each position and each normal of the vertexData according to the passed Matrix
  38241. * @param matrix the transforming matrix
  38242. * @returns the VertexData
  38243. */
  38244. VertexData.prototype.transform = function (matrix) {
  38245. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  38246. var transformed = BABYLON.Vector3.Zero();
  38247. var index;
  38248. if (this.positions) {
  38249. var position = BABYLON.Vector3.Zero();
  38250. for (index = 0; index < this.positions.length; index += 3) {
  38251. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  38252. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  38253. this.positions[index] = transformed.x;
  38254. this.positions[index + 1] = transformed.y;
  38255. this.positions[index + 2] = transformed.z;
  38256. }
  38257. }
  38258. if (this.normals) {
  38259. var normal = BABYLON.Vector3.Zero();
  38260. for (index = 0; index < this.normals.length; index += 3) {
  38261. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  38262. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  38263. this.normals[index] = transformed.x;
  38264. this.normals[index + 1] = transformed.y;
  38265. this.normals[index + 2] = transformed.z;
  38266. }
  38267. }
  38268. if (this.tangents) {
  38269. var tangent = BABYLON.Vector4.Zero();
  38270. var tangentTransformed = BABYLON.Vector4.Zero();
  38271. for (index = 0; index < this.tangents.length; index += 4) {
  38272. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  38273. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  38274. this.tangents[index] = tangentTransformed.x;
  38275. this.tangents[index + 1] = tangentTransformed.y;
  38276. this.tangents[index + 2] = tangentTransformed.z;
  38277. this.tangents[index + 3] = tangentTransformed.w;
  38278. }
  38279. }
  38280. if (flip && this.indices) {
  38281. for (index = 0; index < this.indices.length; index += 3) {
  38282. var tmp = this.indices[index + 1];
  38283. this.indices[index + 1] = this.indices[index + 2];
  38284. this.indices[index + 2] = tmp;
  38285. }
  38286. }
  38287. return this;
  38288. };
  38289. /**
  38290. * Merges the passed VertexData into the current one
  38291. * @param other the VertexData to be merged into the current one
  38292. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  38293. * @returns the modified VertexData
  38294. */
  38295. VertexData.prototype.merge = function (other, use32BitsIndices) {
  38296. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  38297. this._validate();
  38298. other._validate();
  38299. if (!this.normals !== !other.normals ||
  38300. !this.tangents !== !other.tangents ||
  38301. !this.uvs !== !other.uvs ||
  38302. !this.uvs2 !== !other.uvs2 ||
  38303. !this.uvs3 !== !other.uvs3 ||
  38304. !this.uvs4 !== !other.uvs4 ||
  38305. !this.uvs5 !== !other.uvs5 ||
  38306. !this.uvs6 !== !other.uvs6 ||
  38307. !this.colors !== !other.colors ||
  38308. !this.matricesIndices !== !other.matricesIndices ||
  38309. !this.matricesWeights !== !other.matricesWeights ||
  38310. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  38311. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  38312. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  38313. }
  38314. if (other.indices) {
  38315. if (!this.indices) {
  38316. this.indices = [];
  38317. }
  38318. var offset = this.positions ? this.positions.length / 3 : 0;
  38319. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  38320. if (isSrcTypedArray) {
  38321. var len = this.indices.length + other.indices.length;
  38322. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  38323. temp.set(this.indices);
  38324. var decal = this.indices.length;
  38325. for (var index = 0; index < other.indices.length; index++) {
  38326. temp[decal + index] = other.indices[index] + offset;
  38327. }
  38328. this.indices = temp;
  38329. }
  38330. else {
  38331. for (var index = 0; index < other.indices.length; index++) {
  38332. this.indices.push(other.indices[index] + offset);
  38333. }
  38334. }
  38335. }
  38336. this.positions = this._mergeElement(this.positions, other.positions);
  38337. this.normals = this._mergeElement(this.normals, other.normals);
  38338. this.tangents = this._mergeElement(this.tangents, other.tangents);
  38339. this.uvs = this._mergeElement(this.uvs, other.uvs);
  38340. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  38341. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  38342. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  38343. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  38344. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  38345. this.colors = this._mergeElement(this.colors, other.colors);
  38346. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  38347. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  38348. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  38349. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  38350. return this;
  38351. };
  38352. VertexData.prototype._mergeElement = function (source, other) {
  38353. if (!source) {
  38354. return other;
  38355. }
  38356. if (!other) {
  38357. return source;
  38358. }
  38359. var len = other.length + source.length;
  38360. var isSrcTypedArray = source instanceof Float32Array;
  38361. var isOthTypedArray = other instanceof Float32Array;
  38362. // use non-loop method when the source is Float32Array
  38363. if (isSrcTypedArray) {
  38364. var ret32 = new Float32Array(len);
  38365. ret32.set(source);
  38366. ret32.set(other, source.length);
  38367. return ret32;
  38368. // source is number[], when other is also use concat
  38369. }
  38370. else if (!isOthTypedArray) {
  38371. return source.concat(other);
  38372. // source is a number[], but other is a Float32Array, loop required
  38373. }
  38374. else {
  38375. var ret = source.slice(0); // copy source to a separate array
  38376. for (var i = 0, len = other.length; i < len; i++) {
  38377. ret.push(other[i]);
  38378. }
  38379. return ret;
  38380. }
  38381. };
  38382. VertexData.prototype._validate = function () {
  38383. if (!this.positions) {
  38384. throw new Error("Positions are required");
  38385. }
  38386. var getElementCount = function (kind, values) {
  38387. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  38388. if ((values.length % stride) !== 0) {
  38389. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  38390. }
  38391. return values.length / stride;
  38392. };
  38393. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  38394. var validateElementCount = function (kind, values) {
  38395. var elementCount = getElementCount(kind, values);
  38396. if (elementCount !== positionsElementCount) {
  38397. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  38398. }
  38399. };
  38400. if (this.normals) {
  38401. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  38402. }
  38403. if (this.tangents) {
  38404. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  38405. }
  38406. if (this.uvs) {
  38407. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  38408. }
  38409. if (this.uvs2) {
  38410. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  38411. }
  38412. if (this.uvs3) {
  38413. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  38414. }
  38415. if (this.uvs4) {
  38416. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  38417. }
  38418. if (this.uvs5) {
  38419. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  38420. }
  38421. if (this.uvs6) {
  38422. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  38423. }
  38424. if (this.colors) {
  38425. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  38426. }
  38427. if (this.matricesIndices) {
  38428. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  38429. }
  38430. if (this.matricesWeights) {
  38431. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  38432. }
  38433. if (this.matricesIndicesExtra) {
  38434. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  38435. }
  38436. if (this.matricesWeightsExtra) {
  38437. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  38438. }
  38439. };
  38440. /**
  38441. * Serializes the VertexData
  38442. * @returns a serialized object
  38443. */
  38444. VertexData.prototype.serialize = function () {
  38445. var serializationObject = this.serialize();
  38446. if (this.positions) {
  38447. serializationObject.positions = this.positions;
  38448. }
  38449. if (this.normals) {
  38450. serializationObject.normals = this.normals;
  38451. }
  38452. if (this.tangents) {
  38453. serializationObject.tangents = this.tangents;
  38454. }
  38455. if (this.uvs) {
  38456. serializationObject.uvs = this.uvs;
  38457. }
  38458. if (this.uvs2) {
  38459. serializationObject.uvs2 = this.uvs2;
  38460. }
  38461. if (this.uvs3) {
  38462. serializationObject.uvs3 = this.uvs3;
  38463. }
  38464. if (this.uvs4) {
  38465. serializationObject.uvs4 = this.uvs4;
  38466. }
  38467. if (this.uvs5) {
  38468. serializationObject.uvs5 = this.uvs5;
  38469. }
  38470. if (this.uvs6) {
  38471. serializationObject.uvs6 = this.uvs6;
  38472. }
  38473. if (this.colors) {
  38474. serializationObject.colors = this.colors;
  38475. }
  38476. if (this.matricesIndices) {
  38477. serializationObject.matricesIndices = this.matricesIndices;
  38478. serializationObject.matricesIndices._isExpanded = true;
  38479. }
  38480. if (this.matricesWeights) {
  38481. serializationObject.matricesWeights = this.matricesWeights;
  38482. }
  38483. if (this.matricesIndicesExtra) {
  38484. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  38485. serializationObject.matricesIndicesExtra._isExpanded = true;
  38486. }
  38487. if (this.matricesWeightsExtra) {
  38488. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  38489. }
  38490. serializationObject.indices = this.indices;
  38491. return serializationObject;
  38492. };
  38493. // Statics
  38494. /**
  38495. * Extracts the vertexData from a mesh
  38496. * @param mesh the mesh from which to extract the VertexData
  38497. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  38498. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  38499. * @returns the object VertexData associated to the passed mesh
  38500. */
  38501. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  38502. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  38503. };
  38504. /**
  38505. * Extracts the vertexData from the geometry
  38506. * @param geometry the geometry from which to extract the VertexData
  38507. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  38508. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  38509. * @returns the object VertexData associated to the passed mesh
  38510. */
  38511. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  38512. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  38513. };
  38514. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  38515. var result = new VertexData();
  38516. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38517. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  38518. }
  38519. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38520. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  38521. }
  38522. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38523. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  38524. }
  38525. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38526. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  38527. }
  38528. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38529. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  38530. }
  38531. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38532. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  38533. }
  38534. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38535. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  38536. }
  38537. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38538. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  38539. }
  38540. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38541. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  38542. }
  38543. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38544. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  38545. }
  38546. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38547. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  38548. }
  38549. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38550. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  38551. }
  38552. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  38553. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  38554. }
  38555. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  38556. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  38557. }
  38558. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  38559. return result;
  38560. };
  38561. /**
  38562. * Creates the VertexData for a Ribbon
  38563. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  38564. * * pathArray array of paths, each of which an array of successive Vector3
  38565. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  38566. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  38567. * * 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
  38568. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38569. * * 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)
  38570. * * 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)
  38571. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  38572. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  38573. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  38574. * @returns the VertexData of the ribbon
  38575. */
  38576. VertexData.CreateRibbon = function (options) {
  38577. var pathArray = options.pathArray;
  38578. var closeArray = options.closeArray || false;
  38579. var closePath = options.closePath || false;
  38580. var invertUV = options.invertUV || false;
  38581. var defaultOffset = Math.floor(pathArray[0].length / 2);
  38582. var offset = options.offset || defaultOffset;
  38583. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  38584. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38585. var customUV = options.uvs;
  38586. var customColors = options.colors;
  38587. var positions = [];
  38588. var indices = [];
  38589. var normals = [];
  38590. var uvs = [];
  38591. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  38592. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  38593. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  38594. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  38595. var minlg; // minimal length among all paths from pathArray
  38596. var lg = []; // array of path lengths : nb of vertex per path
  38597. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  38598. var p; // path iterator
  38599. var i; // point iterator
  38600. var j; // point iterator
  38601. // if single path in pathArray
  38602. if (pathArray.length < 2) {
  38603. var ar1 = [];
  38604. var ar2 = [];
  38605. for (i = 0; i < pathArray[0].length - offset; i++) {
  38606. ar1.push(pathArray[0][i]);
  38607. ar2.push(pathArray[0][i + offset]);
  38608. }
  38609. pathArray = [ar1, ar2];
  38610. }
  38611. // positions and horizontal distances (u)
  38612. var idc = 0;
  38613. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  38614. var path;
  38615. var l;
  38616. minlg = pathArray[0].length;
  38617. var vectlg;
  38618. var dist;
  38619. for (p = 0; p < pathArray.length; p++) {
  38620. uTotalDistance[p] = 0;
  38621. us[p] = [0];
  38622. path = pathArray[p];
  38623. l = path.length;
  38624. minlg = (minlg < l) ? minlg : l;
  38625. j = 0;
  38626. while (j < l) {
  38627. positions.push(path[j].x, path[j].y, path[j].z);
  38628. if (j > 0) {
  38629. vectlg = path[j].subtract(path[j - 1]).length();
  38630. dist = vectlg + uTotalDistance[p];
  38631. us[p].push(dist);
  38632. uTotalDistance[p] = dist;
  38633. }
  38634. j++;
  38635. }
  38636. if (closePath) { // an extra hidden vertex is added in the "positions" array
  38637. j--;
  38638. positions.push(path[0].x, path[0].y, path[0].z);
  38639. vectlg = path[j].subtract(path[0]).length();
  38640. dist = vectlg + uTotalDistance[p];
  38641. us[p].push(dist);
  38642. uTotalDistance[p] = dist;
  38643. }
  38644. lg[p] = l + closePathCorr;
  38645. idx[p] = idc;
  38646. idc += (l + closePathCorr);
  38647. }
  38648. // vertical distances (v)
  38649. var path1;
  38650. var path2;
  38651. var vertex1 = null;
  38652. var vertex2 = null;
  38653. for (i = 0; i < minlg + closePathCorr; i++) {
  38654. vTotalDistance[i] = 0;
  38655. vs[i] = [0];
  38656. for (p = 0; p < pathArray.length - 1; p++) {
  38657. path1 = pathArray[p];
  38658. path2 = pathArray[p + 1];
  38659. if (i === minlg) { // closePath
  38660. vertex1 = path1[0];
  38661. vertex2 = path2[0];
  38662. }
  38663. else {
  38664. vertex1 = path1[i];
  38665. vertex2 = path2[i];
  38666. }
  38667. vectlg = vertex2.subtract(vertex1).length();
  38668. dist = vectlg + vTotalDistance[i];
  38669. vs[i].push(dist);
  38670. vTotalDistance[i] = dist;
  38671. }
  38672. if (closeArray && vertex2 && vertex1) {
  38673. path1 = pathArray[p];
  38674. path2 = pathArray[0];
  38675. if (i === minlg) { // closePath
  38676. vertex2 = path2[0];
  38677. }
  38678. vectlg = vertex2.subtract(vertex1).length();
  38679. dist = vectlg + vTotalDistance[i];
  38680. vTotalDistance[i] = dist;
  38681. }
  38682. }
  38683. // uvs
  38684. var u;
  38685. var v;
  38686. if (customUV) {
  38687. for (p = 0; p < customUV.length; p++) {
  38688. uvs.push(customUV[p].x, customUV[p].y);
  38689. }
  38690. }
  38691. else {
  38692. for (p = 0; p < pathArray.length; p++) {
  38693. for (i = 0; i < minlg + closePathCorr; i++) {
  38694. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  38695. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  38696. if (invertUV) {
  38697. uvs.push(v, u);
  38698. }
  38699. else {
  38700. uvs.push(u, v);
  38701. }
  38702. }
  38703. }
  38704. }
  38705. // indices
  38706. p = 0; // path index
  38707. var pi = 0; // positions array index
  38708. var l1 = lg[p] - 1; // path1 length
  38709. var l2 = lg[p + 1] - 1; // path2 length
  38710. var min = (l1 < l2) ? l1 : l2; // current path stop index
  38711. var shft = idx[1] - idx[0]; // shift
  38712. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  38713. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  38714. // 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
  38715. indices.push(pi, pi + shft, pi + 1);
  38716. indices.push(pi + shft + 1, pi + 1, pi + shft);
  38717. pi += 1;
  38718. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  38719. p++;
  38720. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  38721. shft = idx[0] - idx[p];
  38722. l1 = lg[p] - 1;
  38723. l2 = lg[0] - 1;
  38724. }
  38725. else {
  38726. shft = idx[p + 1] - idx[p];
  38727. l1 = lg[p] - 1;
  38728. l2 = lg[p + 1] - 1;
  38729. }
  38730. pi = idx[p];
  38731. min = (l1 < l2) ? l1 + pi : l2 + pi;
  38732. }
  38733. }
  38734. // normals
  38735. VertexData.ComputeNormals(positions, indices, normals);
  38736. if (closePath) { // update both the first and last vertex normals to their average value
  38737. var indexFirst = 0;
  38738. var indexLast = 0;
  38739. for (p = 0; p < pathArray.length; p++) {
  38740. indexFirst = idx[p] * 3;
  38741. if (p + 1 < pathArray.length) {
  38742. indexLast = (idx[p + 1] - 1) * 3;
  38743. }
  38744. else {
  38745. indexLast = normals.length - 3;
  38746. }
  38747. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  38748. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  38749. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  38750. normals[indexLast] = normals[indexFirst];
  38751. normals[indexLast + 1] = normals[indexFirst + 1];
  38752. normals[indexLast + 2] = normals[indexFirst + 2];
  38753. }
  38754. }
  38755. // sides
  38756. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38757. // Colors
  38758. var colors = null;
  38759. if (customColors) {
  38760. colors = new Float32Array(customColors.length * 4);
  38761. for (var c = 0; c < customColors.length; c++) {
  38762. colors[c * 4] = customColors[c].r;
  38763. colors[c * 4 + 1] = customColors[c].g;
  38764. colors[c * 4 + 2] = customColors[c].b;
  38765. colors[c * 4 + 3] = customColors[c].a;
  38766. }
  38767. }
  38768. // Result
  38769. var vertexData = new VertexData();
  38770. var positions32 = new Float32Array(positions);
  38771. var normals32 = new Float32Array(normals);
  38772. var uvs32 = new Float32Array(uvs);
  38773. vertexData.indices = indices;
  38774. vertexData.positions = positions32;
  38775. vertexData.normals = normals32;
  38776. vertexData.uvs = uvs32;
  38777. if (colors) {
  38778. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  38779. }
  38780. if (closePath) {
  38781. vertexData._idx = idx;
  38782. }
  38783. return vertexData;
  38784. };
  38785. /**
  38786. * Creates the VertexData for a box
  38787. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38788. * * size sets the width, height and depth of the box to the value of size, optional default 1
  38789. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  38790. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  38791. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  38792. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  38793. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  38794. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38795. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38796. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38797. * @returns the VertexData of the box
  38798. */
  38799. VertexData.CreateBox = function (options) {
  38800. var normalsSource = [
  38801. new BABYLON.Vector3(0, 0, 1),
  38802. new BABYLON.Vector3(0, 0, -1),
  38803. new BABYLON.Vector3(1, 0, 0),
  38804. new BABYLON.Vector3(-1, 0, 0),
  38805. new BABYLON.Vector3(0, 1, 0),
  38806. new BABYLON.Vector3(0, -1, 0)
  38807. ];
  38808. var indices = [];
  38809. var positions = [];
  38810. var normals = [];
  38811. var uvs = [];
  38812. var width = options.width || options.size || 1;
  38813. var height = options.height || options.size || 1;
  38814. var depth = options.depth || options.size || 1;
  38815. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38816. var faceUV = options.faceUV || new Array(6);
  38817. var faceColors = options.faceColors;
  38818. var colors = [];
  38819. // default face colors and UV if undefined
  38820. for (var f = 0; f < 6; f++) {
  38821. if (faceUV[f] === undefined) {
  38822. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38823. }
  38824. if (faceColors && faceColors[f] === undefined) {
  38825. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38826. }
  38827. }
  38828. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  38829. // Create each face in turn.
  38830. for (var index = 0; index < normalsSource.length; index++) {
  38831. var normal = normalsSource[index];
  38832. // Get two vectors perpendicular to the face normal and to each other.
  38833. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  38834. var side2 = BABYLON.Vector3.Cross(normal, side1);
  38835. // Six indices (two triangles) per face.
  38836. var verticesLength = positions.length / 3;
  38837. indices.push(verticesLength);
  38838. indices.push(verticesLength + 1);
  38839. indices.push(verticesLength + 2);
  38840. indices.push(verticesLength);
  38841. indices.push(verticesLength + 2);
  38842. indices.push(verticesLength + 3);
  38843. // Four vertices per face.
  38844. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  38845. positions.push(vertex.x, vertex.y, vertex.z);
  38846. normals.push(normal.x, normal.y, normal.z);
  38847. uvs.push(faceUV[index].z, faceUV[index].w);
  38848. if (faceColors) {
  38849. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38850. }
  38851. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  38852. positions.push(vertex.x, vertex.y, vertex.z);
  38853. normals.push(normal.x, normal.y, normal.z);
  38854. uvs.push(faceUV[index].x, faceUV[index].w);
  38855. if (faceColors) {
  38856. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38857. }
  38858. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  38859. positions.push(vertex.x, vertex.y, vertex.z);
  38860. normals.push(normal.x, normal.y, normal.z);
  38861. uvs.push(faceUV[index].x, faceUV[index].y);
  38862. if (faceColors) {
  38863. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38864. }
  38865. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  38866. positions.push(vertex.x, vertex.y, vertex.z);
  38867. normals.push(normal.x, normal.y, normal.z);
  38868. uvs.push(faceUV[index].z, faceUV[index].y);
  38869. if (faceColors) {
  38870. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38871. }
  38872. }
  38873. // sides
  38874. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38875. // Result
  38876. var vertexData = new VertexData();
  38877. vertexData.indices = indices;
  38878. vertexData.positions = positions;
  38879. vertexData.normals = normals;
  38880. vertexData.uvs = uvs;
  38881. if (faceColors) {
  38882. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38883. vertexData.colors = totalColors;
  38884. }
  38885. return vertexData;
  38886. };
  38887. /**
  38888. * Creates the VertexData for an ellipsoid, defaults to a sphere
  38889. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38890. * * segments sets the number of horizontal strips optional, default 32
  38891. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  38892. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  38893. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  38894. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  38895. * * 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
  38896. * * 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
  38897. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38898. * * 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)
  38899. * * 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)
  38900. * @returns the VertexData of the ellipsoid
  38901. */
  38902. VertexData.CreateSphere = function (options) {
  38903. var segments = options.segments || 32;
  38904. var diameterX = options.diameterX || options.diameter || 1;
  38905. var diameterY = options.diameterY || options.diameter || 1;
  38906. var diameterZ = options.diameterZ || options.diameter || 1;
  38907. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38908. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  38909. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38910. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  38911. var totalZRotationSteps = 2 + segments;
  38912. var totalYRotationSteps = 2 * totalZRotationSteps;
  38913. var indices = [];
  38914. var positions = [];
  38915. var normals = [];
  38916. var uvs = [];
  38917. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  38918. var normalizedZ = zRotationStep / totalZRotationSteps;
  38919. var angleZ = normalizedZ * Math.PI * slice;
  38920. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  38921. var normalizedY = yRotationStep / totalYRotationSteps;
  38922. var angleY = normalizedY * Math.PI * 2 * arc;
  38923. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  38924. var rotationY = BABYLON.Matrix.RotationY(angleY);
  38925. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  38926. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  38927. var vertex = complete.multiply(radius);
  38928. var normal = complete.divide(radius).normalize();
  38929. positions.push(vertex.x, vertex.y, vertex.z);
  38930. normals.push(normal.x, normal.y, normal.z);
  38931. uvs.push(normalizedY, normalizedZ);
  38932. }
  38933. if (zRotationStep > 0) {
  38934. var verticesCount = positions.length / 3;
  38935. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  38936. indices.push((firstIndex));
  38937. indices.push((firstIndex + 1));
  38938. indices.push(firstIndex + totalYRotationSteps + 1);
  38939. indices.push((firstIndex + totalYRotationSteps + 1));
  38940. indices.push((firstIndex + 1));
  38941. indices.push((firstIndex + totalYRotationSteps + 2));
  38942. }
  38943. }
  38944. }
  38945. // Sides
  38946. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38947. // Result
  38948. var vertexData = new VertexData();
  38949. vertexData.indices = indices;
  38950. vertexData.positions = positions;
  38951. vertexData.normals = normals;
  38952. vertexData.uvs = uvs;
  38953. return vertexData;
  38954. };
  38955. /**
  38956. * Creates the VertexData for a cylinder, cone or prism
  38957. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38958. * * height sets the height (y direction) of the cylinder, optional, default 2
  38959. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  38960. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  38961. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  38962. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38963. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  38964. * * 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
  38965. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38966. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38967. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  38968. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  38969. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38970. * * 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)
  38971. * * 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)
  38972. * @returns the VertexData of the cylinder, cone or prism
  38973. */
  38974. VertexData.CreateCylinder = function (options) {
  38975. var height = options.height || 2;
  38976. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  38977. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  38978. var tessellation = options.tessellation || 24;
  38979. var subdivisions = options.subdivisions || 1;
  38980. var hasRings = options.hasRings ? true : false;
  38981. var enclose = options.enclose ? true : false;
  38982. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38983. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38984. var faceUV = options.faceUV || new Array(3);
  38985. var faceColors = options.faceColors;
  38986. // default face colors and UV if undefined
  38987. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  38988. var ringNb = (hasRings) ? subdivisions : 1;
  38989. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  38990. var f;
  38991. for (f = 0; f < surfaceNb; f++) {
  38992. if (faceColors && faceColors[f] === undefined) {
  38993. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38994. }
  38995. }
  38996. for (f = 0; f < surfaceNb; f++) {
  38997. if (faceUV && faceUV[f] === undefined) {
  38998. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38999. }
  39000. }
  39001. var indices = new Array();
  39002. var positions = new Array();
  39003. var normals = new Array();
  39004. var uvs = new Array();
  39005. var colors = new Array();
  39006. var angle_step = Math.PI * 2 * arc / tessellation;
  39007. var angle;
  39008. var h;
  39009. var radius;
  39010. var tan = (diameterBottom - diameterTop) / 2 / height;
  39011. var ringVertex = BABYLON.Vector3.Zero();
  39012. var ringNormal = BABYLON.Vector3.Zero();
  39013. var ringFirstVertex = BABYLON.Vector3.Zero();
  39014. var ringFirstNormal = BABYLON.Vector3.Zero();
  39015. var quadNormal = BABYLON.Vector3.Zero();
  39016. var Y = BABYLON.Axis.Y;
  39017. // positions, normals, uvs
  39018. var i;
  39019. var j;
  39020. var r;
  39021. var ringIdx = 1;
  39022. var s = 1; // surface index
  39023. var cs = 0;
  39024. var v = 0;
  39025. for (i = 0; i <= subdivisions; i++) {
  39026. h = i / subdivisions;
  39027. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  39028. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  39029. for (r = 0; r < ringIdx; r++) {
  39030. if (hasRings) {
  39031. s += r;
  39032. }
  39033. if (enclose) {
  39034. s += 2 * r;
  39035. }
  39036. for (j = 0; j <= tessellation; j++) {
  39037. angle = j * angle_step;
  39038. // position
  39039. ringVertex.x = Math.cos(-angle) * radius;
  39040. ringVertex.y = -height / 2 + h * height;
  39041. ringVertex.z = Math.sin(-angle) * radius;
  39042. // normal
  39043. if (diameterTop === 0 && i === subdivisions) {
  39044. // if no top cap, reuse former normals
  39045. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  39046. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  39047. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  39048. }
  39049. else {
  39050. ringNormal.x = ringVertex.x;
  39051. ringNormal.z = ringVertex.z;
  39052. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  39053. ringNormal.normalize();
  39054. }
  39055. // keep first ring vertex values for enclose
  39056. if (j === 0) {
  39057. ringFirstVertex.copyFrom(ringVertex);
  39058. ringFirstNormal.copyFrom(ringNormal);
  39059. }
  39060. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  39061. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  39062. if (hasRings) {
  39063. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  39064. }
  39065. else {
  39066. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  39067. }
  39068. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  39069. if (faceColors) {
  39070. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  39071. }
  39072. }
  39073. // if enclose, add four vertices and their dedicated normals
  39074. if (arc !== 1 && enclose) {
  39075. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  39076. positions.push(0, ringVertex.y, 0);
  39077. positions.push(0, ringVertex.y, 0);
  39078. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  39079. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  39080. quadNormal.normalize();
  39081. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  39082. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  39083. quadNormal.normalize();
  39084. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  39085. if (hasRings) {
  39086. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  39087. }
  39088. else {
  39089. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  39090. }
  39091. uvs.push(faceUV[s + 1].x, v);
  39092. uvs.push(faceUV[s + 1].z, v);
  39093. if (hasRings) {
  39094. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  39095. }
  39096. else {
  39097. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  39098. }
  39099. uvs.push(faceUV[s + 2].x, v);
  39100. uvs.push(faceUV[s + 2].z, v);
  39101. if (faceColors) {
  39102. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  39103. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  39104. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  39105. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  39106. }
  39107. }
  39108. if (cs !== s) {
  39109. cs = s;
  39110. }
  39111. }
  39112. }
  39113. // indices
  39114. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  39115. var s;
  39116. i = 0;
  39117. for (s = 0; s < subdivisions; s++) {
  39118. var i0 = 0;
  39119. var i1 = 0;
  39120. var i2 = 0;
  39121. var i3 = 0;
  39122. for (j = 0; j < tessellation; j++) {
  39123. i0 = i * (e + 1) + j;
  39124. i1 = (i + 1) * (e + 1) + j;
  39125. i2 = i * (e + 1) + (j + 1);
  39126. i3 = (i + 1) * (e + 1) + (j + 1);
  39127. indices.push(i0, i1, i2);
  39128. indices.push(i3, i2, i1);
  39129. }
  39130. if (arc !== 1 && enclose) { // if enclose, add two quads
  39131. indices.push(i0 + 2, i1 + 2, i2 + 2);
  39132. indices.push(i3 + 2, i2 + 2, i1 + 2);
  39133. indices.push(i0 + 4, i1 + 4, i2 + 4);
  39134. indices.push(i3 + 4, i2 + 4, i1 + 4);
  39135. }
  39136. i = (hasRings) ? (i + 2) : (i + 1);
  39137. }
  39138. // Caps
  39139. var createCylinderCap = function (isTop) {
  39140. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  39141. if (radius === 0) {
  39142. return;
  39143. }
  39144. // Cap positions, normals & uvs
  39145. var angle;
  39146. var circleVector;
  39147. var i;
  39148. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  39149. var c = null;
  39150. if (faceColors) {
  39151. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  39152. }
  39153. // cap center
  39154. var vbase = positions.length / 3;
  39155. var offset = isTop ? height / 2 : -height / 2;
  39156. var center = new BABYLON.Vector3(0, offset, 0);
  39157. positions.push(center.x, center.y, center.z);
  39158. normals.push(0, isTop ? 1 : -1, 0);
  39159. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  39160. if (c) {
  39161. colors.push(c.r, c.g, c.b, c.a);
  39162. }
  39163. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  39164. for (i = 0; i <= tessellation; i++) {
  39165. angle = Math.PI * 2 * i * arc / tessellation;
  39166. var cos = Math.cos(-angle);
  39167. var sin = Math.sin(-angle);
  39168. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  39169. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  39170. positions.push(circleVector.x, circleVector.y, circleVector.z);
  39171. normals.push(0, isTop ? 1 : -1, 0);
  39172. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  39173. if (c) {
  39174. colors.push(c.r, c.g, c.b, c.a);
  39175. }
  39176. }
  39177. // Cap indices
  39178. for (i = 0; i < tessellation; i++) {
  39179. if (!isTop) {
  39180. indices.push(vbase);
  39181. indices.push(vbase + (i + 1));
  39182. indices.push(vbase + (i + 2));
  39183. }
  39184. else {
  39185. indices.push(vbase);
  39186. indices.push(vbase + (i + 2));
  39187. indices.push(vbase + (i + 1));
  39188. }
  39189. }
  39190. };
  39191. // add caps to geometry
  39192. createCylinderCap(false);
  39193. createCylinderCap(true);
  39194. // Sides
  39195. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39196. var vertexData = new VertexData();
  39197. vertexData.indices = indices;
  39198. vertexData.positions = positions;
  39199. vertexData.normals = normals;
  39200. vertexData.uvs = uvs;
  39201. if (faceColors) {
  39202. vertexData.colors = colors;
  39203. }
  39204. return vertexData;
  39205. };
  39206. /**
  39207. * Creates the VertexData for a torus
  39208. * @param options an object used to set the following optional parameters for the box, required but can be empty
  39209. * * diameter the diameter of the torus, optional default 1
  39210. * * thickness the diameter of the tube forming the torus, optional default 0.5
  39211. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  39212. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39213. * * 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)
  39214. * * 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)
  39215. * @returns the VertexData of the torus
  39216. */
  39217. VertexData.CreateTorus = function (options) {
  39218. var indices = [];
  39219. var positions = [];
  39220. var normals = [];
  39221. var uvs = [];
  39222. var diameter = options.diameter || 1;
  39223. var thickness = options.thickness || 0.5;
  39224. var tessellation = options.tessellation || 16;
  39225. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39226. var stride = tessellation + 1;
  39227. for (var i = 0; i <= tessellation; i++) {
  39228. var u = i / tessellation;
  39229. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  39230. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  39231. for (var j = 0; j <= tessellation; j++) {
  39232. var v = 1 - j / tessellation;
  39233. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  39234. var dx = Math.cos(innerAngle);
  39235. var dy = Math.sin(innerAngle);
  39236. // Create a vertex.
  39237. var normal = new BABYLON.Vector3(dx, dy, 0);
  39238. var position = normal.scale(thickness / 2);
  39239. var textureCoordinate = new BABYLON.Vector2(u, v);
  39240. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  39241. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  39242. positions.push(position.x, position.y, position.z);
  39243. normals.push(normal.x, normal.y, normal.z);
  39244. uvs.push(textureCoordinate.x, textureCoordinate.y);
  39245. // And create indices for two triangles.
  39246. var nextI = (i + 1) % stride;
  39247. var nextJ = (j + 1) % stride;
  39248. indices.push(i * stride + j);
  39249. indices.push(i * stride + nextJ);
  39250. indices.push(nextI * stride + j);
  39251. indices.push(i * stride + nextJ);
  39252. indices.push(nextI * stride + nextJ);
  39253. indices.push(nextI * stride + j);
  39254. }
  39255. }
  39256. // Sides
  39257. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39258. // Result
  39259. var vertexData = new VertexData();
  39260. vertexData.indices = indices;
  39261. vertexData.positions = positions;
  39262. vertexData.normals = normals;
  39263. vertexData.uvs = uvs;
  39264. return vertexData;
  39265. };
  39266. /**
  39267. * Creates the VertexData of the LineSystem
  39268. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  39269. * - lines an array of lines, each line being an array of successive Vector3
  39270. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  39271. * @returns the VertexData of the LineSystem
  39272. */
  39273. VertexData.CreateLineSystem = function (options) {
  39274. var indices = [];
  39275. var positions = [];
  39276. var lines = options.lines;
  39277. var colors = options.colors;
  39278. var vertexColors = [];
  39279. var idx = 0;
  39280. for (var l = 0; l < lines.length; l++) {
  39281. var points = lines[l];
  39282. for (var index = 0; index < points.length; index++) {
  39283. positions.push(points[index].x, points[index].y, points[index].z);
  39284. if (colors) {
  39285. var color = colors[l];
  39286. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  39287. }
  39288. if (index > 0) {
  39289. indices.push(idx - 1);
  39290. indices.push(idx);
  39291. }
  39292. idx++;
  39293. }
  39294. }
  39295. var vertexData = new VertexData();
  39296. vertexData.indices = indices;
  39297. vertexData.positions = positions;
  39298. if (colors) {
  39299. vertexData.colors = vertexColors;
  39300. }
  39301. return vertexData;
  39302. };
  39303. /**
  39304. * Create the VertexData for a DashedLines
  39305. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  39306. * - points an array successive Vector3
  39307. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  39308. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  39309. * - dashNb the intended total number of dashes, optional, default 200
  39310. * @returns the VertexData for the DashedLines
  39311. */
  39312. VertexData.CreateDashedLines = function (options) {
  39313. var dashSize = options.dashSize || 3;
  39314. var gapSize = options.gapSize || 1;
  39315. var dashNb = options.dashNb || 200;
  39316. var points = options.points;
  39317. var positions = new Array();
  39318. var indices = new Array();
  39319. var curvect = BABYLON.Vector3.Zero();
  39320. var lg = 0;
  39321. var nb = 0;
  39322. var shft = 0;
  39323. var dashshft = 0;
  39324. var curshft = 0;
  39325. var idx = 0;
  39326. var i = 0;
  39327. for (i = 0; i < points.length - 1; i++) {
  39328. points[i + 1].subtractToRef(points[i], curvect);
  39329. lg += curvect.length();
  39330. }
  39331. shft = lg / dashNb;
  39332. dashshft = dashSize * shft / (dashSize + gapSize);
  39333. for (i = 0; i < points.length - 1; i++) {
  39334. points[i + 1].subtractToRef(points[i], curvect);
  39335. nb = Math.floor(curvect.length() / shft);
  39336. curvect.normalize();
  39337. for (var j = 0; j < nb; j++) {
  39338. curshft = shft * j;
  39339. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  39340. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  39341. indices.push(idx, idx + 1);
  39342. idx += 2;
  39343. }
  39344. }
  39345. // Result
  39346. var vertexData = new VertexData();
  39347. vertexData.positions = positions;
  39348. vertexData.indices = indices;
  39349. return vertexData;
  39350. };
  39351. /**
  39352. * Creates the VertexData for a Ground
  39353. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  39354. * - width the width (x direction) of the ground, optional, default 1
  39355. * - height the height (z direction) of the ground, optional, default 1
  39356. * - subdivisions the number of subdivisions per side, optional, default 1
  39357. * @returns the VertexData of the Ground
  39358. */
  39359. VertexData.CreateGround = function (options) {
  39360. var indices = [];
  39361. var positions = [];
  39362. var normals = [];
  39363. var uvs = [];
  39364. var row, col;
  39365. var width = options.width || 1;
  39366. var height = options.height || 1;
  39367. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  39368. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  39369. for (row = 0; row <= subdivisionsY; row++) {
  39370. for (col = 0; col <= subdivisionsX; col++) {
  39371. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  39372. var normal = new BABYLON.Vector3(0, 1.0, 0);
  39373. positions.push(position.x, position.y, position.z);
  39374. normals.push(normal.x, normal.y, normal.z);
  39375. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  39376. }
  39377. }
  39378. for (row = 0; row < subdivisionsY; row++) {
  39379. for (col = 0; col < subdivisionsX; col++) {
  39380. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  39381. indices.push(col + 1 + row * (subdivisionsX + 1));
  39382. indices.push(col + row * (subdivisionsX + 1));
  39383. indices.push(col + (row + 1) * (subdivisionsX + 1));
  39384. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  39385. indices.push(col + row * (subdivisionsX + 1));
  39386. }
  39387. }
  39388. // Result
  39389. var vertexData = new VertexData();
  39390. vertexData.indices = indices;
  39391. vertexData.positions = positions;
  39392. vertexData.normals = normals;
  39393. vertexData.uvs = uvs;
  39394. return vertexData;
  39395. };
  39396. /**
  39397. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  39398. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  39399. * * xmin the ground minimum X coordinate, optional, default -1
  39400. * * zmin the ground minimum Z coordinate, optional, default -1
  39401. * * xmax the ground maximum X coordinate, optional, default 1
  39402. * * zmax the ground maximum Z coordinate, optional, default 1
  39403. * * 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}
  39404. * * 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}
  39405. * @returns the VertexData of the TiledGround
  39406. */
  39407. VertexData.CreateTiledGround = function (options) {
  39408. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  39409. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  39410. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  39411. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  39412. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  39413. var precision = options.precision || { w: 1, h: 1 };
  39414. var indices = new Array();
  39415. var positions = new Array();
  39416. var normals = new Array();
  39417. var uvs = new Array();
  39418. var row, col, tileRow, tileCol;
  39419. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  39420. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  39421. precision.w = (precision.w < 1) ? 1 : precision.w;
  39422. precision.h = (precision.h < 1) ? 1 : precision.h;
  39423. var tileSize = {
  39424. 'w': (xmax - xmin) / subdivisions.w,
  39425. 'h': (zmax - zmin) / subdivisions.h
  39426. };
  39427. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  39428. // Indices
  39429. var base = positions.length / 3;
  39430. var rowLength = precision.w + 1;
  39431. for (row = 0; row < precision.h; row++) {
  39432. for (col = 0; col < precision.w; col++) {
  39433. var square = [
  39434. base + col + row * rowLength,
  39435. base + (col + 1) + row * rowLength,
  39436. base + (col + 1) + (row + 1) * rowLength,
  39437. base + col + (row + 1) * rowLength
  39438. ];
  39439. indices.push(square[1]);
  39440. indices.push(square[2]);
  39441. indices.push(square[3]);
  39442. indices.push(square[0]);
  39443. indices.push(square[1]);
  39444. indices.push(square[3]);
  39445. }
  39446. }
  39447. // Position, normals and uvs
  39448. var position = BABYLON.Vector3.Zero();
  39449. var normal = new BABYLON.Vector3(0, 1.0, 0);
  39450. for (row = 0; row <= precision.h; row++) {
  39451. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  39452. for (col = 0; col <= precision.w; col++) {
  39453. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  39454. position.y = 0;
  39455. positions.push(position.x, position.y, position.z);
  39456. normals.push(normal.x, normal.y, normal.z);
  39457. uvs.push(col / precision.w, row / precision.h);
  39458. }
  39459. }
  39460. }
  39461. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  39462. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  39463. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  39464. }
  39465. }
  39466. // Result
  39467. var vertexData = new VertexData();
  39468. vertexData.indices = indices;
  39469. vertexData.positions = positions;
  39470. vertexData.normals = normals;
  39471. vertexData.uvs = uvs;
  39472. return vertexData;
  39473. };
  39474. /**
  39475. * Creates the VertexData of the Ground designed from a heightmap
  39476. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  39477. * * width the width (x direction) of the ground
  39478. * * height the height (z direction) of the ground
  39479. * * subdivisions the number of subdivisions per side
  39480. * * minHeight the minimum altitude on the ground, optional, default 0
  39481. * * maxHeight the maximum altitude on the ground, optional default 1
  39482. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  39483. * * buffer the array holding the image color data
  39484. * * bufferWidth the width of image
  39485. * * bufferHeight the height of image
  39486. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  39487. * @returns the VertexData of the Ground designed from a heightmap
  39488. */
  39489. VertexData.CreateGroundFromHeightMap = function (options) {
  39490. var indices = [];
  39491. var positions = [];
  39492. var normals = [];
  39493. var uvs = [];
  39494. var row, col;
  39495. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  39496. var alphaFilter = options.alphaFilter || 0.0;
  39497. // Vertices
  39498. for (row = 0; row <= options.subdivisions; row++) {
  39499. for (col = 0; col <= options.subdivisions; col++) {
  39500. 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));
  39501. // Compute height
  39502. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  39503. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  39504. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  39505. var r = options.buffer[pos] / 255.0;
  39506. var g = options.buffer[pos + 1] / 255.0;
  39507. var b = options.buffer[pos + 2] / 255.0;
  39508. var a = options.buffer[pos + 3] / 255.0;
  39509. var gradient = r * filter.r + g * filter.g + b * filter.b;
  39510. // If our alpha channel is not within our filter then we will assign a 'special' height
  39511. // Then when building the indices, we will ignore any vertex that is using the special height
  39512. if (a >= alphaFilter) {
  39513. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  39514. }
  39515. else {
  39516. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  39517. }
  39518. // Add vertex
  39519. positions.push(position.x, position.y, position.z);
  39520. normals.push(0, 0, 0);
  39521. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  39522. }
  39523. }
  39524. // Indices
  39525. for (row = 0; row < options.subdivisions; row++) {
  39526. for (col = 0; col < options.subdivisions; col++) {
  39527. // Calculate Indices
  39528. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  39529. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  39530. var idx3 = (col + row * (options.subdivisions + 1));
  39531. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  39532. // Check that all indices are visible (based on our special height)
  39533. // Only display the vertex if all Indices are visible
  39534. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  39535. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  39536. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  39537. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  39538. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  39539. indices.push(idx1);
  39540. indices.push(idx2);
  39541. indices.push(idx3);
  39542. }
  39543. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  39544. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  39545. indices.push(idx4);
  39546. indices.push(idx1);
  39547. indices.push(idx3);
  39548. }
  39549. }
  39550. }
  39551. // Normals
  39552. VertexData.ComputeNormals(positions, indices, normals);
  39553. // Result
  39554. var vertexData = new VertexData();
  39555. vertexData.indices = indices;
  39556. vertexData.positions = positions;
  39557. vertexData.normals = normals;
  39558. vertexData.uvs = uvs;
  39559. return vertexData;
  39560. };
  39561. /**
  39562. * Creates the VertexData for a Plane
  39563. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  39564. * * size sets the width and height of the plane to the value of size, optional default 1
  39565. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  39566. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  39567. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39568. * * 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)
  39569. * * 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)
  39570. * @returns the VertexData of the box
  39571. */
  39572. VertexData.CreatePlane = function (options) {
  39573. var indices = [];
  39574. var positions = [];
  39575. var normals = [];
  39576. var uvs = [];
  39577. var width = options.width || options.size || 1;
  39578. var height = options.height || options.size || 1;
  39579. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39580. // Vertices
  39581. var halfWidth = width / 2.0;
  39582. var halfHeight = height / 2.0;
  39583. positions.push(-halfWidth, -halfHeight, 0);
  39584. normals.push(0, 0, -1.0);
  39585. uvs.push(0.0, 0.0);
  39586. positions.push(halfWidth, -halfHeight, 0);
  39587. normals.push(0, 0, -1.0);
  39588. uvs.push(1.0, 0.0);
  39589. positions.push(halfWidth, halfHeight, 0);
  39590. normals.push(0, 0, -1.0);
  39591. uvs.push(1.0, 1.0);
  39592. positions.push(-halfWidth, halfHeight, 0);
  39593. normals.push(0, 0, -1.0);
  39594. uvs.push(0.0, 1.0);
  39595. // Indices
  39596. indices.push(0);
  39597. indices.push(1);
  39598. indices.push(2);
  39599. indices.push(0);
  39600. indices.push(2);
  39601. indices.push(3);
  39602. // Sides
  39603. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39604. // Result
  39605. var vertexData = new VertexData();
  39606. vertexData.indices = indices;
  39607. vertexData.positions = positions;
  39608. vertexData.normals = normals;
  39609. vertexData.uvs = uvs;
  39610. return vertexData;
  39611. };
  39612. /**
  39613. * Creates the VertexData of the Disc or regular Polygon
  39614. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  39615. * * radius the radius of the disc, optional default 0.5
  39616. * * tessellation the number of polygon sides, optional, default 64
  39617. * * 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
  39618. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39619. * * 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)
  39620. * * 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)
  39621. * @returns the VertexData of the box
  39622. */
  39623. VertexData.CreateDisc = function (options) {
  39624. var positions = new Array();
  39625. var indices = new Array();
  39626. var normals = new Array();
  39627. var uvs = new Array();
  39628. var radius = options.radius || 0.5;
  39629. var tessellation = options.tessellation || 64;
  39630. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  39631. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39632. // positions and uvs
  39633. positions.push(0, 0, 0); // disc center first
  39634. uvs.push(0.5, 0.5);
  39635. var theta = Math.PI * 2 * arc;
  39636. var step = theta / tessellation;
  39637. for (var a = 0; a < theta; a += step) {
  39638. var x = Math.cos(a);
  39639. var y = Math.sin(a);
  39640. var u = (x + 1) / 2;
  39641. var v = (1 - y) / 2;
  39642. positions.push(radius * x, radius * y, 0);
  39643. uvs.push(u, v);
  39644. }
  39645. if (arc === 1) {
  39646. positions.push(positions[3], positions[4], positions[5]); // close the circle
  39647. uvs.push(uvs[2], uvs[3]);
  39648. }
  39649. //indices
  39650. var vertexNb = positions.length / 3;
  39651. for (var i = 1; i < vertexNb - 1; i++) {
  39652. indices.push(i + 1, 0, i);
  39653. }
  39654. // result
  39655. VertexData.ComputeNormals(positions, indices, normals);
  39656. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39657. var vertexData = new VertexData();
  39658. vertexData.indices = indices;
  39659. vertexData.positions = positions;
  39660. vertexData.normals = normals;
  39661. vertexData.uvs = uvs;
  39662. return vertexData;
  39663. };
  39664. /**
  39665. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  39666. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  39667. * @param polygon a mesh built from polygonTriangulation.build()
  39668. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39669. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39670. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39671. * @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)
  39672. * @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)
  39673. * @returns the VertexData of the Polygon
  39674. */
  39675. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  39676. var faceUV = fUV || new Array(3);
  39677. var faceColors = fColors;
  39678. var colors = [];
  39679. // default face colors and UV if undefined
  39680. for (var f = 0; f < 3; f++) {
  39681. if (faceUV[f] === undefined) {
  39682. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39683. }
  39684. if (faceColors && faceColors[f] === undefined) {
  39685. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39686. }
  39687. }
  39688. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39689. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39690. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39691. var indices = polygon.getIndices();
  39692. // set face colours and textures
  39693. var idx = 0;
  39694. var face = 0;
  39695. for (var index = 0; index < normals.length; index += 3) {
  39696. //Edge Face no. 1
  39697. if (Math.abs(normals[index + 1]) < 0.001) {
  39698. face = 1;
  39699. }
  39700. //Top Face no. 0
  39701. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  39702. face = 0;
  39703. }
  39704. //Bottom Face no. 2
  39705. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  39706. face = 2;
  39707. }
  39708. idx = index / 3;
  39709. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  39710. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  39711. if (faceColors) {
  39712. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  39713. }
  39714. }
  39715. // sides
  39716. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  39717. // Result
  39718. var vertexData = new VertexData();
  39719. vertexData.indices = indices;
  39720. vertexData.positions = positions;
  39721. vertexData.normals = normals;
  39722. vertexData.uvs = uvs;
  39723. if (faceColors) {
  39724. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  39725. vertexData.colors = totalColors;
  39726. }
  39727. return vertexData;
  39728. };
  39729. /**
  39730. * Creates the VertexData of the IcoSphere
  39731. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  39732. * * radius the radius of the IcoSphere, optional default 1
  39733. * * radiusX allows stretching in the x direction, optional, default radius
  39734. * * radiusY allows stretching in the y direction, optional, default radius
  39735. * * radiusZ allows stretching in the z direction, optional, default radius
  39736. * * flat when true creates a flat shaded mesh, optional, default true
  39737. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39738. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39739. * * 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)
  39740. * * 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)
  39741. * @returns the VertexData of the IcoSphere
  39742. */
  39743. VertexData.CreateIcoSphere = function (options) {
  39744. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39745. var radius = options.radius || 1;
  39746. var flat = (options.flat === undefined) ? true : options.flat;
  39747. var subdivisions = options.subdivisions || 4;
  39748. var radiusX = options.radiusX || radius;
  39749. var radiusY = options.radiusY || radius;
  39750. var radiusZ = options.radiusZ || radius;
  39751. var t = (1 + Math.sqrt(5)) / 2;
  39752. // 12 vertex x,y,z
  39753. var ico_vertices = [
  39754. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  39755. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  39756. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  39757. ];
  39758. // index of 3 vertex makes a face of icopshere
  39759. var ico_indices = [
  39760. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  39761. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  39762. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  39763. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  39764. ];
  39765. // vertex for uv have aliased position, not for UV
  39766. var vertices_unalias_id = [
  39767. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  39768. // vertex alias
  39769. 0,
  39770. 2,
  39771. 3,
  39772. 3,
  39773. 3,
  39774. 4,
  39775. 7,
  39776. 8,
  39777. 9,
  39778. 9,
  39779. 10,
  39780. 11 // 23: B + 12
  39781. ];
  39782. // uv as integer step (not pixels !)
  39783. var ico_vertexuv = [
  39784. 5, 1, 3, 1, 6, 4, 0, 0,
  39785. 5, 3, 4, 2, 2, 2, 4, 0,
  39786. 2, 0, 1, 1, 6, 0, 6, 2,
  39787. // vertex alias (for same vertex on different faces)
  39788. 0, 4,
  39789. 3, 3,
  39790. 4, 4,
  39791. 3, 1,
  39792. 4, 2,
  39793. 4, 4,
  39794. 0, 2,
  39795. 1, 1,
  39796. 2, 2,
  39797. 3, 3,
  39798. 1, 3,
  39799. 2, 4 // 23: B + 12
  39800. ];
  39801. // Vertices[0, 1, ...9, A, B] : position on UV plane
  39802. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  39803. // First island of uv mapping
  39804. // v = 4h 3+ 2
  39805. // v = 3h 9+ 4
  39806. // v = 2h 9+ 5 B
  39807. // v = 1h 9 1 0
  39808. // v = 0h 3 8 7 A
  39809. // u = 0 1 2 3 4 5 6 *a
  39810. // Second island of uv mapping
  39811. // v = 4h 0+ B+ 4+
  39812. // v = 3h A+ 2+
  39813. // v = 2h 7+ 6 3+
  39814. // v = 1h 8+ 3+
  39815. // v = 0h
  39816. // u = 0 1 2 3 4 5 6 *a
  39817. // Face layout on texture UV mapping
  39818. // ============
  39819. // \ 4 /\ 16 / ======
  39820. // \ / \ / /\ 11 /
  39821. // \/ 7 \/ / \ /
  39822. // ======= / 10 \/
  39823. // /\ 17 /\ =======
  39824. // / \ / \ \ 15 /\
  39825. // / 8 \/ 12 \ \ / \
  39826. // ============ \/ 6 \
  39827. // \ 18 /\ ============
  39828. // \ / \ \ 5 /\ 0 /
  39829. // \/ 13 \ \ / \ /
  39830. // ======= \/ 1 \/
  39831. // =============
  39832. // /\ 19 /\ 2 /\
  39833. // / \ / \ / \
  39834. // / 14 \/ 9 \/ 3 \
  39835. // ===================
  39836. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  39837. var ustep = 138 / 1024;
  39838. var vstep = 239 / 1024;
  39839. var uoffset = 60 / 1024;
  39840. var voffset = 26 / 1024;
  39841. // Second island should have margin, not to touch the first island
  39842. // avoid any borderline artefact in pixel rounding
  39843. var island_u_offset = -40 / 1024;
  39844. var island_v_offset = +20 / 1024;
  39845. // face is either island 0 or 1 :
  39846. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  39847. var island = [
  39848. 0, 0, 0, 0, 1,
  39849. 0, 0, 1, 1, 0,
  39850. 0, 0, 1, 1, 0,
  39851. 0, 1, 1, 1, 0 // 15 - 19
  39852. ];
  39853. var indices = new Array();
  39854. var positions = new Array();
  39855. var normals = new Array();
  39856. var uvs = new Array();
  39857. var current_indice = 0;
  39858. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  39859. var face_vertex_pos = new Array(3);
  39860. var face_vertex_uv = new Array(3);
  39861. var v012;
  39862. for (v012 = 0; v012 < 3; v012++) {
  39863. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  39864. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  39865. }
  39866. // create all with normals
  39867. for (var face = 0; face < 20; face++) {
  39868. // 3 vertex per face
  39869. for (v012 = 0; v012 < 3; v012++) {
  39870. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  39871. var v_id = ico_indices[3 * face + v012];
  39872. // vertex have 3D position (x,y,z)
  39873. 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]);
  39874. // Normalize to get normal, then scale to radius
  39875. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  39876. // uv Coordinates from vertex ID
  39877. 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);
  39878. }
  39879. // Subdivide the face (interpolate pos, norm, uv)
  39880. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  39881. // - norm is linear interpolation of vertex corner normal
  39882. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  39883. // - uv is linear interpolation
  39884. //
  39885. // Topology is as below for sub-divide by 2
  39886. // vertex shown as v0,v1,v2
  39887. // interp index is i1 to progress in range [v0,v1[
  39888. // interp index is i2 to progress in range [v0,v2[
  39889. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  39890. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39891. //
  39892. //
  39893. // i2 v2
  39894. // ^ ^
  39895. // / / \
  39896. // / / \
  39897. // / / \
  39898. // / / (0,1) \
  39899. // / #---------\
  39900. // / / \ (0,0)'/ \
  39901. // / / \ / \
  39902. // / / \ / \
  39903. // / / (0,0) \ / (1,0) \
  39904. // / #---------#---------\
  39905. // v0 v1
  39906. //
  39907. // --------------------> i1
  39908. //
  39909. // interp of (i1,i2):
  39910. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  39911. // along i1 : lerp(x0,x1, i1/(S-i2))
  39912. //
  39913. // centroid of triangle is needed to get help normal computation
  39914. // (c1,c2) are used for centroid location
  39915. var interp_vertex = function (i1, i2, c1, c2) {
  39916. // vertex is interpolated from
  39917. // - face_vertex_pos[0..2]
  39918. // - face_vertex_uv[0..2]
  39919. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  39920. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  39921. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  39922. pos_interp.normalize();
  39923. var vertex_normal;
  39924. if (flat) {
  39925. // in flat mode, recalculate normal as face centroid normal
  39926. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  39927. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  39928. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  39929. }
  39930. else {
  39931. // in smooth mode, recalculate normal from each single vertex position
  39932. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  39933. }
  39934. // Vertex normal need correction due to X,Y,Z radius scaling
  39935. vertex_normal.x /= radiusX;
  39936. vertex_normal.y /= radiusY;
  39937. vertex_normal.z /= radiusZ;
  39938. vertex_normal.normalize();
  39939. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  39940. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  39941. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  39942. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  39943. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  39944. uvs.push(uv_interp.x, uv_interp.y);
  39945. // push each vertex has member of a face
  39946. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  39947. indices.push(current_indice);
  39948. current_indice++;
  39949. };
  39950. for (var i2 = 0; i2 < subdivisions; i2++) {
  39951. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  39952. // face : (i1,i2) for /\ :
  39953. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  39954. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39955. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39956. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39957. if (i1 + i2 + 1 < subdivisions) {
  39958. // face : (i1,i2)' for \/ :
  39959. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39960. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39961. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39962. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39963. }
  39964. }
  39965. }
  39966. }
  39967. // Sides
  39968. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39969. // Result
  39970. var vertexData = new VertexData();
  39971. vertexData.indices = indices;
  39972. vertexData.positions = positions;
  39973. vertexData.normals = normals;
  39974. vertexData.uvs = uvs;
  39975. return vertexData;
  39976. };
  39977. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  39978. /**
  39979. * Creates the VertexData for a Polyhedron
  39980. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  39981. * * type provided types are:
  39982. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39983. * * 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)
  39984. * * size the size of the IcoSphere, optional default 1
  39985. * * sizeX allows stretching in the x direction, optional, default size
  39986. * * sizeY allows stretching in the y direction, optional, default size
  39987. * * sizeZ allows stretching in the z direction, optional, default size
  39988. * * 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
  39989. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39990. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39991. * * flat when true creates a flat shaded mesh, optional, default true
  39992. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39993. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39994. * * 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)
  39995. * * 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)
  39996. * @returns the VertexData of the Polyhedron
  39997. */
  39998. VertexData.CreatePolyhedron = function (options) {
  39999. // provided polyhedron types :
  40000. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  40001. // 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)
  40002. var polyhedra = [];
  40003. 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]] };
  40004. 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]] };
  40005. polyhedra[2] = {
  40006. 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]],
  40007. 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]]
  40008. };
  40009. polyhedra[3] = {
  40010. 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]],
  40011. 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]]
  40012. };
  40013. polyhedra[4] = {
  40014. 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]],
  40015. 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]]
  40016. };
  40017. 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]] };
  40018. 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]] };
  40019. 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]] };
  40020. 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]] };
  40021. 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]] };
  40022. 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]] };
  40023. 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]] };
  40024. 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]] };
  40025. 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]] };
  40026. polyhedra[14] = {
  40027. 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]],
  40028. 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]]
  40029. };
  40030. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  40031. var size = options.size;
  40032. var sizeX = options.sizeX || size || 1;
  40033. var sizeY = options.sizeY || size || 1;
  40034. var sizeZ = options.sizeZ || size || 1;
  40035. var data = options.custom || polyhedra[type];
  40036. var nbfaces = data.face.length;
  40037. var faceUV = options.faceUV || new Array(nbfaces);
  40038. var faceColors = options.faceColors;
  40039. var flat = (options.flat === undefined) ? true : options.flat;
  40040. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40041. var positions = new Array();
  40042. var indices = new Array();
  40043. var normals = new Array();
  40044. var uvs = new Array();
  40045. var colors = new Array();
  40046. var index = 0;
  40047. var faceIdx = 0; // face cursor in the array "indexes"
  40048. var indexes = new Array();
  40049. var i = 0;
  40050. var f = 0;
  40051. var u, v, ang, x, y, tmp;
  40052. // default face colors and UV if undefined
  40053. if (flat) {
  40054. for (f = 0; f < nbfaces; f++) {
  40055. if (faceColors && faceColors[f] === undefined) {
  40056. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  40057. }
  40058. if (faceUV && faceUV[f] === undefined) {
  40059. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  40060. }
  40061. }
  40062. }
  40063. if (!flat) {
  40064. for (i = 0; i < data.vertex.length; i++) {
  40065. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  40066. uvs.push(0, 0);
  40067. }
  40068. for (f = 0; f < nbfaces; f++) {
  40069. for (i = 0; i < data.face[f].length - 2; i++) {
  40070. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  40071. }
  40072. }
  40073. }
  40074. else {
  40075. for (f = 0; f < nbfaces; f++) {
  40076. var fl = data.face[f].length; // number of vertices of the current face
  40077. ang = 2 * Math.PI / fl;
  40078. x = 0.5 * Math.tan(ang / 2);
  40079. y = 0.5;
  40080. // positions, uvs, colors
  40081. for (i = 0; i < fl; i++) {
  40082. // positions
  40083. 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);
  40084. indexes.push(index);
  40085. index++;
  40086. // uvs
  40087. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  40088. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  40089. uvs.push(u, v);
  40090. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  40091. y = x * Math.sin(ang) + y * Math.cos(ang);
  40092. x = tmp;
  40093. // colors
  40094. if (faceColors) {
  40095. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  40096. }
  40097. }
  40098. // indices from indexes
  40099. for (i = 0; i < fl - 2; i++) {
  40100. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  40101. }
  40102. faceIdx += fl;
  40103. }
  40104. }
  40105. VertexData.ComputeNormals(positions, indices, normals);
  40106. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  40107. var vertexData = new VertexData();
  40108. vertexData.positions = positions;
  40109. vertexData.indices = indices;
  40110. vertexData.normals = normals;
  40111. vertexData.uvs = uvs;
  40112. if (faceColors && flat) {
  40113. vertexData.colors = colors;
  40114. }
  40115. return vertexData;
  40116. };
  40117. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  40118. /**
  40119. * Creates the VertexData for a TorusKnot
  40120. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  40121. * * radius the radius of the torus knot, optional, default 2
  40122. * * tube the thickness of the tube, optional, default 0.5
  40123. * * radialSegments the number of sides on each tube segments, optional, default 32
  40124. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  40125. * * p the number of windings around the z axis, optional, default 2
  40126. * * q the number of windings around the x axis, optional, default 3
  40127. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40128. * * 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)
  40129. * * 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)
  40130. * @returns the VertexData of the Torus Knot
  40131. */
  40132. VertexData.CreateTorusKnot = function (options) {
  40133. var indices = new Array();
  40134. var positions = new Array();
  40135. var normals = new Array();
  40136. var uvs = new Array();
  40137. var radius = options.radius || 2;
  40138. var tube = options.tube || 0.5;
  40139. var radialSegments = options.radialSegments || 32;
  40140. var tubularSegments = options.tubularSegments || 32;
  40141. var p = options.p || 2;
  40142. var q = options.q || 3;
  40143. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40144. // Helper
  40145. var getPos = function (angle) {
  40146. var cu = Math.cos(angle);
  40147. var su = Math.sin(angle);
  40148. var quOverP = q / p * angle;
  40149. var cs = Math.cos(quOverP);
  40150. var tx = radius * (2 + cs) * 0.5 * cu;
  40151. var ty = radius * (2 + cs) * su * 0.5;
  40152. var tz = radius * Math.sin(quOverP) * 0.5;
  40153. return new BABYLON.Vector3(tx, ty, tz);
  40154. };
  40155. // Vertices
  40156. var i;
  40157. var j;
  40158. for (i = 0; i <= radialSegments; i++) {
  40159. var modI = i % radialSegments;
  40160. var u = modI / radialSegments * 2 * p * Math.PI;
  40161. var p1 = getPos(u);
  40162. var p2 = getPos(u + 0.01);
  40163. var tang = p2.subtract(p1);
  40164. var n = p2.add(p1);
  40165. var bitan = BABYLON.Vector3.Cross(tang, n);
  40166. n = BABYLON.Vector3.Cross(bitan, tang);
  40167. bitan.normalize();
  40168. n.normalize();
  40169. for (j = 0; j < tubularSegments; j++) {
  40170. var modJ = j % tubularSegments;
  40171. var v = modJ / tubularSegments * 2 * Math.PI;
  40172. var cx = -tube * Math.cos(v);
  40173. var cy = tube * Math.sin(v);
  40174. positions.push(p1.x + cx * n.x + cy * bitan.x);
  40175. positions.push(p1.y + cx * n.y + cy * bitan.y);
  40176. positions.push(p1.z + cx * n.z + cy * bitan.z);
  40177. uvs.push(i / radialSegments);
  40178. uvs.push(j / tubularSegments);
  40179. }
  40180. }
  40181. for (i = 0; i < radialSegments; i++) {
  40182. for (j = 0; j < tubularSegments; j++) {
  40183. var jNext = (j + 1) % tubularSegments;
  40184. var a = i * tubularSegments + j;
  40185. var b = (i + 1) * tubularSegments + j;
  40186. var c = (i + 1) * tubularSegments + jNext;
  40187. var d = i * tubularSegments + jNext;
  40188. indices.push(d);
  40189. indices.push(b);
  40190. indices.push(a);
  40191. indices.push(d);
  40192. indices.push(c);
  40193. indices.push(b);
  40194. }
  40195. }
  40196. // Normals
  40197. VertexData.ComputeNormals(positions, indices, normals);
  40198. // Sides
  40199. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  40200. // Result
  40201. var vertexData = new VertexData();
  40202. vertexData.indices = indices;
  40203. vertexData.positions = positions;
  40204. vertexData.normals = normals;
  40205. vertexData.uvs = uvs;
  40206. return vertexData;
  40207. };
  40208. // Tools
  40209. /**
  40210. * Compute normals for given positions and indices
  40211. * @param positions an array of vertex positions, [...., x, y, z, ......]
  40212. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  40213. * @param normals an array of vertex normals, [...., x, y, z, ......]
  40214. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  40215. * * facetNormals : optional array of facet normals (vector3)
  40216. * * facetPositions : optional array of facet positions (vector3)
  40217. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  40218. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  40219. * * bInfo : optional bounding info, required for facetPartitioning computation
  40220. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  40221. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  40222. * * useRightHandedSystem: optional boolean to for right handed system computation
  40223. * * depthSort : optional boolean to enable the facet depth sort computation
  40224. * * distanceTo : optional Vector3 to compute the facet depth from this location
  40225. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  40226. */
  40227. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  40228. // temporary scalar variables
  40229. var index = 0; // facet index
  40230. var p1p2x = 0.0; // p1p2 vector x coordinate
  40231. var p1p2y = 0.0; // p1p2 vector y coordinate
  40232. var p1p2z = 0.0; // p1p2 vector z coordinate
  40233. var p3p2x = 0.0; // p3p2 vector x coordinate
  40234. var p3p2y = 0.0; // p3p2 vector y coordinate
  40235. var p3p2z = 0.0; // p3p2 vector z coordinate
  40236. var faceNormalx = 0.0; // facet normal x coordinate
  40237. var faceNormaly = 0.0; // facet normal y coordinate
  40238. var faceNormalz = 0.0; // facet normal z coordinate
  40239. var length = 0.0; // facet normal length before normalization
  40240. var v1x = 0; // vector1 x index in the positions array
  40241. var v1y = 0; // vector1 y index in the positions array
  40242. var v1z = 0; // vector1 z index in the positions array
  40243. var v2x = 0; // vector2 x index in the positions array
  40244. var v2y = 0; // vector2 y index in the positions array
  40245. var v2z = 0; // vector2 z index in the positions array
  40246. var v3x = 0; // vector3 x index in the positions array
  40247. var v3y = 0; // vector3 y index in the positions array
  40248. var v3z = 0; // vector3 z index in the positions array
  40249. var computeFacetNormals = false;
  40250. var computeFacetPositions = false;
  40251. var computeFacetPartitioning = false;
  40252. var computeDepthSort = false;
  40253. var faceNormalSign = 1;
  40254. var ratio = 0;
  40255. var distanceTo = null;
  40256. if (options) {
  40257. computeFacetNormals = (options.facetNormals) ? true : false;
  40258. computeFacetPositions = (options.facetPositions) ? true : false;
  40259. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  40260. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  40261. ratio = options.ratio || 0;
  40262. computeDepthSort = (options.depthSort) ? true : false;
  40263. distanceTo = (options.distanceTo);
  40264. if (computeDepthSort) {
  40265. if (distanceTo === undefined) {
  40266. distanceTo = BABYLON.Vector3.Zero();
  40267. }
  40268. var depthSortedFacets = options.depthSortedFacets;
  40269. }
  40270. }
  40271. // facetPartitioning reinit if needed
  40272. var xSubRatio = 0;
  40273. var ySubRatio = 0;
  40274. var zSubRatio = 0;
  40275. var subSq = 0;
  40276. if (computeFacetPartitioning && options && options.bbSize) {
  40277. var ox = 0; // X partitioning index for facet position
  40278. var oy = 0; // Y partinioning index for facet position
  40279. var oz = 0; // Z partinioning index for facet position
  40280. var b1x = 0; // X partitioning index for facet v1 vertex
  40281. var b1y = 0; // Y partitioning index for facet v1 vertex
  40282. var b1z = 0; // z partitioning index for facet v1 vertex
  40283. var b2x = 0; // X partitioning index for facet v2 vertex
  40284. var b2y = 0; // Y partitioning index for facet v2 vertex
  40285. var b2z = 0; // Z partitioning index for facet v2 vertex
  40286. var b3x = 0; // X partitioning index for facet v3 vertex
  40287. var b3y = 0; // Y partitioning index for facet v3 vertex
  40288. var b3z = 0; // Z partitioning index for facet v3 vertex
  40289. var block_idx_o = 0; // facet barycenter block index
  40290. var block_idx_v1 = 0; // v1 vertex block index
  40291. var block_idx_v2 = 0; // v2 vertex block index
  40292. var block_idx_v3 = 0; // v3 vertex block index
  40293. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  40294. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  40295. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  40296. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  40297. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  40298. subSq = options.subDiv.max * options.subDiv.max;
  40299. options.facetPartitioning.length = 0;
  40300. }
  40301. // reset the normals
  40302. for (index = 0; index < positions.length; index++) {
  40303. normals[index] = 0.0;
  40304. }
  40305. // Loop : 1 indice triplet = 1 facet
  40306. var nbFaces = (indices.length / 3) | 0;
  40307. for (index = 0; index < nbFaces; index++) {
  40308. // get the indexes of the coordinates of each vertex of the facet
  40309. v1x = indices[index * 3] * 3;
  40310. v1y = v1x + 1;
  40311. v1z = v1x + 2;
  40312. v2x = indices[index * 3 + 1] * 3;
  40313. v2y = v2x + 1;
  40314. v2z = v2x + 2;
  40315. v3x = indices[index * 3 + 2] * 3;
  40316. v3y = v3x + 1;
  40317. v3z = v3x + 2;
  40318. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  40319. p1p2y = positions[v1y] - positions[v2y];
  40320. p1p2z = positions[v1z] - positions[v2z];
  40321. p3p2x = positions[v3x] - positions[v2x];
  40322. p3p2y = positions[v3y] - positions[v2y];
  40323. p3p2z = positions[v3z] - positions[v2z];
  40324. // compute the face normal with the cross product
  40325. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  40326. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  40327. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  40328. // normalize this normal and store it in the array facetData
  40329. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  40330. length = (length === 0) ? 1.0 : length;
  40331. faceNormalx /= length;
  40332. faceNormaly /= length;
  40333. faceNormalz /= length;
  40334. if (computeFacetNormals && options) {
  40335. options.facetNormals[index].x = faceNormalx;
  40336. options.facetNormals[index].y = faceNormaly;
  40337. options.facetNormals[index].z = faceNormalz;
  40338. }
  40339. if (computeFacetPositions && options) {
  40340. // compute and the facet barycenter coordinates in the array facetPositions
  40341. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  40342. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  40343. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  40344. }
  40345. if (computeFacetPartitioning && options) {
  40346. // store the facet indexes in arrays in the main facetPartitioning array :
  40347. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  40348. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  40349. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  40350. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  40351. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  40352. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  40353. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  40354. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  40355. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  40356. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  40357. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  40358. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  40359. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  40360. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  40361. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  40362. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  40363. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  40364. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  40365. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  40366. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  40367. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  40368. // push each facet index in each block containing the vertex
  40369. options.facetPartitioning[block_idx_v1].push(index);
  40370. if (block_idx_v2 != block_idx_v1) {
  40371. options.facetPartitioning[block_idx_v2].push(index);
  40372. }
  40373. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  40374. options.facetPartitioning[block_idx_v3].push(index);
  40375. }
  40376. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  40377. options.facetPartitioning[block_idx_o].push(index);
  40378. }
  40379. }
  40380. if (computeDepthSort && options && options.facetPositions) {
  40381. var dsf = depthSortedFacets[index];
  40382. dsf.ind = index * 3;
  40383. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  40384. }
  40385. // compute the normals anyway
  40386. normals[v1x] += faceNormalx; // accumulate all the normals per face
  40387. normals[v1y] += faceNormaly;
  40388. normals[v1z] += faceNormalz;
  40389. normals[v2x] += faceNormalx;
  40390. normals[v2y] += faceNormaly;
  40391. normals[v2z] += faceNormalz;
  40392. normals[v3x] += faceNormalx;
  40393. normals[v3y] += faceNormaly;
  40394. normals[v3z] += faceNormalz;
  40395. }
  40396. // last normalization of each normal
  40397. for (index = 0; index < normals.length / 3; index++) {
  40398. faceNormalx = normals[index * 3];
  40399. faceNormaly = normals[index * 3 + 1];
  40400. faceNormalz = normals[index * 3 + 2];
  40401. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  40402. length = (length === 0) ? 1.0 : length;
  40403. faceNormalx /= length;
  40404. faceNormaly /= length;
  40405. faceNormalz /= length;
  40406. normals[index * 3] = faceNormalx;
  40407. normals[index * 3 + 1] = faceNormaly;
  40408. normals[index * 3 + 2] = faceNormalz;
  40409. }
  40410. };
  40411. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  40412. var li = indices.length;
  40413. var ln = normals.length;
  40414. var i;
  40415. var n;
  40416. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  40417. switch (sideOrientation) {
  40418. case BABYLON.Mesh.FRONTSIDE:
  40419. // nothing changed
  40420. break;
  40421. case BABYLON.Mesh.BACKSIDE:
  40422. var tmp;
  40423. // indices
  40424. for (i = 0; i < li; i += 3) {
  40425. tmp = indices[i];
  40426. indices[i] = indices[i + 2];
  40427. indices[i + 2] = tmp;
  40428. }
  40429. // normals
  40430. for (n = 0; n < ln; n++) {
  40431. normals[n] = -normals[n];
  40432. }
  40433. break;
  40434. case BABYLON.Mesh.DOUBLESIDE:
  40435. // positions
  40436. var lp = positions.length;
  40437. var l = lp / 3;
  40438. for (var p = 0; p < lp; p++) {
  40439. positions[lp + p] = positions[p];
  40440. }
  40441. // indices
  40442. for (i = 0; i < li; i += 3) {
  40443. indices[i + li] = indices[i + 2] + l;
  40444. indices[i + 1 + li] = indices[i + 1] + l;
  40445. indices[i + 2 + li] = indices[i] + l;
  40446. }
  40447. // normals
  40448. for (n = 0; n < ln; n++) {
  40449. normals[ln + n] = -normals[n];
  40450. }
  40451. // uvs
  40452. var lu = uvs.length;
  40453. var u = 0;
  40454. for (u = 0; u < lu; u++) {
  40455. uvs[u + lu] = uvs[u];
  40456. }
  40457. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  40458. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  40459. u = 0;
  40460. for (i = 0; i < lu / 2; i++) {
  40461. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  40462. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  40463. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  40464. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  40465. u += 2;
  40466. }
  40467. break;
  40468. }
  40469. };
  40470. /**
  40471. * Applies VertexData created from the imported parameters to the geometry
  40472. * @param parsedVertexData the parsed data from an imported file
  40473. * @param geometry the geometry to apply the VertexData to
  40474. */
  40475. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  40476. var vertexData = new VertexData();
  40477. // positions
  40478. var positions = parsedVertexData.positions;
  40479. if (positions) {
  40480. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  40481. }
  40482. // normals
  40483. var normals = parsedVertexData.normals;
  40484. if (normals) {
  40485. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  40486. }
  40487. // tangents
  40488. var tangents = parsedVertexData.tangents;
  40489. if (tangents) {
  40490. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  40491. }
  40492. // uvs
  40493. var uvs = parsedVertexData.uvs;
  40494. if (uvs) {
  40495. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  40496. }
  40497. // uv2s
  40498. var uv2s = parsedVertexData.uv2s;
  40499. if (uv2s) {
  40500. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  40501. }
  40502. // uv3s
  40503. var uv3s = parsedVertexData.uv3s;
  40504. if (uv3s) {
  40505. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  40506. }
  40507. // uv4s
  40508. var uv4s = parsedVertexData.uv4s;
  40509. if (uv4s) {
  40510. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  40511. }
  40512. // uv5s
  40513. var uv5s = parsedVertexData.uv5s;
  40514. if (uv5s) {
  40515. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  40516. }
  40517. // uv6s
  40518. var uv6s = parsedVertexData.uv6s;
  40519. if (uv6s) {
  40520. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  40521. }
  40522. // colors
  40523. var colors = parsedVertexData.colors;
  40524. if (colors) {
  40525. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  40526. }
  40527. // matricesIndices
  40528. var matricesIndices = parsedVertexData.matricesIndices;
  40529. if (matricesIndices) {
  40530. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  40531. }
  40532. // matricesWeights
  40533. var matricesWeights = parsedVertexData.matricesWeights;
  40534. if (matricesWeights) {
  40535. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  40536. }
  40537. // indices
  40538. var indices = parsedVertexData.indices;
  40539. if (indices) {
  40540. vertexData.indices = indices;
  40541. }
  40542. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  40543. };
  40544. return VertexData;
  40545. }());
  40546. BABYLON.VertexData = VertexData;
  40547. })(BABYLON || (BABYLON = {}));
  40548. //# sourceMappingURL=mesh.vertexData.js.map
  40549. var BABYLON;
  40550. (function (BABYLON) {
  40551. /**
  40552. * Class used to store geometry data (vertex buffers + index buffer)
  40553. */
  40554. var Geometry = /** @class */ (function () {
  40555. /**
  40556. * Creates a new geometry
  40557. * @param id defines the unique ID
  40558. * @param scene defines the hosting scene
  40559. * @param vertexData defines the VertexData used to get geometry data
  40560. * @param updatable defines if geometry must be updatable (false by default)
  40561. * @param mesh defines the mesh that will be associated with the geometry
  40562. */
  40563. function Geometry(id, scene, vertexData, updatable, mesh) {
  40564. if (updatable === void 0) { updatable = false; }
  40565. if (mesh === void 0) { mesh = null; }
  40566. /**
  40567. * Gets the delay loading state of the geometry (none by default which means not delayed)
  40568. */
  40569. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40570. this._totalVertices = 0;
  40571. this._isDisposed = false;
  40572. this._indexBufferIsUpdatable = false;
  40573. this.id = id;
  40574. this._engine = scene.getEngine();
  40575. this._meshes = [];
  40576. this._scene = scene;
  40577. //Init vertex buffer cache
  40578. this._vertexBuffers = {};
  40579. this._indices = [];
  40580. this._updatable = updatable;
  40581. // vertexData
  40582. if (vertexData) {
  40583. this.setAllVerticesData(vertexData, updatable);
  40584. }
  40585. else {
  40586. this._totalVertices = 0;
  40587. this._indices = [];
  40588. }
  40589. if (this._engine.getCaps().vertexArrayObject) {
  40590. this._vertexArrayObjects = {};
  40591. }
  40592. // applyToMesh
  40593. if (mesh) {
  40594. this.applyToMesh(mesh);
  40595. mesh.computeWorldMatrix(true);
  40596. }
  40597. }
  40598. Object.defineProperty(Geometry.prototype, "boundingBias", {
  40599. /**
  40600. * 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
  40601. */
  40602. get: function () {
  40603. return this._boundingBias;
  40604. },
  40605. /**
  40606. * 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
  40607. */
  40608. set: function (value) {
  40609. if (this._boundingBias) {
  40610. this._boundingBias.copyFrom(value);
  40611. }
  40612. else {
  40613. this._boundingBias = value.clone();
  40614. }
  40615. this._updateBoundingInfo(true, null);
  40616. },
  40617. enumerable: true,
  40618. configurable: true
  40619. });
  40620. /**
  40621. * Static function used to attach a new empty geometry to a mesh
  40622. * @param mesh defines the mesh to attach the geometry to
  40623. * @returns the new Geometry
  40624. */
  40625. Geometry.CreateGeometryForMesh = function (mesh) {
  40626. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  40627. geometry.applyToMesh(mesh);
  40628. return geometry;
  40629. };
  40630. Object.defineProperty(Geometry.prototype, "extend", {
  40631. /**
  40632. * Gets the current extend of the geometry
  40633. */
  40634. get: function () {
  40635. return this._extend;
  40636. },
  40637. enumerable: true,
  40638. configurable: true
  40639. });
  40640. /**
  40641. * Gets the hosting scene
  40642. * @returns the hosting Scene
  40643. */
  40644. Geometry.prototype.getScene = function () {
  40645. return this._scene;
  40646. };
  40647. /**
  40648. * Gets the hosting engine
  40649. * @returns the hosting Engine
  40650. */
  40651. Geometry.prototype.getEngine = function () {
  40652. return this._engine;
  40653. };
  40654. /**
  40655. * Defines if the geometry is ready to use
  40656. * @returns true if the geometry is ready to be used
  40657. */
  40658. Geometry.prototype.isReady = function () {
  40659. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  40660. };
  40661. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  40662. /**
  40663. * Gets a value indicating that the geometry should not be serialized
  40664. */
  40665. get: function () {
  40666. for (var index = 0; index < this._meshes.length; index++) {
  40667. if (!this._meshes[index].doNotSerialize) {
  40668. return false;
  40669. }
  40670. }
  40671. return true;
  40672. },
  40673. enumerable: true,
  40674. configurable: true
  40675. });
  40676. /** @hidden */
  40677. Geometry.prototype._rebuild = function () {
  40678. if (this._vertexArrayObjects) {
  40679. this._vertexArrayObjects = {};
  40680. }
  40681. // Index buffer
  40682. if (this._meshes.length !== 0 && this._indices) {
  40683. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40684. }
  40685. // Vertex buffers
  40686. for (var key in this._vertexBuffers) {
  40687. var vertexBuffer = this._vertexBuffers[key];
  40688. vertexBuffer._rebuild();
  40689. }
  40690. };
  40691. /**
  40692. * Affects all geometry data in one call
  40693. * @param vertexData defines the geometry data
  40694. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  40695. */
  40696. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40697. vertexData.applyToGeometry(this, updatable);
  40698. this.notifyUpdate();
  40699. };
  40700. /**
  40701. * Set specific vertex data
  40702. * @param kind defines the data kind (Position, normal, etc...)
  40703. * @param data defines the vertex data to use
  40704. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  40705. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  40706. */
  40707. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  40708. if (updatable === void 0) { updatable = false; }
  40709. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  40710. this.setVerticesBuffer(buffer);
  40711. };
  40712. /**
  40713. * Removes a specific vertex data
  40714. * @param kind defines the data kind (Position, normal, etc...)
  40715. */
  40716. Geometry.prototype.removeVerticesData = function (kind) {
  40717. if (this._vertexBuffers[kind]) {
  40718. this._vertexBuffers[kind].dispose();
  40719. delete this._vertexBuffers[kind];
  40720. }
  40721. };
  40722. /**
  40723. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  40724. * @param buffer defines the vertex buffer to use
  40725. * @param totalVertices defines the total number of vertices for position kind (could be null)
  40726. */
  40727. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  40728. if (totalVertices === void 0) { totalVertices = null; }
  40729. var kind = buffer.getKind();
  40730. if (this._vertexBuffers[kind]) {
  40731. this._vertexBuffers[kind].dispose();
  40732. }
  40733. this._vertexBuffers[kind] = buffer;
  40734. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40735. var data = buffer.getData();
  40736. if (totalVertices != null) {
  40737. this._totalVertices = totalVertices;
  40738. }
  40739. else {
  40740. if (data != null) {
  40741. this._totalVertices = data.length / (buffer.byteStride / 4);
  40742. }
  40743. }
  40744. this._updateExtend(data);
  40745. this._resetPointsArrayCache();
  40746. var meshes = this._meshes;
  40747. var numOfMeshes = meshes.length;
  40748. for (var index = 0; index < numOfMeshes; index++) {
  40749. var mesh = meshes[index];
  40750. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40751. mesh._createGlobalSubMesh(false);
  40752. mesh.computeWorldMatrix(true);
  40753. }
  40754. }
  40755. this.notifyUpdate(kind);
  40756. if (this._vertexArrayObjects) {
  40757. this._disposeVertexArrayObjects();
  40758. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  40759. }
  40760. };
  40761. /**
  40762. * Update a specific vertex buffer
  40763. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  40764. * It will do nothing if the buffer is not updatable
  40765. * @param kind defines the data kind (Position, normal, etc...)
  40766. * @param data defines the data to use
  40767. * @param offset defines the offset in the target buffer where to store the data
  40768. * @param useBytes set to true if the offset is in bytes
  40769. */
  40770. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  40771. if (useBytes === void 0) { useBytes = false; }
  40772. var vertexBuffer = this.getVertexBuffer(kind);
  40773. if (!vertexBuffer) {
  40774. return;
  40775. }
  40776. vertexBuffer.updateDirectly(data, offset, useBytes);
  40777. this.notifyUpdate(kind);
  40778. };
  40779. /**
  40780. * Update a specific vertex buffer
  40781. * This function will create a new buffer if the current one is not updatable
  40782. * @param kind defines the data kind (Position, normal, etc...)
  40783. * @param data defines the data to use
  40784. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  40785. */
  40786. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  40787. if (updateExtends === void 0) { updateExtends = false; }
  40788. var vertexBuffer = this.getVertexBuffer(kind);
  40789. if (!vertexBuffer) {
  40790. return;
  40791. }
  40792. vertexBuffer.update(data);
  40793. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40794. this._updateBoundingInfo(updateExtends, data);
  40795. }
  40796. this.notifyUpdate(kind);
  40797. };
  40798. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  40799. if (updateExtends) {
  40800. this._updateExtend(data);
  40801. }
  40802. this._resetPointsArrayCache();
  40803. if (updateExtends) {
  40804. var meshes = this._meshes;
  40805. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  40806. var mesh = meshes_1[_i];
  40807. if (mesh._boundingInfo) {
  40808. mesh._boundingInfo.reConstruct(this._extend.minimum, this._extend.maximum);
  40809. }
  40810. else {
  40811. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40812. }
  40813. var subMeshes = mesh.subMeshes;
  40814. for (var _a = 0, subMeshes_1 = subMeshes; _a < subMeshes_1.length; _a++) {
  40815. var subMesh = subMeshes_1[_a];
  40816. subMesh.refreshBoundingInfo();
  40817. }
  40818. }
  40819. }
  40820. };
  40821. /** @hidden */
  40822. Geometry.prototype._bind = function (effect, indexToBind) {
  40823. if (!effect) {
  40824. return;
  40825. }
  40826. if (indexToBind === undefined) {
  40827. indexToBind = this._indexBuffer;
  40828. }
  40829. var vbs = this.getVertexBuffers();
  40830. if (!vbs) {
  40831. return;
  40832. }
  40833. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  40834. this._engine.bindBuffers(vbs, indexToBind, effect);
  40835. return;
  40836. }
  40837. // Using VAO
  40838. if (!this._vertexArrayObjects[effect.key]) {
  40839. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  40840. }
  40841. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  40842. };
  40843. /**
  40844. * Gets total number of vertices
  40845. * @returns the total number of vertices
  40846. */
  40847. Geometry.prototype.getTotalVertices = function () {
  40848. if (!this.isReady()) {
  40849. return 0;
  40850. }
  40851. return this._totalVertices;
  40852. };
  40853. /**
  40854. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  40855. * @param kind defines the data kind (Position, normal, etc...)
  40856. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40857. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40858. * @returns a float array containing vertex data
  40859. */
  40860. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  40861. var vertexBuffer = this.getVertexBuffer(kind);
  40862. if (!vertexBuffer) {
  40863. return null;
  40864. }
  40865. var data = vertexBuffer.getData();
  40866. if (!data) {
  40867. return null;
  40868. }
  40869. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  40870. var count = this._totalVertices * vertexBuffer.getSize();
  40871. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  40872. var copy_1 = [];
  40873. vertexBuffer.forEach(count, function (value) { return copy_1.push(value); });
  40874. return copy_1;
  40875. }
  40876. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  40877. if (data instanceof Array) {
  40878. var offset = vertexBuffer.byteOffset / 4;
  40879. return BABYLON.Tools.Slice(data, offset, offset + count);
  40880. }
  40881. else if (data instanceof ArrayBuffer) {
  40882. return new Float32Array(data, vertexBuffer.byteOffset, count);
  40883. }
  40884. else {
  40885. var offset = data.byteOffset + vertexBuffer.byteOffset;
  40886. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  40887. var result = new Float32Array(count);
  40888. var source = new Float32Array(data.buffer, offset, count);
  40889. result.set(source);
  40890. return result;
  40891. }
  40892. return new Float32Array(data.buffer, offset, count);
  40893. }
  40894. }
  40895. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  40896. return BABYLON.Tools.Slice(data);
  40897. }
  40898. return data;
  40899. };
  40900. /**
  40901. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  40902. * @param kind defines the data kind (Position, normal, etc...)
  40903. * @returns true if the vertex buffer with the specified kind is updatable
  40904. */
  40905. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  40906. var vb = this._vertexBuffers[kind];
  40907. if (!vb) {
  40908. return false;
  40909. }
  40910. return vb.isUpdatable();
  40911. };
  40912. /**
  40913. * Gets a specific vertex buffer
  40914. * @param kind defines the data kind (Position, normal, etc...)
  40915. * @returns a VertexBuffer
  40916. */
  40917. Geometry.prototype.getVertexBuffer = function (kind) {
  40918. if (!this.isReady()) {
  40919. return null;
  40920. }
  40921. return this._vertexBuffers[kind];
  40922. };
  40923. /**
  40924. * Returns all vertex buffers
  40925. * @return an object holding all vertex buffers indexed by kind
  40926. */
  40927. Geometry.prototype.getVertexBuffers = function () {
  40928. if (!this.isReady()) {
  40929. return null;
  40930. }
  40931. return this._vertexBuffers;
  40932. };
  40933. /**
  40934. * Gets a boolean indicating if specific vertex buffer is present
  40935. * @param kind defines the data kind (Position, normal, etc...)
  40936. * @returns true if data is present
  40937. */
  40938. Geometry.prototype.isVerticesDataPresent = function (kind) {
  40939. if (!this._vertexBuffers) {
  40940. if (this._delayInfo) {
  40941. return this._delayInfo.indexOf(kind) !== -1;
  40942. }
  40943. return false;
  40944. }
  40945. return this._vertexBuffers[kind] !== undefined;
  40946. };
  40947. /**
  40948. * Gets a list of all attached data kinds (Position, normal, etc...)
  40949. * @returns a list of string containing all kinds
  40950. */
  40951. Geometry.prototype.getVerticesDataKinds = function () {
  40952. var result = [];
  40953. var kind;
  40954. if (!this._vertexBuffers && this._delayInfo) {
  40955. for (kind in this._delayInfo) {
  40956. result.push(kind);
  40957. }
  40958. }
  40959. else {
  40960. for (kind in this._vertexBuffers) {
  40961. result.push(kind);
  40962. }
  40963. }
  40964. return result;
  40965. };
  40966. /**
  40967. * Update index buffer
  40968. * @param indices defines the indices to store in the index buffer
  40969. * @param offset defines the offset in the target buffer where to store the data
  40970. */
  40971. Geometry.prototype.updateIndices = function (indices, offset) {
  40972. if (!this._indexBuffer) {
  40973. return;
  40974. }
  40975. if (!this._indexBufferIsUpdatable) {
  40976. this.setIndices(indices, null, true);
  40977. }
  40978. else {
  40979. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  40980. }
  40981. };
  40982. /**
  40983. * Creates a new index buffer
  40984. * @param indices defines the indices to store in the index buffer
  40985. * @param totalVertices defines the total number of vertices (could be null)
  40986. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  40987. */
  40988. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  40989. if (totalVertices === void 0) { totalVertices = null; }
  40990. if (updatable === void 0) { updatable = false; }
  40991. if (this._indexBuffer) {
  40992. this._engine._releaseBuffer(this._indexBuffer);
  40993. }
  40994. this._disposeVertexArrayObjects();
  40995. this._indices = indices;
  40996. this._indexBufferIsUpdatable = updatable;
  40997. if (this._meshes.length !== 0 && this._indices) {
  40998. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  40999. }
  41000. if (totalVertices != undefined) { // including null and undefined
  41001. this._totalVertices = totalVertices;
  41002. }
  41003. var meshes = this._meshes;
  41004. var numOfMeshes = meshes.length;
  41005. for (var index = 0; index < numOfMeshes; index++) {
  41006. meshes[index]._createGlobalSubMesh(true);
  41007. }
  41008. this.notifyUpdate();
  41009. };
  41010. /**
  41011. * Return the total number of indices
  41012. * @returns the total number of indices
  41013. */
  41014. Geometry.prototype.getTotalIndices = function () {
  41015. if (!this.isReady()) {
  41016. return 0;
  41017. }
  41018. return this._indices.length;
  41019. };
  41020. /**
  41021. * Gets the index buffer array
  41022. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  41023. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  41024. * @returns the index buffer array
  41025. */
  41026. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  41027. if (!this.isReady()) {
  41028. return null;
  41029. }
  41030. var orig = this._indices;
  41031. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  41032. return orig;
  41033. }
  41034. else {
  41035. var len = orig.length;
  41036. var copy = [];
  41037. for (var i = 0; i < len; i++) {
  41038. copy.push(orig[i]);
  41039. }
  41040. return copy;
  41041. }
  41042. };
  41043. /**
  41044. * Gets the index buffer
  41045. * @return the index buffer
  41046. */
  41047. Geometry.prototype.getIndexBuffer = function () {
  41048. if (!this.isReady()) {
  41049. return null;
  41050. }
  41051. return this._indexBuffer;
  41052. };
  41053. /** @hidden */
  41054. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  41055. if (effect === void 0) { effect = null; }
  41056. if (!effect || !this._vertexArrayObjects) {
  41057. return;
  41058. }
  41059. if (this._vertexArrayObjects[effect.key]) {
  41060. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  41061. delete this._vertexArrayObjects[effect.key];
  41062. }
  41063. };
  41064. /**
  41065. * Release the associated resources for a specific mesh
  41066. * @param mesh defines the source mesh
  41067. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  41068. */
  41069. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  41070. var meshes = this._meshes;
  41071. var index = meshes.indexOf(mesh);
  41072. if (index === -1) {
  41073. return;
  41074. }
  41075. meshes.splice(index, 1);
  41076. mesh._geometry = null;
  41077. if (meshes.length === 0 && shouldDispose) {
  41078. this.dispose();
  41079. }
  41080. };
  41081. /**
  41082. * Apply current geometry to a given mesh
  41083. * @param mesh defines the mesh to apply geometry to
  41084. */
  41085. Geometry.prototype.applyToMesh = function (mesh) {
  41086. if (mesh._geometry === this) {
  41087. return;
  41088. }
  41089. var previousGeometry = mesh._geometry;
  41090. if (previousGeometry) {
  41091. previousGeometry.releaseForMesh(mesh);
  41092. }
  41093. var meshes = this._meshes;
  41094. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  41095. mesh._geometry = this;
  41096. this._scene.pushGeometry(this);
  41097. meshes.push(mesh);
  41098. if (this.isReady()) {
  41099. this._applyToMesh(mesh);
  41100. }
  41101. else {
  41102. mesh._boundingInfo = this._boundingInfo;
  41103. }
  41104. };
  41105. Geometry.prototype._updateExtend = function (data) {
  41106. if (data === void 0) { data = null; }
  41107. if (!data) {
  41108. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41109. }
  41110. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  41111. };
  41112. Geometry.prototype._applyToMesh = function (mesh) {
  41113. var numOfMeshes = this._meshes.length;
  41114. // vertexBuffers
  41115. for (var kind in this._vertexBuffers) {
  41116. if (numOfMeshes === 1) {
  41117. this._vertexBuffers[kind].create();
  41118. }
  41119. var buffer = this._vertexBuffers[kind].getBuffer();
  41120. if (buffer) {
  41121. buffer.references = numOfMeshes;
  41122. }
  41123. if (kind === BABYLON.VertexBuffer.PositionKind) {
  41124. if (!this._extend) {
  41125. this._updateExtend();
  41126. }
  41127. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41128. mesh._createGlobalSubMesh(false);
  41129. //bounding info was just created again, world matrix should be applied again.
  41130. mesh._updateBoundingInfo();
  41131. }
  41132. }
  41133. // indexBuffer
  41134. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  41135. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  41136. }
  41137. if (this._indexBuffer) {
  41138. this._indexBuffer.references = numOfMeshes;
  41139. }
  41140. // morphTargets
  41141. mesh._syncGeometryWithMorphTargetManager();
  41142. };
  41143. Geometry.prototype.notifyUpdate = function (kind) {
  41144. if (this.onGeometryUpdated) {
  41145. this.onGeometryUpdated(this, kind);
  41146. }
  41147. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  41148. var mesh = _a[_i];
  41149. mesh._markSubMeshesAsAttributesDirty();
  41150. }
  41151. };
  41152. /**
  41153. * Load the geometry if it was flagged as delay loaded
  41154. * @param scene defines the hosting scene
  41155. * @param onLoaded defines a callback called when the geometry is loaded
  41156. */
  41157. Geometry.prototype.load = function (scene, onLoaded) {
  41158. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  41159. return;
  41160. }
  41161. if (this.isReady()) {
  41162. if (onLoaded) {
  41163. onLoaded();
  41164. }
  41165. return;
  41166. }
  41167. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  41168. this._queueLoad(scene, onLoaded);
  41169. };
  41170. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  41171. var _this = this;
  41172. if (!this.delayLoadingFile) {
  41173. return;
  41174. }
  41175. scene._addPendingData(this);
  41176. scene._loadFile(this.delayLoadingFile, function (data) {
  41177. if (!_this._delayLoadingFunction) {
  41178. return;
  41179. }
  41180. _this._delayLoadingFunction(JSON.parse(data), _this);
  41181. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41182. _this._delayInfo = [];
  41183. scene._removePendingData(_this);
  41184. var meshes = _this._meshes;
  41185. var numOfMeshes = meshes.length;
  41186. for (var index = 0; index < numOfMeshes; index++) {
  41187. _this._applyToMesh(meshes[index]);
  41188. }
  41189. if (onLoaded) {
  41190. onLoaded();
  41191. }
  41192. }, undefined, true);
  41193. };
  41194. /**
  41195. * Invert the geometry to move from a right handed system to a left handed one.
  41196. */
  41197. Geometry.prototype.toLeftHanded = function () {
  41198. // Flip faces
  41199. var tIndices = this.getIndices(false);
  41200. if (tIndices != null && tIndices.length > 0) {
  41201. for (var i = 0; i < tIndices.length; i += 3) {
  41202. var tTemp = tIndices[i + 0];
  41203. tIndices[i + 0] = tIndices[i + 2];
  41204. tIndices[i + 2] = tTemp;
  41205. }
  41206. this.setIndices(tIndices);
  41207. }
  41208. // Negate position.z
  41209. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  41210. if (tPositions != null && tPositions.length > 0) {
  41211. for (var i = 0; i < tPositions.length; i += 3) {
  41212. tPositions[i + 2] = -tPositions[i + 2];
  41213. }
  41214. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  41215. }
  41216. // Negate normal.z
  41217. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  41218. if (tNormals != null && tNormals.length > 0) {
  41219. for (var i = 0; i < tNormals.length; i += 3) {
  41220. tNormals[i + 2] = -tNormals[i + 2];
  41221. }
  41222. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  41223. }
  41224. };
  41225. // Cache
  41226. /** @hidden */
  41227. Geometry.prototype._resetPointsArrayCache = function () {
  41228. this._positions = null;
  41229. };
  41230. /** @hidden */
  41231. Geometry.prototype._generatePointsArray = function () {
  41232. if (this._positions) {
  41233. return true;
  41234. }
  41235. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41236. if (!data || data.length === 0) {
  41237. return false;
  41238. }
  41239. this._positions = [];
  41240. for (var index = 0; index < data.length; index += 3) {
  41241. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  41242. }
  41243. return true;
  41244. };
  41245. /**
  41246. * Gets a value indicating if the geometry is disposed
  41247. * @returns true if the geometry was disposed
  41248. */
  41249. Geometry.prototype.isDisposed = function () {
  41250. return this._isDisposed;
  41251. };
  41252. Geometry.prototype._disposeVertexArrayObjects = function () {
  41253. if (this._vertexArrayObjects) {
  41254. for (var kind in this._vertexArrayObjects) {
  41255. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  41256. }
  41257. this._vertexArrayObjects = {};
  41258. }
  41259. };
  41260. /**
  41261. * Free all associated resources
  41262. */
  41263. Geometry.prototype.dispose = function () {
  41264. var meshes = this._meshes;
  41265. var numOfMeshes = meshes.length;
  41266. var index;
  41267. for (index = 0; index < numOfMeshes; index++) {
  41268. this.releaseForMesh(meshes[index]);
  41269. }
  41270. this._meshes = [];
  41271. this._disposeVertexArrayObjects();
  41272. for (var kind in this._vertexBuffers) {
  41273. this._vertexBuffers[kind].dispose();
  41274. }
  41275. this._vertexBuffers = {};
  41276. this._totalVertices = 0;
  41277. if (this._indexBuffer) {
  41278. this._engine._releaseBuffer(this._indexBuffer);
  41279. }
  41280. this._indexBuffer = null;
  41281. this._indices = [];
  41282. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  41283. this.delayLoadingFile = null;
  41284. this._delayLoadingFunction = null;
  41285. this._delayInfo = [];
  41286. this._boundingInfo = null;
  41287. this._scene.removeGeometry(this);
  41288. this._isDisposed = true;
  41289. };
  41290. /**
  41291. * Clone the current geometry into a new geometry
  41292. * @param id defines the unique ID of the new geometry
  41293. * @returns a new geometry object
  41294. */
  41295. Geometry.prototype.copy = function (id) {
  41296. var vertexData = new BABYLON.VertexData();
  41297. vertexData.indices = [];
  41298. var indices = this.getIndices();
  41299. if (indices) {
  41300. for (var index = 0; index < indices.length; index++) {
  41301. vertexData.indices.push(indices[index]);
  41302. }
  41303. }
  41304. var updatable = false;
  41305. var stopChecking = false;
  41306. var kind;
  41307. for (kind in this._vertexBuffers) {
  41308. // using slice() to make a copy of the array and not just reference it
  41309. var data = this.getVerticesData(kind);
  41310. if (data instanceof Float32Array) {
  41311. vertexData.set(new Float32Array(data), kind);
  41312. }
  41313. else {
  41314. vertexData.set(data.slice(0), kind);
  41315. }
  41316. if (!stopChecking) {
  41317. var vb = this.getVertexBuffer(kind);
  41318. if (vb) {
  41319. updatable = vb.isUpdatable();
  41320. stopChecking = !updatable;
  41321. }
  41322. }
  41323. }
  41324. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  41325. geometry.delayLoadState = this.delayLoadState;
  41326. geometry.delayLoadingFile = this.delayLoadingFile;
  41327. geometry._delayLoadingFunction = this._delayLoadingFunction;
  41328. for (kind in this._delayInfo) {
  41329. geometry._delayInfo = geometry._delayInfo || [];
  41330. geometry._delayInfo.push(kind);
  41331. }
  41332. // Bounding info
  41333. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41334. return geometry;
  41335. };
  41336. /**
  41337. * Serialize the current geometry info (and not the vertices data) into a JSON object
  41338. * @return a JSON representation of the current geometry data (without the vertices data)
  41339. */
  41340. Geometry.prototype.serialize = function () {
  41341. var serializationObject = {};
  41342. serializationObject.id = this.id;
  41343. serializationObject.updatable = this._updatable;
  41344. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  41345. serializationObject.tags = BABYLON.Tags.GetTags(this);
  41346. }
  41347. return serializationObject;
  41348. };
  41349. Geometry.prototype.toNumberArray = function (origin) {
  41350. if (Array.isArray(origin)) {
  41351. return origin;
  41352. }
  41353. else {
  41354. return Array.prototype.slice.call(origin);
  41355. }
  41356. };
  41357. /**
  41358. * Serialize all vertices data into a JSON oject
  41359. * @returns a JSON representation of the current geometry data
  41360. */
  41361. Geometry.prototype.serializeVerticeData = function () {
  41362. var serializationObject = this.serialize();
  41363. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  41364. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  41365. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  41366. serializationObject.positions._updatable = true;
  41367. }
  41368. }
  41369. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41370. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  41371. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  41372. serializationObject.normals._updatable = true;
  41373. }
  41374. }
  41375. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41376. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  41377. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  41378. serializationObject.tangets._updatable = true;
  41379. }
  41380. }
  41381. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  41382. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  41383. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  41384. serializationObject.uvs._updatable = true;
  41385. }
  41386. }
  41387. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  41388. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  41389. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  41390. serializationObject.uv2s._updatable = true;
  41391. }
  41392. }
  41393. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  41394. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  41395. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  41396. serializationObject.uv3s._updatable = true;
  41397. }
  41398. }
  41399. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  41400. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  41401. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  41402. serializationObject.uv4s._updatable = true;
  41403. }
  41404. }
  41405. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  41406. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  41407. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  41408. serializationObject.uv5s._updatable = true;
  41409. }
  41410. }
  41411. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  41412. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  41413. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  41414. serializationObject.uv6s._updatable = true;
  41415. }
  41416. }
  41417. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  41418. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  41419. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  41420. serializationObject.colors._updatable = true;
  41421. }
  41422. }
  41423. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  41424. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  41425. serializationObject.matricesIndices._isExpanded = true;
  41426. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  41427. serializationObject.matricesIndices._updatable = true;
  41428. }
  41429. }
  41430. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  41431. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  41432. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  41433. serializationObject.matricesWeights._updatable = true;
  41434. }
  41435. }
  41436. serializationObject.indices = this.toNumberArray(this.getIndices());
  41437. return serializationObject;
  41438. };
  41439. // Statics
  41440. /**
  41441. * Extracts a clone of a mesh geometry
  41442. * @param mesh defines the source mesh
  41443. * @param id defines the unique ID of the new geometry object
  41444. * @returns the new geometry object
  41445. */
  41446. Geometry.ExtractFromMesh = function (mesh, id) {
  41447. var geometry = mesh._geometry;
  41448. if (!geometry) {
  41449. return null;
  41450. }
  41451. return geometry.copy(id);
  41452. };
  41453. /**
  41454. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  41455. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  41456. * Be aware Math.random() could cause collisions, but:
  41457. * "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"
  41458. * @returns a string containing a new GUID
  41459. */
  41460. Geometry.RandomId = function () {
  41461. return BABYLON.Tools.RandomId();
  41462. };
  41463. /** @hidden */
  41464. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  41465. var scene = mesh.getScene();
  41466. // Geometry
  41467. var geometryId = parsedGeometry.geometryId;
  41468. if (geometryId) {
  41469. var geometry = scene.getGeometryByID(geometryId);
  41470. if (geometry) {
  41471. geometry.applyToMesh(mesh);
  41472. }
  41473. }
  41474. else if (parsedGeometry instanceof ArrayBuffer) {
  41475. var binaryInfo = mesh._binaryInfo;
  41476. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  41477. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  41478. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  41479. }
  41480. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  41481. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  41482. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  41483. }
  41484. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  41485. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  41486. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  41487. }
  41488. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  41489. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  41490. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  41491. }
  41492. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  41493. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  41494. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  41495. }
  41496. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  41497. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  41498. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  41499. }
  41500. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  41501. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  41502. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  41503. }
  41504. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  41505. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  41506. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  41507. }
  41508. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  41509. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  41510. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  41511. }
  41512. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  41513. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  41514. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  41515. }
  41516. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  41517. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  41518. var floatIndices = [];
  41519. for (var i = 0; i < matricesIndicesData.length; i++) {
  41520. var index = matricesIndicesData[i];
  41521. floatIndices.push(index & 0x000000FF);
  41522. floatIndices.push((index & 0x0000FF00) >> 8);
  41523. floatIndices.push((index & 0x00FF0000) >> 16);
  41524. floatIndices.push(index >> 24);
  41525. }
  41526. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  41527. }
  41528. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  41529. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  41530. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  41531. }
  41532. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  41533. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  41534. mesh.setIndices(indicesData, null);
  41535. }
  41536. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  41537. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  41538. mesh.subMeshes = [];
  41539. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  41540. var materialIndex = subMeshesData[(i * 5) + 0];
  41541. var verticesStart = subMeshesData[(i * 5) + 1];
  41542. var verticesCount = subMeshesData[(i * 5) + 2];
  41543. var indexStart = subMeshesData[(i * 5) + 3];
  41544. var indexCount = subMeshesData[(i * 5) + 4];
  41545. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  41546. }
  41547. }
  41548. }
  41549. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  41550. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  41551. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  41552. if (parsedGeometry.tangents) {
  41553. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  41554. }
  41555. if (parsedGeometry.uvs) {
  41556. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  41557. }
  41558. if (parsedGeometry.uvs2) {
  41559. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  41560. }
  41561. if (parsedGeometry.uvs3) {
  41562. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  41563. }
  41564. if (parsedGeometry.uvs4) {
  41565. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  41566. }
  41567. if (parsedGeometry.uvs5) {
  41568. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  41569. }
  41570. if (parsedGeometry.uvs6) {
  41571. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  41572. }
  41573. if (parsedGeometry.colors) {
  41574. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  41575. }
  41576. if (parsedGeometry.matricesIndices) {
  41577. if (!parsedGeometry.matricesIndices._isExpanded) {
  41578. var floatIndices = [];
  41579. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  41580. var matricesIndex = parsedGeometry.matricesIndices[i];
  41581. floatIndices.push(matricesIndex & 0x000000FF);
  41582. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41583. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41584. floatIndices.push(matricesIndex >> 24);
  41585. }
  41586. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  41587. }
  41588. else {
  41589. delete parsedGeometry.matricesIndices._isExpanded;
  41590. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  41591. }
  41592. }
  41593. if (parsedGeometry.matricesIndicesExtra) {
  41594. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  41595. var floatIndices = [];
  41596. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  41597. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  41598. floatIndices.push(matricesIndex & 0x000000FF);
  41599. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41600. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41601. floatIndices.push(matricesIndex >> 24);
  41602. }
  41603. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  41604. }
  41605. else {
  41606. delete parsedGeometry.matricesIndices._isExpanded;
  41607. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  41608. }
  41609. }
  41610. if (parsedGeometry.matricesWeights) {
  41611. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  41612. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  41613. }
  41614. if (parsedGeometry.matricesWeightsExtra) {
  41615. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  41616. }
  41617. mesh.setIndices(parsedGeometry.indices, null);
  41618. }
  41619. // SubMeshes
  41620. if (parsedGeometry.subMeshes) {
  41621. mesh.subMeshes = [];
  41622. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  41623. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  41624. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  41625. }
  41626. }
  41627. // Flat shading
  41628. if (mesh._shouldGenerateFlatShading) {
  41629. mesh.convertToFlatShadedMesh();
  41630. delete mesh._shouldGenerateFlatShading;
  41631. }
  41632. // Update
  41633. mesh.computeWorldMatrix(true);
  41634. scene.onMeshImportedObservable.notifyObservers(mesh);
  41635. };
  41636. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  41637. var epsilon = 1e-3;
  41638. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  41639. return;
  41640. }
  41641. var noInfluenceBoneIndex = 0.0;
  41642. if (parsedGeometry.skeletonId > -1) {
  41643. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  41644. if (!skeleton) {
  41645. return;
  41646. }
  41647. noInfluenceBoneIndex = skeleton.bones.length;
  41648. }
  41649. else {
  41650. return;
  41651. }
  41652. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  41653. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41654. var matricesWeights = parsedGeometry.matricesWeights;
  41655. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  41656. var influencers = parsedGeometry.numBoneInfluencer;
  41657. var size = matricesWeights.length;
  41658. for (var i = 0; i < size; i += 4) {
  41659. var weight = 0.0;
  41660. var firstZeroWeight = -1;
  41661. for (var j = 0; j < 4; j++) {
  41662. var w = matricesWeights[i + j];
  41663. weight += w;
  41664. if (w < epsilon && firstZeroWeight < 0) {
  41665. firstZeroWeight = j;
  41666. }
  41667. }
  41668. if (matricesWeightsExtra) {
  41669. for (var j = 0; j < 4; j++) {
  41670. var w = matricesWeightsExtra[i + j];
  41671. weight += w;
  41672. if (w < epsilon && firstZeroWeight < 0) {
  41673. firstZeroWeight = j + 4;
  41674. }
  41675. }
  41676. }
  41677. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  41678. firstZeroWeight = influencers - 1;
  41679. }
  41680. if (weight > epsilon) {
  41681. var mweight = 1.0 / weight;
  41682. for (var j = 0; j < 4; j++) {
  41683. matricesWeights[i + j] *= mweight;
  41684. }
  41685. if (matricesWeightsExtra) {
  41686. for (var j = 0; j < 4; j++) {
  41687. matricesWeightsExtra[i + j] *= mweight;
  41688. }
  41689. }
  41690. }
  41691. else {
  41692. if (firstZeroWeight >= 4) {
  41693. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  41694. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  41695. }
  41696. else {
  41697. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  41698. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  41699. }
  41700. }
  41701. }
  41702. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  41703. if (parsedGeometry.matricesWeightsExtra) {
  41704. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  41705. }
  41706. };
  41707. /**
  41708. * Create a new geometry from persisted data (Using .babylon file format)
  41709. * @param parsedVertexData defines the persisted data
  41710. * @param scene defines the hosting scene
  41711. * @param rootUrl defines the root url to use to load assets (like delayed data)
  41712. * @returns the new geometry object
  41713. */
  41714. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  41715. if (scene.getGeometryByID(parsedVertexData.id)) {
  41716. return null; // null since geometry could be something else than a box...
  41717. }
  41718. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  41719. if (BABYLON.Tags) {
  41720. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  41721. }
  41722. if (parsedVertexData.delayLoadingFile) {
  41723. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41724. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  41725. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  41726. geometry._delayInfo = [];
  41727. if (parsedVertexData.hasUVs) {
  41728. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  41729. }
  41730. if (parsedVertexData.hasUVs2) {
  41731. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  41732. }
  41733. if (parsedVertexData.hasUVs3) {
  41734. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  41735. }
  41736. if (parsedVertexData.hasUVs4) {
  41737. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  41738. }
  41739. if (parsedVertexData.hasUVs5) {
  41740. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  41741. }
  41742. if (parsedVertexData.hasUVs6) {
  41743. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  41744. }
  41745. if (parsedVertexData.hasColors) {
  41746. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  41747. }
  41748. if (parsedVertexData.hasMatricesIndices) {
  41749. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41750. }
  41751. if (parsedVertexData.hasMatricesWeights) {
  41752. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41753. }
  41754. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  41755. }
  41756. else {
  41757. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  41758. }
  41759. scene.pushGeometry(geometry, true);
  41760. return geometry;
  41761. };
  41762. return Geometry;
  41763. }());
  41764. BABYLON.Geometry = Geometry;
  41765. // Primitives
  41766. /// Abstract class
  41767. /**
  41768. * Abstract class used to provide common services for all typed geometries
  41769. * @hidden
  41770. */
  41771. var _PrimitiveGeometry = /** @class */ (function (_super) {
  41772. __extends(_PrimitiveGeometry, _super);
  41773. /**
  41774. * Creates a new typed geometry
  41775. * @param id defines the unique ID of the geometry
  41776. * @param scene defines the hosting scene
  41777. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41778. * @param mesh defines the hosting mesh (can be null)
  41779. */
  41780. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  41781. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  41782. if (mesh === void 0) { mesh = null; }
  41783. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  41784. _this._canBeRegenerated = _canBeRegenerated;
  41785. _this._beingRegenerated = true;
  41786. _this.regenerate();
  41787. _this._beingRegenerated = false;
  41788. return _this;
  41789. }
  41790. /**
  41791. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  41792. * @returns true if the geometry can be regenerated
  41793. */
  41794. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  41795. return this._canBeRegenerated;
  41796. };
  41797. /**
  41798. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  41799. */
  41800. _PrimitiveGeometry.prototype.regenerate = function () {
  41801. if (!this._canBeRegenerated) {
  41802. return;
  41803. }
  41804. this._beingRegenerated = true;
  41805. this.setAllVerticesData(this._regenerateVertexData(), false);
  41806. this._beingRegenerated = false;
  41807. };
  41808. /**
  41809. * Clone the geometry
  41810. * @param id defines the unique ID of the new geometry
  41811. * @returns the new geometry
  41812. */
  41813. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  41814. return _super.prototype.copy.call(this, id);
  41815. };
  41816. // overrides
  41817. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  41818. if (!this._beingRegenerated) {
  41819. return;
  41820. }
  41821. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  41822. };
  41823. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  41824. if (!this._beingRegenerated) {
  41825. return;
  41826. }
  41827. _super.prototype.setVerticesData.call(this, kind, data, false);
  41828. };
  41829. // to override
  41830. /** @hidden */
  41831. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  41832. throw new Error("Abstract method");
  41833. };
  41834. _PrimitiveGeometry.prototype.copy = function (id) {
  41835. throw new Error("Must be overriden in sub-classes.");
  41836. };
  41837. _PrimitiveGeometry.prototype.serialize = function () {
  41838. var serializationObject = _super.prototype.serialize.call(this);
  41839. serializationObject.canBeRegenerated = this.canBeRegenerated();
  41840. return serializationObject;
  41841. };
  41842. return _PrimitiveGeometry;
  41843. }(Geometry));
  41844. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  41845. /**
  41846. * Creates a ribbon geometry
  41847. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  41848. */
  41849. var RibbonGeometry = /** @class */ (function (_super) {
  41850. __extends(RibbonGeometry, _super);
  41851. /**
  41852. * Creates a ribbon geometry
  41853. * @param id defines the unique ID of the geometry
  41854. * @param scene defines the hosting scene
  41855. * @param pathArray defines the array of paths to use
  41856. * @param closeArray defines if the last path and the first path must be joined
  41857. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  41858. * @param offset defines the offset between points
  41859. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41860. * @param mesh defines the hosting mesh (can be null)
  41861. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41862. */
  41863. function RibbonGeometry(id, scene,
  41864. /**
  41865. * Defines the array of paths to use
  41866. */
  41867. pathArray,
  41868. /**
  41869. * Defines if the last and first points of each path in your pathArray must be joined
  41870. */
  41871. closeArray,
  41872. /**
  41873. * Defines if the last and first points of each path in your pathArray must be joined
  41874. */
  41875. closePath,
  41876. /**
  41877. * Defines the offset between points
  41878. */
  41879. offset, canBeRegenerated, mesh,
  41880. /**
  41881. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41882. */
  41883. side) {
  41884. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41885. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41886. _this.pathArray = pathArray;
  41887. _this.closeArray = closeArray;
  41888. _this.closePath = closePath;
  41889. _this.offset = offset;
  41890. _this.side = side;
  41891. return _this;
  41892. }
  41893. /** @hidden */
  41894. RibbonGeometry.prototype._regenerateVertexData = function () {
  41895. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  41896. };
  41897. RibbonGeometry.prototype.copy = function (id) {
  41898. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  41899. };
  41900. return RibbonGeometry;
  41901. }(_PrimitiveGeometry));
  41902. BABYLON.RibbonGeometry = RibbonGeometry;
  41903. /**
  41904. * Creates a box geometry
  41905. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  41906. */
  41907. var BoxGeometry = /** @class */ (function (_super) {
  41908. __extends(BoxGeometry, _super);
  41909. /**
  41910. * Creates a box geometry
  41911. * @param id defines the unique ID of the geometry
  41912. * @param scene defines the hosting scene
  41913. * @param size defines the zise of the box (width, height and depth are the same)
  41914. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41915. * @param mesh defines the hosting mesh (can be null)
  41916. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41917. */
  41918. function BoxGeometry(id, scene,
  41919. /**
  41920. * Defines the zise of the box (width, height and depth are the same)
  41921. */
  41922. size, canBeRegenerated, mesh,
  41923. /**
  41924. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41925. */
  41926. side) {
  41927. if (mesh === void 0) { mesh = null; }
  41928. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41929. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41930. _this.size = size;
  41931. _this.side = side;
  41932. return _this;
  41933. }
  41934. /** @hidden */
  41935. BoxGeometry.prototype._regenerateVertexData = function () {
  41936. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  41937. };
  41938. BoxGeometry.prototype.copy = function (id) {
  41939. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  41940. };
  41941. BoxGeometry.prototype.serialize = function () {
  41942. var serializationObject = _super.prototype.serialize.call(this);
  41943. serializationObject.size = this.size;
  41944. return serializationObject;
  41945. };
  41946. BoxGeometry.Parse = function (parsedBox, scene) {
  41947. if (scene.getGeometryByID(parsedBox.id)) {
  41948. return null; // null since geometry could be something else than a box...
  41949. }
  41950. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  41951. if (BABYLON.Tags) {
  41952. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  41953. }
  41954. scene.pushGeometry(box, true);
  41955. return box;
  41956. };
  41957. return BoxGeometry;
  41958. }(_PrimitiveGeometry));
  41959. BABYLON.BoxGeometry = BoxGeometry;
  41960. /**
  41961. * Creates a sphere geometry
  41962. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  41963. */
  41964. var SphereGeometry = /** @class */ (function (_super) {
  41965. __extends(SphereGeometry, _super);
  41966. /**
  41967. * Create a new sphere geometry
  41968. * @param id defines the unique ID of the geometry
  41969. * @param scene defines the hosting scene
  41970. * @param segments defines the number of segments to use to create the sphere
  41971. * @param diameter defines the diameter of the sphere
  41972. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41973. * @param mesh defines the hosting mesh (can be null)
  41974. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41975. */
  41976. function SphereGeometry(id, scene,
  41977. /**
  41978. * Defines the number of segments to use to create the sphere
  41979. */
  41980. segments,
  41981. /**
  41982. * Defines the diameter of the sphere
  41983. */
  41984. diameter, canBeRegenerated, mesh,
  41985. /**
  41986. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41987. */
  41988. side) {
  41989. if (mesh === void 0) { mesh = null; }
  41990. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41991. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41992. _this.segments = segments;
  41993. _this.diameter = diameter;
  41994. _this.side = side;
  41995. return _this;
  41996. }
  41997. /** @hidden */
  41998. SphereGeometry.prototype._regenerateVertexData = function () {
  41999. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  42000. };
  42001. SphereGeometry.prototype.copy = function (id) {
  42002. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  42003. };
  42004. SphereGeometry.prototype.serialize = function () {
  42005. var serializationObject = _super.prototype.serialize.call(this);
  42006. serializationObject.segments = this.segments;
  42007. serializationObject.diameter = this.diameter;
  42008. return serializationObject;
  42009. };
  42010. SphereGeometry.Parse = function (parsedSphere, scene) {
  42011. if (scene.getGeometryByID(parsedSphere.id)) {
  42012. return null; // null since geometry could be something else than a sphere...
  42013. }
  42014. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  42015. if (BABYLON.Tags) {
  42016. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  42017. }
  42018. scene.pushGeometry(sphere, true);
  42019. return sphere;
  42020. };
  42021. return SphereGeometry;
  42022. }(_PrimitiveGeometry));
  42023. BABYLON.SphereGeometry = SphereGeometry;
  42024. /**
  42025. * Creates a disc geometry
  42026. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  42027. */
  42028. var DiscGeometry = /** @class */ (function (_super) {
  42029. __extends(DiscGeometry, _super);
  42030. /**
  42031. * Creates a new disc geometry
  42032. * @param id defines the unique ID of the geometry
  42033. * @param scene defines the hosting scene
  42034. * @param radius defines the radius of the disc
  42035. * @param tessellation defines the tesselation factor to apply to the disc
  42036. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42037. * @param mesh defines the hosting mesh (can be null)
  42038. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42039. */
  42040. function DiscGeometry(id, scene,
  42041. /**
  42042. * Defines the radius of the disc
  42043. */
  42044. radius,
  42045. /**
  42046. * Defines the tesselation factor to apply to the disc
  42047. */
  42048. tessellation, canBeRegenerated, mesh,
  42049. /**
  42050. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42051. */
  42052. side) {
  42053. if (mesh === void 0) { mesh = null; }
  42054. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42055. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42056. _this.radius = radius;
  42057. _this.tessellation = tessellation;
  42058. _this.side = side;
  42059. return _this;
  42060. }
  42061. /** @hidden */
  42062. DiscGeometry.prototype._regenerateVertexData = function () {
  42063. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  42064. };
  42065. DiscGeometry.prototype.copy = function (id) {
  42066. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  42067. };
  42068. return DiscGeometry;
  42069. }(_PrimitiveGeometry));
  42070. BABYLON.DiscGeometry = DiscGeometry;
  42071. /**
  42072. * Creates a new cylinder geometry
  42073. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  42074. */
  42075. var CylinderGeometry = /** @class */ (function (_super) {
  42076. __extends(CylinderGeometry, _super);
  42077. /**
  42078. * Creates a new cylinder geometry
  42079. * @param id defines the unique ID of the geometry
  42080. * @param scene defines the hosting scene
  42081. * @param height defines the height of the cylinder
  42082. * @param diameterTop defines the diameter of the cylinder's top cap
  42083. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  42084. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  42085. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  42086. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42087. * @param mesh defines the hosting mesh (can be null)
  42088. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42089. */
  42090. function CylinderGeometry(id, scene,
  42091. /**
  42092. * Defines the height of the cylinder
  42093. */
  42094. height,
  42095. /**
  42096. * Defines the diameter of the cylinder's top cap
  42097. */
  42098. diameterTop,
  42099. /**
  42100. * Defines the diameter of the cylinder's bottom cap
  42101. */
  42102. diameterBottom,
  42103. /**
  42104. * Defines the tessellation factor to apply to the cylinder
  42105. */
  42106. tessellation,
  42107. /**
  42108. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  42109. */
  42110. subdivisions, canBeRegenerated, mesh,
  42111. /**
  42112. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42113. */
  42114. side) {
  42115. if (subdivisions === void 0) { subdivisions = 1; }
  42116. if (mesh === void 0) { mesh = null; }
  42117. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42118. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42119. _this.height = height;
  42120. _this.diameterTop = diameterTop;
  42121. _this.diameterBottom = diameterBottom;
  42122. _this.tessellation = tessellation;
  42123. _this.subdivisions = subdivisions;
  42124. _this.side = side;
  42125. return _this;
  42126. }
  42127. /** @hidden */
  42128. CylinderGeometry.prototype._regenerateVertexData = function () {
  42129. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  42130. };
  42131. CylinderGeometry.prototype.copy = function (id) {
  42132. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  42133. };
  42134. CylinderGeometry.prototype.serialize = function () {
  42135. var serializationObject = _super.prototype.serialize.call(this);
  42136. serializationObject.height = this.height;
  42137. serializationObject.diameterTop = this.diameterTop;
  42138. serializationObject.diameterBottom = this.diameterBottom;
  42139. serializationObject.tessellation = this.tessellation;
  42140. return serializationObject;
  42141. };
  42142. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  42143. if (scene.getGeometryByID(parsedCylinder.id)) {
  42144. return null; // null since geometry could be something else than a cylinder...
  42145. }
  42146. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  42147. if (BABYLON.Tags) {
  42148. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  42149. }
  42150. scene.pushGeometry(cylinder, true);
  42151. return cylinder;
  42152. };
  42153. return CylinderGeometry;
  42154. }(_PrimitiveGeometry));
  42155. BABYLON.CylinderGeometry = CylinderGeometry;
  42156. /**
  42157. * Creates a new torus geometry
  42158. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  42159. */
  42160. var TorusGeometry = /** @class */ (function (_super) {
  42161. __extends(TorusGeometry, _super);
  42162. /**
  42163. * Creates a new torus geometry
  42164. * @param id defines the unique ID of the geometry
  42165. * @param scene defines the hosting scene
  42166. * @param diameter defines the diameter of the torus
  42167. * @param thickness defines the thickness of the torus (ie. internal diameter)
  42168. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  42169. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42170. * @param mesh defines the hosting mesh (can be null)
  42171. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42172. */
  42173. function TorusGeometry(id, scene,
  42174. /**
  42175. * Defines the diameter of the torus
  42176. */
  42177. diameter,
  42178. /**
  42179. * Defines the thickness of the torus (ie. internal diameter)
  42180. */
  42181. thickness,
  42182. /**
  42183. * Defines the tesselation factor to apply to the torus
  42184. */
  42185. tessellation, canBeRegenerated, mesh,
  42186. /**
  42187. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42188. */
  42189. side) {
  42190. if (mesh === void 0) { mesh = null; }
  42191. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42192. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42193. _this.diameter = diameter;
  42194. _this.thickness = thickness;
  42195. _this.tessellation = tessellation;
  42196. _this.side = side;
  42197. return _this;
  42198. }
  42199. /** @hidden */
  42200. TorusGeometry.prototype._regenerateVertexData = function () {
  42201. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  42202. };
  42203. TorusGeometry.prototype.copy = function (id) {
  42204. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  42205. };
  42206. TorusGeometry.prototype.serialize = function () {
  42207. var serializationObject = _super.prototype.serialize.call(this);
  42208. serializationObject.diameter = this.diameter;
  42209. serializationObject.thickness = this.thickness;
  42210. serializationObject.tessellation = this.tessellation;
  42211. return serializationObject;
  42212. };
  42213. TorusGeometry.Parse = function (parsedTorus, scene) {
  42214. if (scene.getGeometryByID(parsedTorus.id)) {
  42215. return null; // null since geometry could be something else than a torus...
  42216. }
  42217. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  42218. if (BABYLON.Tags) {
  42219. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  42220. }
  42221. scene.pushGeometry(torus, true);
  42222. return torus;
  42223. };
  42224. return TorusGeometry;
  42225. }(_PrimitiveGeometry));
  42226. BABYLON.TorusGeometry = TorusGeometry;
  42227. /**
  42228. * Creates a new ground geometry
  42229. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  42230. */
  42231. var GroundGeometry = /** @class */ (function (_super) {
  42232. __extends(GroundGeometry, _super);
  42233. /**
  42234. * Creates a new ground geometry
  42235. * @param id defines the unique ID of the geometry
  42236. * @param scene defines the hosting scene
  42237. * @param width defines the width of the ground
  42238. * @param height defines the height of the ground
  42239. * @param subdivisions defines the subdivisions to apply to the ground
  42240. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42241. * @param mesh defines the hosting mesh (can be null)
  42242. */
  42243. function GroundGeometry(id, scene,
  42244. /**
  42245. * Defines the width of the ground
  42246. */
  42247. width,
  42248. /**
  42249. * Defines the height of the ground
  42250. */
  42251. height,
  42252. /**
  42253. * Defines the subdivisions to apply to the ground
  42254. */
  42255. subdivisions, canBeRegenerated, mesh) {
  42256. if (mesh === void 0) { mesh = null; }
  42257. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42258. _this.width = width;
  42259. _this.height = height;
  42260. _this.subdivisions = subdivisions;
  42261. return _this;
  42262. }
  42263. /** @hidden */
  42264. GroundGeometry.prototype._regenerateVertexData = function () {
  42265. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  42266. };
  42267. GroundGeometry.prototype.copy = function (id) {
  42268. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  42269. };
  42270. GroundGeometry.prototype.serialize = function () {
  42271. var serializationObject = _super.prototype.serialize.call(this);
  42272. serializationObject.width = this.width;
  42273. serializationObject.height = this.height;
  42274. serializationObject.subdivisions = this.subdivisions;
  42275. return serializationObject;
  42276. };
  42277. GroundGeometry.Parse = function (parsedGround, scene) {
  42278. if (scene.getGeometryByID(parsedGround.id)) {
  42279. return null; // null since geometry could be something else than a ground...
  42280. }
  42281. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  42282. if (BABYLON.Tags) {
  42283. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  42284. }
  42285. scene.pushGeometry(ground, true);
  42286. return ground;
  42287. };
  42288. return GroundGeometry;
  42289. }(_PrimitiveGeometry));
  42290. BABYLON.GroundGeometry = GroundGeometry;
  42291. /**
  42292. * Creates a tiled ground geometry
  42293. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  42294. */
  42295. var TiledGroundGeometry = /** @class */ (function (_super) {
  42296. __extends(TiledGroundGeometry, _super);
  42297. /**
  42298. * Creates a tiled ground geometry
  42299. * @param id defines the unique ID of the geometry
  42300. * @param scene defines the hosting scene
  42301. * @param xmin defines the minimum value on X axis
  42302. * @param zmin defines the minimum value on Z axis
  42303. * @param xmax defines the maximum value on X axis
  42304. * @param zmax defines the maximum value on Z axis
  42305. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  42306. * @param precision defines the precision to use when computing the tiles
  42307. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42308. * @param mesh defines the hosting mesh (can be null)
  42309. */
  42310. function TiledGroundGeometry(id, scene,
  42311. /**
  42312. * Defines the minimum value on X axis
  42313. */
  42314. xmin,
  42315. /**
  42316. * Defines the minimum value on Z axis
  42317. */
  42318. zmin,
  42319. /**
  42320. * Defines the maximum value on X axis
  42321. */
  42322. xmax,
  42323. /**
  42324. * Defines the maximum value on Z axis
  42325. */
  42326. zmax,
  42327. /**
  42328. * Defines the subdivisions to apply to the ground
  42329. */
  42330. subdivisions,
  42331. /**
  42332. * Defines the precision to use when computing the tiles
  42333. */
  42334. precision, canBeRegenerated, mesh) {
  42335. if (mesh === void 0) { mesh = null; }
  42336. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42337. _this.xmin = xmin;
  42338. _this.zmin = zmin;
  42339. _this.xmax = xmax;
  42340. _this.zmax = zmax;
  42341. _this.subdivisions = subdivisions;
  42342. _this.precision = precision;
  42343. return _this;
  42344. }
  42345. /** @hidden */
  42346. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  42347. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  42348. };
  42349. TiledGroundGeometry.prototype.copy = function (id) {
  42350. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  42351. };
  42352. return TiledGroundGeometry;
  42353. }(_PrimitiveGeometry));
  42354. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  42355. /**
  42356. * Creates a plane geometry
  42357. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  42358. */
  42359. var PlaneGeometry = /** @class */ (function (_super) {
  42360. __extends(PlaneGeometry, _super);
  42361. /**
  42362. * Creates a plane geometry
  42363. * @param id defines the unique ID of the geometry
  42364. * @param scene defines the hosting scene
  42365. * @param size defines the size of the plane (width === height)
  42366. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42367. * @param mesh defines the hosting mesh (can be null)
  42368. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42369. */
  42370. function PlaneGeometry(id, scene,
  42371. /**
  42372. * Defines the size of the plane (width === height)
  42373. */
  42374. size, canBeRegenerated, mesh,
  42375. /**
  42376. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42377. */
  42378. side) {
  42379. if (mesh === void 0) { mesh = null; }
  42380. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42381. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42382. _this.size = size;
  42383. _this.side = side;
  42384. return _this;
  42385. }
  42386. /** @hidden */
  42387. PlaneGeometry.prototype._regenerateVertexData = function () {
  42388. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  42389. };
  42390. PlaneGeometry.prototype.copy = function (id) {
  42391. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  42392. };
  42393. PlaneGeometry.prototype.serialize = function () {
  42394. var serializationObject = _super.prototype.serialize.call(this);
  42395. serializationObject.size = this.size;
  42396. return serializationObject;
  42397. };
  42398. PlaneGeometry.Parse = function (parsedPlane, scene) {
  42399. if (scene.getGeometryByID(parsedPlane.id)) {
  42400. return null; // null since geometry could be something else than a ground...
  42401. }
  42402. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  42403. if (BABYLON.Tags) {
  42404. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  42405. }
  42406. scene.pushGeometry(plane, true);
  42407. return plane;
  42408. };
  42409. return PlaneGeometry;
  42410. }(_PrimitiveGeometry));
  42411. BABYLON.PlaneGeometry = PlaneGeometry;
  42412. /**
  42413. * Creates a torus knot geometry
  42414. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  42415. */
  42416. var TorusKnotGeometry = /** @class */ (function (_super) {
  42417. __extends(TorusKnotGeometry, _super);
  42418. /**
  42419. * Creates a torus knot geometry
  42420. * @param id defines the unique ID of the geometry
  42421. * @param scene defines the hosting scene
  42422. * @param radius defines the radius of the torus knot
  42423. * @param tube defines the thickness of the torus knot tube
  42424. * @param radialSegments defines the number of radial segments
  42425. * @param tubularSegments defines the number of tubular segments
  42426. * @param p defines the first number of windings
  42427. * @param q defines the second number of windings
  42428. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  42429. * @param mesh defines the hosting mesh (can be null)
  42430. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42431. */
  42432. function TorusKnotGeometry(id, scene,
  42433. /**
  42434. * Defines the radius of the torus knot
  42435. */
  42436. radius,
  42437. /**
  42438. * Defines the thickness of the torus knot tube
  42439. */
  42440. tube,
  42441. /**
  42442. * Defines the number of radial segments
  42443. */
  42444. radialSegments,
  42445. /**
  42446. * Defines the number of tubular segments
  42447. */
  42448. tubularSegments,
  42449. /**
  42450. * Defines the first number of windings
  42451. */
  42452. p,
  42453. /**
  42454. * Defines the second number of windings
  42455. */
  42456. q, canBeRegenerated, mesh,
  42457. /**
  42458. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  42459. */
  42460. side) {
  42461. if (mesh === void 0) { mesh = null; }
  42462. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  42463. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  42464. _this.radius = radius;
  42465. _this.tube = tube;
  42466. _this.radialSegments = radialSegments;
  42467. _this.tubularSegments = tubularSegments;
  42468. _this.p = p;
  42469. _this.q = q;
  42470. _this.side = side;
  42471. return _this;
  42472. }
  42473. /** @hidden */
  42474. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  42475. 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 });
  42476. };
  42477. TorusKnotGeometry.prototype.copy = function (id) {
  42478. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  42479. };
  42480. TorusKnotGeometry.prototype.serialize = function () {
  42481. var serializationObject = _super.prototype.serialize.call(this);
  42482. serializationObject.radius = this.radius;
  42483. serializationObject.tube = this.tube;
  42484. serializationObject.radialSegments = this.radialSegments;
  42485. serializationObject.tubularSegments = this.tubularSegments;
  42486. serializationObject.p = this.p;
  42487. serializationObject.q = this.q;
  42488. return serializationObject;
  42489. };
  42490. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  42491. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  42492. return null; // null since geometry could be something else than a ground...
  42493. }
  42494. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  42495. if (BABYLON.Tags) {
  42496. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  42497. }
  42498. scene.pushGeometry(torusKnot, true);
  42499. return torusKnot;
  42500. };
  42501. return TorusKnotGeometry;
  42502. }(_PrimitiveGeometry));
  42503. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  42504. //}
  42505. })(BABYLON || (BABYLON = {}));
  42506. //# sourceMappingURL=geometry.js.map
  42507. var BABYLON;
  42508. (function (BABYLON) {
  42509. /**
  42510. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  42511. */
  42512. var PerformanceMonitor = /** @class */ (function () {
  42513. /**
  42514. * constructor
  42515. * @param frameSampleSize The number of samples required to saturate the sliding window
  42516. */
  42517. function PerformanceMonitor(frameSampleSize) {
  42518. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  42519. this._enabled = true;
  42520. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  42521. }
  42522. /**
  42523. * Samples current frame
  42524. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  42525. */
  42526. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  42527. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  42528. if (!this._enabled) {
  42529. return;
  42530. }
  42531. if (this._lastFrameTimeMs != null) {
  42532. var dt = timeMs - this._lastFrameTimeMs;
  42533. this._rollingFrameTime.add(dt);
  42534. }
  42535. this._lastFrameTimeMs = timeMs;
  42536. };
  42537. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  42538. /**
  42539. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  42540. */
  42541. get: function () {
  42542. return this._rollingFrameTime.average;
  42543. },
  42544. enumerable: true,
  42545. configurable: true
  42546. });
  42547. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  42548. /**
  42549. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  42550. */
  42551. get: function () {
  42552. return this._rollingFrameTime.variance;
  42553. },
  42554. enumerable: true,
  42555. configurable: true
  42556. });
  42557. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  42558. /**
  42559. * Returns the frame time of the most recent frame
  42560. */
  42561. get: function () {
  42562. return this._rollingFrameTime.history(0);
  42563. },
  42564. enumerable: true,
  42565. configurable: true
  42566. });
  42567. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  42568. /**
  42569. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  42570. */
  42571. get: function () {
  42572. return 1000.0 / this._rollingFrameTime.average;
  42573. },
  42574. enumerable: true,
  42575. configurable: true
  42576. });
  42577. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  42578. /**
  42579. * Returns the average framerate in frames per second using the most recent frame time
  42580. */
  42581. get: function () {
  42582. var history = this._rollingFrameTime.history(0);
  42583. if (history === 0) {
  42584. return 0;
  42585. }
  42586. return 1000.0 / history;
  42587. },
  42588. enumerable: true,
  42589. configurable: true
  42590. });
  42591. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  42592. /**
  42593. * Returns true if enough samples have been taken to completely fill the sliding window
  42594. */
  42595. get: function () {
  42596. return this._rollingFrameTime.isSaturated();
  42597. },
  42598. enumerable: true,
  42599. configurable: true
  42600. });
  42601. /**
  42602. * Enables contributions to the sliding window sample set
  42603. */
  42604. PerformanceMonitor.prototype.enable = function () {
  42605. this._enabled = true;
  42606. };
  42607. /**
  42608. * Disables contributions to the sliding window sample set
  42609. * Samples will not be interpolated over the disabled period
  42610. */
  42611. PerformanceMonitor.prototype.disable = function () {
  42612. this._enabled = false;
  42613. //clear last sample to avoid interpolating over the disabled period when next enabled
  42614. this._lastFrameTimeMs = null;
  42615. };
  42616. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  42617. /**
  42618. * Returns true if sampling is enabled
  42619. */
  42620. get: function () {
  42621. return this._enabled;
  42622. },
  42623. enumerable: true,
  42624. configurable: true
  42625. });
  42626. /**
  42627. * Resets performance monitor
  42628. */
  42629. PerformanceMonitor.prototype.reset = function () {
  42630. //clear last sample to avoid interpolating over the disabled period when next enabled
  42631. this._lastFrameTimeMs = null;
  42632. //wipe record
  42633. this._rollingFrameTime.reset();
  42634. };
  42635. return PerformanceMonitor;
  42636. }());
  42637. BABYLON.PerformanceMonitor = PerformanceMonitor;
  42638. /**
  42639. * RollingAverage
  42640. *
  42641. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  42642. */
  42643. var RollingAverage = /** @class */ (function () {
  42644. /**
  42645. * constructor
  42646. * @param length The number of samples required to saturate the sliding window
  42647. */
  42648. function RollingAverage(length) {
  42649. this._samples = new Array(length);
  42650. this.reset();
  42651. }
  42652. /**
  42653. * Adds a sample to the sample set
  42654. * @param v The sample value
  42655. */
  42656. RollingAverage.prototype.add = function (v) {
  42657. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  42658. var delta;
  42659. //we need to check if we've already wrapped round
  42660. if (this.isSaturated()) {
  42661. //remove bottom of stack from mean
  42662. var bottomValue = this._samples[this._pos];
  42663. delta = bottomValue - this.average;
  42664. this.average -= delta / (this._sampleCount - 1);
  42665. this._m2 -= delta * (bottomValue - this.average);
  42666. }
  42667. else {
  42668. this._sampleCount++;
  42669. }
  42670. //add new value to mean
  42671. delta = v - this.average;
  42672. this.average += delta / (this._sampleCount);
  42673. this._m2 += delta * (v - this.average);
  42674. //set the new variance
  42675. this.variance = this._m2 / (this._sampleCount - 1);
  42676. this._samples[this._pos] = v;
  42677. this._pos++;
  42678. this._pos %= this._samples.length; //positive wrap around
  42679. };
  42680. /**
  42681. * Returns previously added values or null if outside of history or outside the sliding window domain
  42682. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  42683. * @return Value previously recorded with add() or null if outside of range
  42684. */
  42685. RollingAverage.prototype.history = function (i) {
  42686. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  42687. return 0;
  42688. }
  42689. var i0 = this._wrapPosition(this._pos - 1.0);
  42690. return this._samples[this._wrapPosition(i0 - i)];
  42691. };
  42692. /**
  42693. * Returns true if enough samples have been taken to completely fill the sliding window
  42694. * @return true if sample-set saturated
  42695. */
  42696. RollingAverage.prototype.isSaturated = function () {
  42697. return this._sampleCount >= this._samples.length;
  42698. };
  42699. /**
  42700. * Resets the rolling average (equivalent to 0 samples taken so far)
  42701. */
  42702. RollingAverage.prototype.reset = function () {
  42703. this.average = 0;
  42704. this.variance = 0;
  42705. this._sampleCount = 0;
  42706. this._pos = 0;
  42707. this._m2 = 0;
  42708. };
  42709. /**
  42710. * Wraps a value around the sample range boundaries
  42711. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  42712. * @return Wrapped position in sample range
  42713. */
  42714. RollingAverage.prototype._wrapPosition = function (i) {
  42715. var max = this._samples.length;
  42716. return ((i % max) + max) % max;
  42717. };
  42718. return RollingAverage;
  42719. }());
  42720. BABYLON.RollingAverage = RollingAverage;
  42721. })(BABYLON || (BABYLON = {}));
  42722. //# sourceMappingURL=performanceMonitor.js.map
  42723. var BABYLON;
  42724. (function (BABYLON) {
  42725. /**
  42726. * "Static Class" containing the most commonly used helper while dealing with material for
  42727. * rendering purpose.
  42728. *
  42729. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42730. *
  42731. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42732. */
  42733. var MaterialHelper = /** @class */ (function () {
  42734. function MaterialHelper() {
  42735. }
  42736. /**
  42737. * Bind the current view position to an effect.
  42738. * @param effect The effect to be bound
  42739. * @param scene The scene the eyes position is used from
  42740. */
  42741. MaterialHelper.BindEyePosition = function (effect, scene) {
  42742. if (scene._forcedViewPosition) {
  42743. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42744. return;
  42745. }
  42746. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42747. };
  42748. /**
  42749. * Helps preparing the defines values about the UVs in used in the effect.
  42750. * UVs are shared as much as we can accross channels in the shaders.
  42751. * @param texture The texture we are preparing the UVs for
  42752. * @param defines The defines to update
  42753. * @param key The channel key "diffuse", "specular"... used in the shader
  42754. */
  42755. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42756. defines._needUVs = true;
  42757. defines[key] = true;
  42758. if (texture.getTextureMatrix().isIdentityAs3x2()) {
  42759. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42760. if (texture.coordinatesIndex === 0) {
  42761. defines["MAINUV1"] = true;
  42762. }
  42763. else {
  42764. defines["MAINUV2"] = true;
  42765. }
  42766. }
  42767. else {
  42768. defines[key + "DIRECTUV"] = 0;
  42769. }
  42770. };
  42771. /**
  42772. * Binds a texture matrix value to its corrsponding uniform
  42773. * @param texture The texture to bind the matrix for
  42774. * @param uniformBuffer The uniform buffer receivin the data
  42775. * @param key The channel key "diffuse", "specular"... used in the shader
  42776. */
  42777. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42778. var matrix = texture.getTextureMatrix();
  42779. if (!matrix.isIdentityAs3x2()) {
  42780. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42781. }
  42782. };
  42783. /**
  42784. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42785. * @param mesh defines the current mesh
  42786. * @param scene defines the current scene
  42787. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42788. * @param pointsCloud defines if point cloud rendering has to be turned on
  42789. * @param fogEnabled defines if fog has to be turned on
  42790. * @param alphaTest defines if alpha testing has to be turned on
  42791. * @param defines defines the current list of defines
  42792. */
  42793. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42794. if (defines._areMiscDirty) {
  42795. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42796. defines["POINTSIZE"] = pointsCloud;
  42797. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42798. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42799. defines["ALPHATEST"] = alphaTest;
  42800. }
  42801. };
  42802. /**
  42803. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42804. * @param scene defines the current scene
  42805. * @param engine defines the current engine
  42806. * @param defines specifies the list of active defines
  42807. * @param useInstances defines if instances have to be turned on
  42808. * @param useClipPlane defines if clip plane have to be turned on
  42809. */
  42810. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42811. if (useClipPlane === void 0) { useClipPlane = null; }
  42812. var changed = false;
  42813. var useClipPlane1 = false;
  42814. var useClipPlane2 = false;
  42815. var useClipPlane3 = false;
  42816. var useClipPlane4 = false;
  42817. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  42818. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  42819. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  42820. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  42821. if (defines["CLIPPLANE"] !== useClipPlane1) {
  42822. defines["CLIPPLANE"] = useClipPlane1;
  42823. changed = true;
  42824. }
  42825. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  42826. defines["CLIPPLANE2"] = useClipPlane2;
  42827. changed = true;
  42828. }
  42829. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  42830. defines["CLIPPLANE3"] = useClipPlane3;
  42831. changed = true;
  42832. }
  42833. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  42834. defines["CLIPPLANE4"] = useClipPlane4;
  42835. changed = true;
  42836. }
  42837. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42838. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42839. changed = true;
  42840. }
  42841. if (defines["INSTANCES"] !== useInstances) {
  42842. defines["INSTANCES"] = useInstances;
  42843. changed = true;
  42844. }
  42845. if (changed) {
  42846. defines.markAsUnprocessed();
  42847. }
  42848. };
  42849. /**
  42850. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42851. * @param mesh The mesh containing the geometry data we will draw
  42852. * @param defines The defines to update
  42853. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42854. * @param useBones Precise whether bones should be used or not (override mesh info)
  42855. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42856. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42857. * @returns false if defines are considered not dirty and have not been checked
  42858. */
  42859. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42860. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42861. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42862. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42863. return false;
  42864. }
  42865. defines._normals = defines._needNormals;
  42866. defines._uvs = defines._needUVs;
  42867. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42868. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42869. defines["TANGENT"] = true;
  42870. }
  42871. if (defines._needUVs) {
  42872. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42873. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42874. }
  42875. else {
  42876. defines["UV1"] = false;
  42877. defines["UV2"] = false;
  42878. }
  42879. if (useVertexColor) {
  42880. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42881. defines["VERTEXCOLOR"] = hasVertexColors;
  42882. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42883. }
  42884. if (useBones) {
  42885. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42886. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42887. var materialSupportsBoneTexture = defines["BONETEXTURE"] !== undefined;
  42888. if (mesh.skeleton.isUsingTextureForMatrices && materialSupportsBoneTexture) {
  42889. defines["BONETEXTURE"] = true;
  42890. }
  42891. else {
  42892. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42893. defines["BONETEXTURE"] = materialSupportsBoneTexture ? false : undefined;
  42894. }
  42895. }
  42896. else {
  42897. defines["NUM_BONE_INFLUENCERS"] = 0;
  42898. defines["BonesPerMesh"] = 0;
  42899. }
  42900. }
  42901. if (useMorphTargets) {
  42902. var manager = mesh.morphTargetManager;
  42903. if (manager) {
  42904. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42905. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42906. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42907. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42908. }
  42909. else {
  42910. defines["MORPHTARGETS_TANGENT"] = false;
  42911. defines["MORPHTARGETS_NORMAL"] = false;
  42912. defines["MORPHTARGETS"] = false;
  42913. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42914. }
  42915. }
  42916. return true;
  42917. };
  42918. /**
  42919. * Prepares the defines related to the light information passed in parameter
  42920. * @param scene The scene we are intending to draw
  42921. * @param mesh The mesh the effect is compiling for
  42922. * @param defines The defines to update
  42923. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42924. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42925. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42926. * @returns true if normals will be required for the rest of the effect
  42927. */
  42928. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42929. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42930. if (disableLighting === void 0) { disableLighting = false; }
  42931. if (!defines._areLightsDirty) {
  42932. return defines._needNormals;
  42933. }
  42934. var lightIndex = 0;
  42935. var needNormals = false;
  42936. var needRebuild = false;
  42937. var lightmapMode = false;
  42938. var shadowEnabled = false;
  42939. var specularEnabled = false;
  42940. if (scene.lightsEnabled && !disableLighting) {
  42941. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42942. var light = _a[_i];
  42943. needNormals = true;
  42944. if (defines["LIGHT" + lightIndex] === undefined) {
  42945. needRebuild = true;
  42946. }
  42947. defines["LIGHT" + lightIndex] = true;
  42948. defines["SPOTLIGHT" + lightIndex] = false;
  42949. defines["HEMILIGHT" + lightIndex] = false;
  42950. defines["POINTLIGHT" + lightIndex] = false;
  42951. defines["DIRLIGHT" + lightIndex] = false;
  42952. light.prepareLightSpecificDefines(defines, lightIndex);
  42953. // FallOff.
  42954. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  42955. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  42956. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  42957. switch (light.falloffType) {
  42958. case BABYLON.Light.FALLOFF_GLTF:
  42959. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  42960. break;
  42961. case BABYLON.Light.FALLOFF_PHYSICAL:
  42962. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  42963. break;
  42964. case BABYLON.Light.FALLOFF_STANDARD:
  42965. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  42966. break;
  42967. }
  42968. // Specular
  42969. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42970. specularEnabled = true;
  42971. }
  42972. // Shadows
  42973. defines["SHADOW" + lightIndex] = false;
  42974. defines["SHADOWPCF" + lightIndex] = false;
  42975. defines["SHADOWPCSS" + lightIndex] = false;
  42976. defines["SHADOWPOISSON" + lightIndex] = false;
  42977. defines["SHADOWESM" + lightIndex] = false;
  42978. defines["SHADOWCUBE" + lightIndex] = false;
  42979. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42980. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42981. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42982. var shadowGenerator = light.getShadowGenerator();
  42983. if (shadowGenerator) {
  42984. var shadowMap = shadowGenerator.getShadowMap();
  42985. if (shadowMap) {
  42986. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  42987. shadowEnabled = true;
  42988. shadowGenerator.prepareDefines(defines, lightIndex);
  42989. }
  42990. }
  42991. }
  42992. }
  42993. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42994. lightmapMode = true;
  42995. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42996. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42997. }
  42998. else {
  42999. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  43000. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  43001. }
  43002. lightIndex++;
  43003. if (lightIndex === maxSimultaneousLights) {
  43004. break;
  43005. }
  43006. }
  43007. }
  43008. defines["SPECULARTERM"] = specularEnabled;
  43009. defines["SHADOWS"] = shadowEnabled;
  43010. // Resetting all other lights if any
  43011. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  43012. if (defines["LIGHT" + index] !== undefined) {
  43013. defines["LIGHT" + index] = false;
  43014. defines["HEMILIGHT" + lightIndex] = false;
  43015. defines["POINTLIGHT" + lightIndex] = false;
  43016. defines["DIRLIGHT" + lightIndex] = false;
  43017. defines["SPOTLIGHT" + lightIndex] = false;
  43018. defines["SHADOW" + lightIndex] = false;
  43019. }
  43020. }
  43021. var caps = scene.getEngine().getCaps();
  43022. if (defines["SHADOWFLOAT"] === undefined) {
  43023. needRebuild = true;
  43024. }
  43025. defines["SHADOWFLOAT"] = shadowEnabled &&
  43026. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  43027. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  43028. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  43029. if (needRebuild) {
  43030. defines.rebuild();
  43031. }
  43032. return needNormals;
  43033. };
  43034. /**
  43035. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  43036. * that won t be acctive due to defines being turned off.
  43037. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  43038. * @param samplersList The samplers list
  43039. * @param defines The defines helping in the list generation
  43040. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  43041. */
  43042. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  43043. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  43044. var uniformsList;
  43045. var uniformBuffersList = null;
  43046. if (uniformsListOrOptions.uniformsNames) {
  43047. var options = uniformsListOrOptions;
  43048. uniformsList = options.uniformsNames;
  43049. uniformBuffersList = options.uniformBuffersNames;
  43050. samplersList = options.samplers;
  43051. defines = options.defines;
  43052. maxSimultaneousLights = options.maxSimultaneousLights;
  43053. }
  43054. else {
  43055. uniformsList = uniformsListOrOptions;
  43056. if (!samplersList) {
  43057. samplersList = [];
  43058. }
  43059. }
  43060. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  43061. if (!defines["LIGHT" + lightIndex]) {
  43062. break;
  43063. }
  43064. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  43065. if (uniformBuffersList) {
  43066. uniformBuffersList.push("Light" + lightIndex);
  43067. }
  43068. samplersList.push("shadowSampler" + lightIndex);
  43069. samplersList.push("depthSampler" + lightIndex);
  43070. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  43071. samplersList.push("projectionLightSampler" + lightIndex);
  43072. uniformsList.push("textureProjectionMatrix" + lightIndex);
  43073. }
  43074. }
  43075. if (defines["NUM_MORPH_INFLUENCERS"]) {
  43076. uniformsList.push("morphTargetInfluences");
  43077. }
  43078. };
  43079. /**
  43080. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  43081. * @param defines The defines to update while falling back
  43082. * @param fallbacks The authorized effect fallbacks
  43083. * @param maxSimultaneousLights The maximum number of lights allowed
  43084. * @param rank the current rank of the Effect
  43085. * @returns The newly affected rank
  43086. */
  43087. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  43088. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  43089. if (rank === void 0) { rank = 0; }
  43090. var lightFallbackRank = 0;
  43091. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  43092. if (!defines["LIGHT" + lightIndex]) {
  43093. break;
  43094. }
  43095. if (lightIndex > 0) {
  43096. lightFallbackRank = rank + lightIndex;
  43097. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  43098. }
  43099. if (!defines["SHADOWS"]) {
  43100. if (defines["SHADOW" + lightIndex]) {
  43101. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  43102. }
  43103. if (defines["SHADOWPCF" + lightIndex]) {
  43104. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  43105. }
  43106. if (defines["SHADOWPCSS" + lightIndex]) {
  43107. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  43108. }
  43109. if (defines["SHADOWPOISSON" + lightIndex]) {
  43110. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  43111. }
  43112. if (defines["SHADOWESM" + lightIndex]) {
  43113. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  43114. }
  43115. }
  43116. }
  43117. return lightFallbackRank++;
  43118. };
  43119. /**
  43120. * Prepares the list of attributes required for morph targets according to the effect defines.
  43121. * @param attribs The current list of supported attribs
  43122. * @param mesh The mesh to prepare the morph targets attributes for
  43123. * @param defines The current Defines of the effect
  43124. */
  43125. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  43126. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  43127. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  43128. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  43129. var manager = mesh.morphTargetManager;
  43130. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  43131. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  43132. for (var index = 0; index < influencers; index++) {
  43133. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  43134. if (normal) {
  43135. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  43136. }
  43137. if (tangent) {
  43138. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  43139. }
  43140. if (attribs.length > maxAttributesCount) {
  43141. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  43142. }
  43143. }
  43144. }
  43145. };
  43146. /**
  43147. * Prepares the list of attributes required for bones according to the effect defines.
  43148. * @param attribs The current list of supported attribs
  43149. * @param mesh The mesh to prepare the bones attributes for
  43150. * @param defines The current Defines of the effect
  43151. * @param fallbacks The current efffect fallback strategy
  43152. */
  43153. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  43154. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  43155. fallbacks.addCPUSkinningFallback(0, mesh);
  43156. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43157. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43158. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  43159. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43160. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43161. }
  43162. }
  43163. };
  43164. /**
  43165. * Prepares the list of attributes required for instances according to the effect defines.
  43166. * @param attribs The current list of supported attribs
  43167. * @param defines The current Defines of the effect
  43168. */
  43169. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  43170. if (defines["INSTANCES"]) {
  43171. attribs.push("world0");
  43172. attribs.push("world1");
  43173. attribs.push("world2");
  43174. attribs.push("world3");
  43175. }
  43176. };
  43177. /**
  43178. * Binds the light shadow information to the effect for the given mesh.
  43179. * @param light The light containing the generator
  43180. * @param scene The scene the lights belongs to
  43181. * @param mesh The mesh we are binding the information to render
  43182. * @param lightIndex The light index in the effect used to render the mesh
  43183. * @param effect The effect we are binding the data to
  43184. */
  43185. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  43186. if (light.shadowEnabled && mesh.receiveShadows) {
  43187. var shadowGenerator = light.getShadowGenerator();
  43188. if (shadowGenerator) {
  43189. shadowGenerator.bindShadowLight(lightIndex, effect);
  43190. }
  43191. }
  43192. };
  43193. /**
  43194. * Binds the light information to the effect.
  43195. * @param light The light containing the generator
  43196. * @param effect The effect we are binding the data to
  43197. * @param lightIndex The light index in the effect used to render
  43198. */
  43199. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  43200. light.transferToEffect(effect, lightIndex + "");
  43201. };
  43202. /**
  43203. * Binds the lights information from the scene to the effect for the given mesh.
  43204. * @param scene The scene the lights belongs to
  43205. * @param mesh The mesh we are binding the information to render
  43206. * @param effect The effect we are binding the data to
  43207. * @param defines The generated defines for the effect
  43208. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  43209. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  43210. */
  43211. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  43212. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  43213. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  43214. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  43215. for (var i = 0; i < len; i++) {
  43216. var light = mesh._lightSources[i];
  43217. var iAsString = i.toString();
  43218. var scaledIntensity = light.getScaledIntensity();
  43219. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  43220. MaterialHelper.BindLightProperties(light, effect, i);
  43221. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  43222. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  43223. if (defines["SPECULARTERM"]) {
  43224. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  43225. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  43226. }
  43227. // Shadows
  43228. if (scene.shadowsEnabled) {
  43229. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  43230. }
  43231. light._uniformBuffer.update();
  43232. }
  43233. };
  43234. /**
  43235. * Binds the fog information from the scene to the effect for the given mesh.
  43236. * @param scene The scene the lights belongs to
  43237. * @param mesh The mesh we are binding the information to render
  43238. * @param effect The effect we are binding the data to
  43239. * @param linearSpace Defines if the fog effect is applied in linear space
  43240. */
  43241. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  43242. if (linearSpace === void 0) { linearSpace = false; }
  43243. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  43244. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  43245. // Convert fog color to linear space if used in a linear space computed shader.
  43246. if (linearSpace) {
  43247. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  43248. effect.setColor3("vFogColor", this._tempFogColor);
  43249. }
  43250. else {
  43251. effect.setColor3("vFogColor", scene.fogColor);
  43252. }
  43253. }
  43254. };
  43255. /**
  43256. * Binds the bones information from the mesh to the effect.
  43257. * @param mesh The mesh we are binding the information to render
  43258. * @param effect The effect we are binding the data to
  43259. */
  43260. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  43261. if (!effect || !mesh) {
  43262. return;
  43263. }
  43264. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  43265. mesh.computeBonesUsingShaders = false;
  43266. }
  43267. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  43268. var skeleton = mesh.skeleton;
  43269. if (skeleton.isUsingTextureForMatrices && effect.getUniformIndex("boneTextureWidth") > -1) {
  43270. var boneTexture = skeleton.getTransformMatrixTexture();
  43271. effect.setTexture("boneSampler", boneTexture);
  43272. effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
  43273. }
  43274. else {
  43275. var matrices = skeleton.getTransformMatrices(mesh);
  43276. if (matrices) {
  43277. effect.setMatrices("mBones", matrices);
  43278. }
  43279. }
  43280. }
  43281. };
  43282. /**
  43283. * Binds the morph targets information from the mesh to the effect.
  43284. * @param abstractMesh The mesh we are binding the information to render
  43285. * @param effect The effect we are binding the data to
  43286. */
  43287. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  43288. var manager = abstractMesh.morphTargetManager;
  43289. if (!abstractMesh || !manager) {
  43290. return;
  43291. }
  43292. effect.setFloatArray("morphTargetInfluences", manager.influences);
  43293. };
  43294. /**
  43295. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  43296. * @param defines The generated defines used in the effect
  43297. * @param effect The effect we are binding the data to
  43298. * @param scene The scene we are willing to render with logarithmic scale for
  43299. */
  43300. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  43301. if (defines["LOGARITHMICDEPTH"]) {
  43302. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  43303. }
  43304. };
  43305. /**
  43306. * Binds the clip plane information from the scene to the effect.
  43307. * @param scene The scene the clip plane information are extracted from
  43308. * @param effect The effect we are binding the data to
  43309. */
  43310. MaterialHelper.BindClipPlane = function (effect, scene) {
  43311. if (scene.clipPlane) {
  43312. var clipPlane = scene.clipPlane;
  43313. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43314. }
  43315. if (scene.clipPlane2) {
  43316. var clipPlane = scene.clipPlane2;
  43317. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43318. }
  43319. if (scene.clipPlane3) {
  43320. var clipPlane = scene.clipPlane3;
  43321. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43322. }
  43323. if (scene.clipPlane4) {
  43324. var clipPlane = scene.clipPlane4;
  43325. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43326. }
  43327. };
  43328. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  43329. return MaterialHelper;
  43330. }());
  43331. BABYLON.MaterialHelper = MaterialHelper;
  43332. })(BABYLON || (BABYLON = {}));
  43333. //# sourceMappingURL=materialHelper.js.map
  43334. var BABYLON;
  43335. (function (BABYLON) {
  43336. /**
  43337. * Base class of materials working in push mode in babylon JS
  43338. * @hidden
  43339. */
  43340. var PushMaterial = /** @class */ (function (_super) {
  43341. __extends(PushMaterial, _super);
  43342. function PushMaterial(name, scene) {
  43343. var _this = _super.call(this, name, scene) || this;
  43344. _this._normalMatrix = new BABYLON.Matrix();
  43345. /**
  43346. * Gets or sets a boolean indicating that the material is allowed to do shader hot swapping.
  43347. * This means that the material can keep using a previous shader while a new one is being compiled.
  43348. * This is mostly used when shader parallel compilation is supported (true by default)
  43349. */
  43350. _this.allowShaderHotSwapping = true;
  43351. _this._storeEffectOnSubMeshes = true;
  43352. return _this;
  43353. }
  43354. PushMaterial.prototype.getEffect = function () {
  43355. return this._activeEffect;
  43356. };
  43357. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  43358. if (!mesh) {
  43359. return false;
  43360. }
  43361. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  43362. return true;
  43363. }
  43364. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  43365. };
  43366. /**
  43367. * Binds the given world matrix to the active effect
  43368. *
  43369. * @param world the matrix to bind
  43370. */
  43371. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43372. this._activeEffect.setMatrix("world", world);
  43373. };
  43374. /**
  43375. * Binds the given normal matrix to the active effect
  43376. *
  43377. * @param normalMatrix the matrix to bind
  43378. */
  43379. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  43380. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  43381. };
  43382. PushMaterial.prototype.bind = function (world, mesh) {
  43383. if (!mesh) {
  43384. return;
  43385. }
  43386. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  43387. };
  43388. PushMaterial.prototype._afterBind = function (mesh, effect) {
  43389. if (effect === void 0) { effect = null; }
  43390. _super.prototype._afterBind.call(this, mesh);
  43391. this.getScene()._cachedEffect = effect;
  43392. };
  43393. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  43394. if (visibility === void 0) { visibility = 1; }
  43395. return scene.isCachedMaterialInvalid(this, effect, visibility);
  43396. };
  43397. return PushMaterial;
  43398. }(BABYLON.Material));
  43399. BABYLON.PushMaterial = PushMaterial;
  43400. })(BABYLON || (BABYLON = {}));
  43401. //# sourceMappingURL=pushMaterial.js.map
  43402. var BABYLON;
  43403. (function (BABYLON) {
  43404. /** @hidden */
  43405. var StandardMaterialDefines = /** @class */ (function (_super) {
  43406. __extends(StandardMaterialDefines, _super);
  43407. function StandardMaterialDefines() {
  43408. var _this = _super.call(this) || this;
  43409. _this.MAINUV1 = false;
  43410. _this.MAINUV2 = false;
  43411. _this.DIFFUSE = false;
  43412. _this.DIFFUSEDIRECTUV = 0;
  43413. _this.AMBIENT = false;
  43414. _this.AMBIENTDIRECTUV = 0;
  43415. _this.OPACITY = false;
  43416. _this.OPACITYDIRECTUV = 0;
  43417. _this.OPACITYRGB = false;
  43418. _this.REFLECTION = false;
  43419. _this.EMISSIVE = false;
  43420. _this.EMISSIVEDIRECTUV = 0;
  43421. _this.SPECULAR = false;
  43422. _this.SPECULARDIRECTUV = 0;
  43423. _this.BUMP = false;
  43424. _this.BUMPDIRECTUV = 0;
  43425. _this.PARALLAX = false;
  43426. _this.PARALLAXOCCLUSION = false;
  43427. _this.SPECULAROVERALPHA = false;
  43428. _this.CLIPPLANE = false;
  43429. _this.CLIPPLANE2 = false;
  43430. _this.CLIPPLANE3 = false;
  43431. _this.CLIPPLANE4 = false;
  43432. _this.ALPHATEST = false;
  43433. _this.DEPTHPREPASS = false;
  43434. _this.ALPHAFROMDIFFUSE = false;
  43435. _this.POINTSIZE = false;
  43436. _this.FOG = false;
  43437. _this.SPECULARTERM = false;
  43438. _this.DIFFUSEFRESNEL = false;
  43439. _this.OPACITYFRESNEL = false;
  43440. _this.REFLECTIONFRESNEL = false;
  43441. _this.REFRACTIONFRESNEL = false;
  43442. _this.EMISSIVEFRESNEL = false;
  43443. _this.FRESNEL = false;
  43444. _this.NORMAL = false;
  43445. _this.UV1 = false;
  43446. _this.UV2 = false;
  43447. _this.VERTEXCOLOR = false;
  43448. _this.VERTEXALPHA = false;
  43449. _this.NUM_BONE_INFLUENCERS = 0;
  43450. _this.BonesPerMesh = 0;
  43451. _this.BONETEXTURE = false;
  43452. _this.INSTANCES = false;
  43453. _this.GLOSSINESS = false;
  43454. _this.ROUGHNESS = false;
  43455. _this.EMISSIVEASILLUMINATION = false;
  43456. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43457. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43458. _this.LIGHTMAP = false;
  43459. _this.LIGHTMAPDIRECTUV = 0;
  43460. _this.OBJECTSPACE_NORMALMAP = false;
  43461. _this.USELIGHTMAPASSHADOWMAP = false;
  43462. _this.REFLECTIONMAP_3D = false;
  43463. _this.REFLECTIONMAP_SPHERICAL = false;
  43464. _this.REFLECTIONMAP_PLANAR = false;
  43465. _this.REFLECTIONMAP_CUBIC = false;
  43466. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43467. _this.REFLECTIONMAP_PROJECTION = false;
  43468. _this.REFLECTIONMAP_SKYBOX = false;
  43469. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43470. _this.REFLECTIONMAP_EXPLICIT = false;
  43471. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43472. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43473. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43474. _this.INVERTCUBICMAP = false;
  43475. _this.LOGARITHMICDEPTH = false;
  43476. _this.REFRACTION = false;
  43477. _this.REFRACTIONMAP_3D = false;
  43478. _this.REFLECTIONOVERALPHA = false;
  43479. _this.TWOSIDEDLIGHTING = false;
  43480. _this.SHADOWFLOAT = false;
  43481. _this.MORPHTARGETS = false;
  43482. _this.MORPHTARGETS_NORMAL = false;
  43483. _this.MORPHTARGETS_TANGENT = false;
  43484. _this.NUM_MORPH_INFLUENCERS = 0;
  43485. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  43486. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  43487. _this.IMAGEPROCESSING = false;
  43488. _this.VIGNETTE = false;
  43489. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43490. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43491. _this.TONEMAPPING = false;
  43492. _this.TONEMAPPING_ACES = false;
  43493. _this.CONTRAST = false;
  43494. _this.COLORCURVES = false;
  43495. _this.COLORGRADING = false;
  43496. _this.COLORGRADING3D = false;
  43497. _this.SAMPLER3DGREENDEPTH = false;
  43498. _this.SAMPLER3DBGRMAP = false;
  43499. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43500. /**
  43501. * If the reflection texture on this material is in linear color space
  43502. * @hidden
  43503. */
  43504. _this.IS_REFLECTION_LINEAR = false;
  43505. /**
  43506. * If the refraction texture on this material is in linear color space
  43507. * @hidden
  43508. */
  43509. _this.IS_REFRACTION_LINEAR = false;
  43510. _this.EXPOSURE = false;
  43511. _this.rebuild();
  43512. return _this;
  43513. }
  43514. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43515. var modes = [
  43516. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43517. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43518. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43519. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43520. ];
  43521. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43522. var mode = modes_1[_i];
  43523. this[mode] = (mode === modeToEnable);
  43524. }
  43525. };
  43526. return StandardMaterialDefines;
  43527. }(BABYLON.MaterialDefines));
  43528. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43529. /**
  43530. * This is the default material used in Babylon. It is the best trade off between quality
  43531. * and performances.
  43532. * @see http://doc.babylonjs.com/babylon101/materials
  43533. */
  43534. var StandardMaterial = /** @class */ (function (_super) {
  43535. __extends(StandardMaterial, _super);
  43536. /**
  43537. * Instantiates a new standard material.
  43538. * This is the default material used in Babylon. It is the best trade off between quality
  43539. * and performances.
  43540. * @see http://doc.babylonjs.com/babylon101/materials
  43541. * @param name Define the name of the material in the scene
  43542. * @param scene Define the scene the material belong to
  43543. */
  43544. function StandardMaterial(name, scene) {
  43545. var _this = _super.call(this, name, scene) || this;
  43546. /**
  43547. * The color of the material lit by the environmental background lighting.
  43548. * @see http://doc.babylonjs.com/babylon101/materials#ambient-color-example
  43549. */
  43550. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43551. /**
  43552. * The basic color of the material as viewed under a light.
  43553. */
  43554. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43555. /**
  43556. * Define how the color and intensity of the highlight given by the light in the material.
  43557. */
  43558. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43559. /**
  43560. * Define the color of the material as if self lit.
  43561. * This will be mixed in the final result even in the absence of light.
  43562. */
  43563. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43564. /**
  43565. * Defines how sharp are the highlights in the material.
  43566. * The bigger the value the sharper giving a more glossy feeling to the result.
  43567. * Reversely, the smaller the value the blurrier giving a more rough feeling to the result.
  43568. */
  43569. _this.specularPower = 64;
  43570. _this._useAlphaFromDiffuseTexture = false;
  43571. _this._useEmissiveAsIllumination = false;
  43572. _this._linkEmissiveWithDiffuse = false;
  43573. _this._useSpecularOverAlpha = false;
  43574. _this._useReflectionOverAlpha = false;
  43575. _this._disableLighting = false;
  43576. _this._useObjectSpaceNormalMap = false;
  43577. _this._useParallax = false;
  43578. _this._useParallaxOcclusion = false;
  43579. /**
  43580. * 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.
  43581. */
  43582. _this.parallaxScaleBias = 0.05;
  43583. _this._roughness = 0;
  43584. /**
  43585. * In case of refraction, define the value of the indice of refraction.
  43586. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43587. */
  43588. _this.indexOfRefraction = 0.98;
  43589. /**
  43590. * Invert the refraction texture alongside the y axis.
  43591. * It can be usefull with procedural textures or probe for instance.
  43592. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43593. */
  43594. _this.invertRefractionY = true;
  43595. /**
  43596. * Defines the alpha limits in alpha test mode.
  43597. */
  43598. _this.alphaCutOff = 0.4;
  43599. _this._useLightmapAsShadowmap = false;
  43600. _this._useReflectionFresnelFromSpecular = false;
  43601. _this._useGlossinessFromSpecularMapAlpha = false;
  43602. _this._maxSimultaneousLights = 4;
  43603. _this._invertNormalMapX = false;
  43604. _this._invertNormalMapY = false;
  43605. _this._twoSidedLighting = false;
  43606. _this._renderTargets = new BABYLON.SmartArray(16);
  43607. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43608. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43609. // Setup the default processing configuration to the scene.
  43610. _this._attachImageProcessingConfiguration(null);
  43611. _this.getRenderTargetTextures = function () {
  43612. _this._renderTargets.reset();
  43613. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43614. _this._renderTargets.push(_this._reflectionTexture);
  43615. }
  43616. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43617. _this._renderTargets.push(_this._refractionTexture);
  43618. }
  43619. return _this._renderTargets;
  43620. };
  43621. return _this;
  43622. }
  43623. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43624. /**
  43625. * Gets the image processing configuration used either in this material.
  43626. */
  43627. get: function () {
  43628. return this._imageProcessingConfiguration;
  43629. },
  43630. /**
  43631. * Sets the Default image processing configuration used either in the this material.
  43632. *
  43633. * If sets to null, the scene one is in use.
  43634. */
  43635. set: function (value) {
  43636. this._attachImageProcessingConfiguration(value);
  43637. // Ensure the effect will be rebuilt.
  43638. this._markAllSubMeshesAsTexturesDirty();
  43639. },
  43640. enumerable: true,
  43641. configurable: true
  43642. });
  43643. /**
  43644. * Attaches a new image processing configuration to the Standard Material.
  43645. * @param configuration
  43646. */
  43647. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43648. var _this = this;
  43649. if (configuration === this._imageProcessingConfiguration) {
  43650. return;
  43651. }
  43652. // Detaches observer.
  43653. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43654. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43655. }
  43656. // Pick the scene configuration if needed.
  43657. if (!configuration) {
  43658. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43659. }
  43660. else {
  43661. this._imageProcessingConfiguration = configuration;
  43662. }
  43663. // Attaches observer.
  43664. if (this._imageProcessingConfiguration) {
  43665. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43666. _this._markAllSubMeshesAsImageProcessingDirty();
  43667. });
  43668. }
  43669. };
  43670. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43671. /**
  43672. * Gets wether the color curves effect is enabled.
  43673. */
  43674. get: function () {
  43675. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43676. },
  43677. /**
  43678. * Sets wether the color curves effect is enabled.
  43679. */
  43680. set: function (value) {
  43681. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43682. },
  43683. enumerable: true,
  43684. configurable: true
  43685. });
  43686. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43687. /**
  43688. * Gets wether the color grading effect is enabled.
  43689. */
  43690. get: function () {
  43691. return this.imageProcessingConfiguration.colorGradingEnabled;
  43692. },
  43693. /**
  43694. * Gets wether the color grading effect is enabled.
  43695. */
  43696. set: function (value) {
  43697. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43698. },
  43699. enumerable: true,
  43700. configurable: true
  43701. });
  43702. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43703. /**
  43704. * Gets wether tonemapping is enabled or not.
  43705. */
  43706. get: function () {
  43707. return this._imageProcessingConfiguration.toneMappingEnabled;
  43708. },
  43709. /**
  43710. * Sets wether tonemapping is enabled or not
  43711. */
  43712. set: function (value) {
  43713. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43714. },
  43715. enumerable: true,
  43716. configurable: true
  43717. });
  43718. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43719. /**
  43720. * The camera exposure used on this material.
  43721. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43722. * This corresponds to a photographic exposure.
  43723. */
  43724. get: function () {
  43725. return this._imageProcessingConfiguration.exposure;
  43726. },
  43727. /**
  43728. * The camera exposure used on this material.
  43729. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43730. * This corresponds to a photographic exposure.
  43731. */
  43732. set: function (value) {
  43733. this._imageProcessingConfiguration.exposure = value;
  43734. },
  43735. enumerable: true,
  43736. configurable: true
  43737. });
  43738. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43739. /**
  43740. * Gets The camera contrast used on this material.
  43741. */
  43742. get: function () {
  43743. return this._imageProcessingConfiguration.contrast;
  43744. },
  43745. /**
  43746. * Sets The camera contrast used on this material.
  43747. */
  43748. set: function (value) {
  43749. this._imageProcessingConfiguration.contrast = value;
  43750. },
  43751. enumerable: true,
  43752. configurable: true
  43753. });
  43754. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43755. /**
  43756. * Gets the Color Grading 2D Lookup Texture.
  43757. */
  43758. get: function () {
  43759. return this._imageProcessingConfiguration.colorGradingTexture;
  43760. },
  43761. /**
  43762. * Sets the Color Grading 2D Lookup Texture.
  43763. */
  43764. set: function (value) {
  43765. this._imageProcessingConfiguration.colorGradingTexture = value;
  43766. },
  43767. enumerable: true,
  43768. configurable: true
  43769. });
  43770. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43771. /**
  43772. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43773. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43774. * 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;
  43775. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43776. */
  43777. get: function () {
  43778. return this._imageProcessingConfiguration.colorCurves;
  43779. },
  43780. /**
  43781. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43782. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43783. * 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;
  43784. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43785. */
  43786. set: function (value) {
  43787. this._imageProcessingConfiguration.colorCurves = value;
  43788. },
  43789. enumerable: true,
  43790. configurable: true
  43791. });
  43792. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  43793. /**
  43794. * Gets a boolean indicating that current material needs to register RTT
  43795. */
  43796. get: function () {
  43797. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43798. return true;
  43799. }
  43800. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43801. return true;
  43802. }
  43803. return false;
  43804. },
  43805. enumerable: true,
  43806. configurable: true
  43807. });
  43808. /**
  43809. * Gets the current class name of the material e.g. "StandardMaterial"
  43810. * Mainly use in serialization.
  43811. * @returns the class name
  43812. */
  43813. StandardMaterial.prototype.getClassName = function () {
  43814. return "StandardMaterial";
  43815. };
  43816. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43817. /**
  43818. * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes)
  43819. * You can try switching to logarithmic depth.
  43820. * @see http://doc.babylonjs.com/how_to/using_logarithmic_depth_buffer
  43821. */
  43822. get: function () {
  43823. return this._useLogarithmicDepth;
  43824. },
  43825. set: function (value) {
  43826. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43827. this._markAllSubMeshesAsMiscDirty();
  43828. },
  43829. enumerable: true,
  43830. configurable: true
  43831. });
  43832. /**
  43833. * Specifies if the material will require alpha blending
  43834. * @returns a boolean specifying if alpha blending is needed
  43835. */
  43836. StandardMaterial.prototype.needAlphaBlending = function () {
  43837. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43838. };
  43839. /**
  43840. * Specifies if this material should be rendered in alpha test mode
  43841. * @returns a boolean specifying if an alpha test is needed.
  43842. */
  43843. StandardMaterial.prototype.needAlphaTesting = function () {
  43844. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43845. };
  43846. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43847. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43848. };
  43849. /**
  43850. * Get the texture used for alpha test purpose.
  43851. * @returns the diffuse texture in case of the standard material.
  43852. */
  43853. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43854. return this._diffuseTexture;
  43855. };
  43856. /**
  43857. * Get if the submesh is ready to be used and all its information available.
  43858. * Child classes can use it to update shaders
  43859. * @param mesh defines the mesh to check
  43860. * @param subMesh defines which submesh to check
  43861. * @param useInstances specifies that instances should be used
  43862. * @returns a boolean indicating that the submesh is ready or not
  43863. */
  43864. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43865. if (useInstances === void 0) { useInstances = false; }
  43866. if (subMesh.effect && this.isFrozen) {
  43867. if (this._wasPreviouslyReady) {
  43868. return true;
  43869. }
  43870. }
  43871. if (!subMesh._materialDefines) {
  43872. subMesh._materialDefines = new StandardMaterialDefines();
  43873. }
  43874. var scene = this.getScene();
  43875. var defines = subMesh._materialDefines;
  43876. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43877. if (defines._renderId === scene.getRenderId()) {
  43878. return true;
  43879. }
  43880. }
  43881. var engine = scene.getEngine();
  43882. // Lights
  43883. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43884. // Textures
  43885. if (defines._areTexturesDirty) {
  43886. defines._needUVs = false;
  43887. defines.MAINUV1 = false;
  43888. defines.MAINUV2 = false;
  43889. if (scene.texturesEnabled) {
  43890. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43891. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43892. return false;
  43893. }
  43894. else {
  43895. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43896. }
  43897. }
  43898. else {
  43899. defines.DIFFUSE = false;
  43900. }
  43901. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43902. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43903. return false;
  43904. }
  43905. else {
  43906. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43907. }
  43908. }
  43909. else {
  43910. defines.AMBIENT = false;
  43911. }
  43912. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43913. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43914. return false;
  43915. }
  43916. else {
  43917. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43918. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43919. }
  43920. }
  43921. else {
  43922. defines.OPACITY = false;
  43923. }
  43924. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43925. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43926. return false;
  43927. }
  43928. else {
  43929. defines._needNormals = true;
  43930. defines.REFLECTION = true;
  43931. defines.ROUGHNESS = (this._roughness > 0);
  43932. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43933. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43934. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43935. switch (this._reflectionTexture.coordinatesMode) {
  43936. case BABYLON.Texture.EXPLICIT_MODE:
  43937. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43938. break;
  43939. case BABYLON.Texture.PLANAR_MODE:
  43940. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43941. break;
  43942. case BABYLON.Texture.PROJECTION_MODE:
  43943. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43944. break;
  43945. case BABYLON.Texture.SKYBOX_MODE:
  43946. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43947. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  43948. break;
  43949. case BABYLON.Texture.SPHERICAL_MODE:
  43950. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43951. break;
  43952. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43953. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43954. break;
  43955. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43956. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43957. break;
  43958. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43959. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43960. break;
  43961. case BABYLON.Texture.CUBIC_MODE:
  43962. case BABYLON.Texture.INVCUBIC_MODE:
  43963. default:
  43964. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43965. break;
  43966. }
  43967. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43968. }
  43969. }
  43970. else {
  43971. defines.REFLECTION = false;
  43972. }
  43973. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43974. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43975. return false;
  43976. }
  43977. else {
  43978. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43979. }
  43980. }
  43981. else {
  43982. defines.EMISSIVE = false;
  43983. }
  43984. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43985. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43986. return false;
  43987. }
  43988. else {
  43989. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43990. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43991. }
  43992. }
  43993. else {
  43994. defines.LIGHTMAP = false;
  43995. }
  43996. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43997. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43998. return false;
  43999. }
  44000. else {
  44001. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  44002. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  44003. }
  44004. }
  44005. else {
  44006. defines.SPECULAR = false;
  44007. }
  44008. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  44009. // Bump texure can not be not blocking.
  44010. if (!this._bumpTexture.isReady()) {
  44011. return false;
  44012. }
  44013. else {
  44014. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44015. defines.PARALLAX = this._useParallax;
  44016. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  44017. }
  44018. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44019. }
  44020. else {
  44021. defines.BUMP = false;
  44022. }
  44023. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44024. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  44025. return false;
  44026. }
  44027. else {
  44028. defines._needUVs = true;
  44029. defines.REFRACTION = true;
  44030. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  44031. }
  44032. }
  44033. else {
  44034. defines.REFRACTION = false;
  44035. }
  44036. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  44037. }
  44038. else {
  44039. defines.DIFFUSE = false;
  44040. defines.AMBIENT = false;
  44041. defines.OPACITY = false;
  44042. defines.REFLECTION = false;
  44043. defines.EMISSIVE = false;
  44044. defines.LIGHTMAP = false;
  44045. defines.BUMP = false;
  44046. defines.REFRACTION = false;
  44047. }
  44048. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  44049. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  44050. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  44051. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44052. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44053. }
  44054. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44055. if (!this._imageProcessingConfiguration.isReady()) {
  44056. return false;
  44057. }
  44058. this._imageProcessingConfiguration.prepareDefines(defines);
  44059. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  44060. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  44061. }
  44062. if (defines._areFresnelDirty) {
  44063. if (StandardMaterial.FresnelEnabled) {
  44064. // Fresnel
  44065. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  44066. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  44067. this._reflectionFresnelParameters) {
  44068. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  44069. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  44070. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  44071. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  44072. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  44073. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  44074. defines._needNormals = true;
  44075. defines.FRESNEL = true;
  44076. }
  44077. }
  44078. else {
  44079. defines.FRESNEL = false;
  44080. }
  44081. }
  44082. // Misc.
  44083. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  44084. // Attribs
  44085. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  44086. // Values that need to be evaluated on every frame
  44087. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  44088. // Get correct effect
  44089. if (defines.isDirty) {
  44090. defines.markAsProcessed();
  44091. // Fallbacks
  44092. var fallbacks = new BABYLON.EffectFallbacks();
  44093. if (defines.REFLECTION) {
  44094. fallbacks.addFallback(0, "REFLECTION");
  44095. }
  44096. if (defines.SPECULAR) {
  44097. fallbacks.addFallback(0, "SPECULAR");
  44098. }
  44099. if (defines.BUMP) {
  44100. fallbacks.addFallback(0, "BUMP");
  44101. }
  44102. if (defines.PARALLAX) {
  44103. fallbacks.addFallback(1, "PARALLAX");
  44104. }
  44105. if (defines.PARALLAXOCCLUSION) {
  44106. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  44107. }
  44108. if (defines.SPECULAROVERALPHA) {
  44109. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  44110. }
  44111. if (defines.FOG) {
  44112. fallbacks.addFallback(1, "FOG");
  44113. }
  44114. if (defines.POINTSIZE) {
  44115. fallbacks.addFallback(0, "POINTSIZE");
  44116. }
  44117. if (defines.LOGARITHMICDEPTH) {
  44118. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  44119. }
  44120. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  44121. if (defines.SPECULARTERM) {
  44122. fallbacks.addFallback(0, "SPECULARTERM");
  44123. }
  44124. if (defines.DIFFUSEFRESNEL) {
  44125. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  44126. }
  44127. if (defines.OPACITYFRESNEL) {
  44128. fallbacks.addFallback(2, "OPACITYFRESNEL");
  44129. }
  44130. if (defines.REFLECTIONFRESNEL) {
  44131. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  44132. }
  44133. if (defines.EMISSIVEFRESNEL) {
  44134. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  44135. }
  44136. if (defines.FRESNEL) {
  44137. fallbacks.addFallback(4, "FRESNEL");
  44138. }
  44139. //Attributes
  44140. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44141. if (defines.NORMAL) {
  44142. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44143. }
  44144. if (defines.UV1) {
  44145. attribs.push(BABYLON.VertexBuffer.UVKind);
  44146. }
  44147. if (defines.UV2) {
  44148. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44149. }
  44150. if (defines.VERTEXCOLOR) {
  44151. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44152. }
  44153. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44154. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44155. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44156. var shaderName = "default";
  44157. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  44158. "vFogInfos", "vFogColor", "pointSize",
  44159. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44160. "mBones",
  44161. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  44162. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  44163. "vReflectionPosition", "vReflectionSize",
  44164. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff", "boneTextureWidth"
  44165. ];
  44166. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler",
  44167. "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  44168. "refractionCubeSampler", "refraction2DSampler", "boneSampler"];
  44169. var uniformBuffers = ["Material", "Scene"];
  44170. if (BABYLON.ImageProcessingConfiguration) {
  44171. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44172. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44173. }
  44174. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44175. uniformsNames: uniforms,
  44176. uniformBuffersNames: uniformBuffers,
  44177. samplers: samplers,
  44178. defines: defines,
  44179. maxSimultaneousLights: this._maxSimultaneousLights
  44180. });
  44181. if (this.customShaderNameResolve) {
  44182. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  44183. }
  44184. var join = defines.toString();
  44185. var previousEffect = subMesh.effect;
  44186. var effect = scene.getEngine().createEffect(shaderName, {
  44187. attributes: attribs,
  44188. uniformsNames: uniforms,
  44189. uniformBuffersNames: uniformBuffers,
  44190. samplers: samplers,
  44191. defines: join,
  44192. fallbacks: fallbacks,
  44193. onCompiled: this.onCompiled,
  44194. onError: this.onError,
  44195. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44196. }, engine);
  44197. if (effect) {
  44198. // Use previous effect while new one is compiling
  44199. if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
  44200. effect = previousEffect;
  44201. defines.markAsUnprocessed();
  44202. }
  44203. else {
  44204. scene.resetCachedMaterial();
  44205. subMesh.setEffect(effect, defines);
  44206. this.buildUniformLayout();
  44207. }
  44208. }
  44209. }
  44210. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44211. return false;
  44212. }
  44213. defines._renderId = scene.getRenderId();
  44214. this._wasPreviouslyReady = true;
  44215. return true;
  44216. };
  44217. /**
  44218. * Builds the material UBO layouts.
  44219. * Used internally during the effect preparation.
  44220. */
  44221. StandardMaterial.prototype.buildUniformLayout = function () {
  44222. // Order is important !
  44223. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  44224. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  44225. this._uniformBuffer.addUniform("opacityParts", 4);
  44226. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  44227. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  44228. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  44229. this._uniformBuffer.addUniform("refractionRightColor", 4);
  44230. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  44231. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  44232. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  44233. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  44234. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44235. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44236. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44237. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44238. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44239. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44240. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  44241. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44242. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  44243. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44244. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44245. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44246. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44247. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44248. this._uniformBuffer.addUniform("specularMatrix", 16);
  44249. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44250. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44251. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44252. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44253. this._uniformBuffer.addUniform("vSpecularColor", 4);
  44254. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44255. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  44256. this._uniformBuffer.addUniform("pointSize", 1);
  44257. this._uniformBuffer.create();
  44258. };
  44259. /**
  44260. * Unbinds the material from the mesh
  44261. */
  44262. StandardMaterial.prototype.unbind = function () {
  44263. if (this._activeEffect) {
  44264. var needFlag = false;
  44265. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44266. this._activeEffect.setTexture("reflection2DSampler", null);
  44267. needFlag = true;
  44268. }
  44269. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44270. this._activeEffect.setTexture("refraction2DSampler", null);
  44271. needFlag = true;
  44272. }
  44273. if (needFlag) {
  44274. this._markAllSubMeshesAsTexturesDirty();
  44275. }
  44276. }
  44277. _super.prototype.unbind.call(this);
  44278. };
  44279. /**
  44280. * Binds the submesh to this material by preparing the effect and shader to draw
  44281. * @param world defines the world transformation matrix
  44282. * @param mesh defines the mesh containing the submesh
  44283. * @param subMesh defines the submesh to bind the material to
  44284. */
  44285. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44286. var scene = this.getScene();
  44287. var defines = subMesh._materialDefines;
  44288. if (!defines) {
  44289. return;
  44290. }
  44291. var effect = subMesh.effect;
  44292. if (!effect) {
  44293. return;
  44294. }
  44295. this._activeEffect = effect;
  44296. // Matrices
  44297. this.bindOnlyWorldMatrix(world);
  44298. // Normal Matrix
  44299. if (defines.OBJECTSPACE_NORMALMAP) {
  44300. world.toNormalMatrix(this._normalMatrix);
  44301. this.bindOnlyNormalMatrix(this._normalMatrix);
  44302. }
  44303. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44304. // Bones
  44305. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  44306. if (mustRebind) {
  44307. this._uniformBuffer.bindToEffect(effect, "Material");
  44308. this.bindViewProjection(effect);
  44309. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44310. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  44311. // Fresnel
  44312. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  44313. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  44314. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  44315. }
  44316. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44317. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  44318. }
  44319. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  44320. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  44321. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  44322. }
  44323. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  44324. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  44325. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  44326. }
  44327. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44328. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  44329. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  44330. }
  44331. }
  44332. // Textures
  44333. if (scene.texturesEnabled) {
  44334. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44335. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  44336. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  44337. if (this._diffuseTexture.hasAlpha) {
  44338. effect.setFloat("alphaCutOff", this.alphaCutOff);
  44339. }
  44340. }
  44341. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44342. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  44343. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44344. }
  44345. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44346. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44347. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44348. }
  44349. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44350. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  44351. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  44352. if (this._reflectionTexture.boundingBoxSize) {
  44353. var cubeTexture = this._reflectionTexture;
  44354. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44355. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44356. }
  44357. }
  44358. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44359. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44360. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44361. }
  44362. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44363. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44364. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44365. }
  44366. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44367. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  44368. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  44369. }
  44370. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44371. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  44372. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44373. if (scene._mirroredCameraPosition) {
  44374. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44375. }
  44376. else {
  44377. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44378. }
  44379. }
  44380. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44381. var depth = 1.0;
  44382. if (!this._refractionTexture.isCube) {
  44383. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  44384. if (this._refractionTexture.depth) {
  44385. depth = this._refractionTexture.depth;
  44386. }
  44387. }
  44388. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  44389. }
  44390. }
  44391. // Point size
  44392. if (this.pointsCloud) {
  44393. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44394. }
  44395. if (defines.SPECULARTERM) {
  44396. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  44397. }
  44398. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  44399. // Diffuse
  44400. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  44401. }
  44402. // Textures
  44403. if (scene.texturesEnabled) {
  44404. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44405. effect.setTexture("diffuseSampler", this._diffuseTexture);
  44406. }
  44407. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44408. effect.setTexture("ambientSampler", this._ambientTexture);
  44409. }
  44410. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44411. effect.setTexture("opacitySampler", this._opacityTexture);
  44412. }
  44413. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44414. if (this._reflectionTexture.isCube) {
  44415. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  44416. }
  44417. else {
  44418. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  44419. }
  44420. }
  44421. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44422. effect.setTexture("emissiveSampler", this._emissiveTexture);
  44423. }
  44424. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44425. effect.setTexture("lightmapSampler", this._lightmapTexture);
  44426. }
  44427. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44428. effect.setTexture("specularSampler", this._specularTexture);
  44429. }
  44430. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44431. effect.setTexture("bumpSampler", this._bumpTexture);
  44432. }
  44433. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44434. var depth = 1.0;
  44435. if (this._refractionTexture.isCube) {
  44436. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  44437. }
  44438. else {
  44439. effect.setTexture("refraction2DSampler", this._refractionTexture);
  44440. }
  44441. }
  44442. }
  44443. // Clip plane
  44444. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  44445. // Colors
  44446. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44447. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  44448. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44449. }
  44450. if (mustRebind || !this.isFrozen) {
  44451. // Lights
  44452. if (scene.lightsEnabled && !this._disableLighting) {
  44453. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  44454. }
  44455. // View
  44456. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  44457. this.bindView(effect);
  44458. }
  44459. // Fog
  44460. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  44461. // Morph targets
  44462. if (defines.NUM_MORPH_INFLUENCERS) {
  44463. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  44464. }
  44465. // Log. depth
  44466. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  44467. // image processing
  44468. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  44469. this._imageProcessingConfiguration.bind(this._activeEffect);
  44470. }
  44471. }
  44472. this._uniformBuffer.update();
  44473. this._afterBind(mesh, this._activeEffect);
  44474. };
  44475. /**
  44476. * Get the list of animatables in the material.
  44477. * @returns the list of animatables object used in the material
  44478. */
  44479. StandardMaterial.prototype.getAnimatables = function () {
  44480. var results = [];
  44481. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  44482. results.push(this._diffuseTexture);
  44483. }
  44484. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44485. results.push(this._ambientTexture);
  44486. }
  44487. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44488. results.push(this._opacityTexture);
  44489. }
  44490. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44491. results.push(this._reflectionTexture);
  44492. }
  44493. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44494. results.push(this._emissiveTexture);
  44495. }
  44496. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  44497. results.push(this._specularTexture);
  44498. }
  44499. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44500. results.push(this._bumpTexture);
  44501. }
  44502. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44503. results.push(this._lightmapTexture);
  44504. }
  44505. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44506. results.push(this._refractionTexture);
  44507. }
  44508. return results;
  44509. };
  44510. /**
  44511. * Gets the active textures from the material
  44512. * @returns an array of textures
  44513. */
  44514. StandardMaterial.prototype.getActiveTextures = function () {
  44515. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44516. if (this._diffuseTexture) {
  44517. activeTextures.push(this._diffuseTexture);
  44518. }
  44519. if (this._ambientTexture) {
  44520. activeTextures.push(this._ambientTexture);
  44521. }
  44522. if (this._opacityTexture) {
  44523. activeTextures.push(this._opacityTexture);
  44524. }
  44525. if (this._reflectionTexture) {
  44526. activeTextures.push(this._reflectionTexture);
  44527. }
  44528. if (this._emissiveTexture) {
  44529. activeTextures.push(this._emissiveTexture);
  44530. }
  44531. if (this._specularTexture) {
  44532. activeTextures.push(this._specularTexture);
  44533. }
  44534. if (this._bumpTexture) {
  44535. activeTextures.push(this._bumpTexture);
  44536. }
  44537. if (this._lightmapTexture) {
  44538. activeTextures.push(this._lightmapTexture);
  44539. }
  44540. if (this._refractionTexture) {
  44541. activeTextures.push(this._refractionTexture);
  44542. }
  44543. return activeTextures;
  44544. };
  44545. /**
  44546. * Specifies if the material uses a texture
  44547. * @param texture defines the texture to check against the material
  44548. * @returns a boolean specifying if the material uses the texture
  44549. */
  44550. StandardMaterial.prototype.hasTexture = function (texture) {
  44551. if (_super.prototype.hasTexture.call(this, texture)) {
  44552. return true;
  44553. }
  44554. if (this._diffuseTexture === texture) {
  44555. return true;
  44556. }
  44557. if (this._ambientTexture === texture) {
  44558. return true;
  44559. }
  44560. if (this._opacityTexture === texture) {
  44561. return true;
  44562. }
  44563. if (this._reflectionTexture === texture) {
  44564. return true;
  44565. }
  44566. if (this._emissiveTexture === texture) {
  44567. return true;
  44568. }
  44569. if (this._specularTexture === texture) {
  44570. return true;
  44571. }
  44572. if (this._bumpTexture === texture) {
  44573. return true;
  44574. }
  44575. if (this._lightmapTexture === texture) {
  44576. return true;
  44577. }
  44578. if (this._refractionTexture === texture) {
  44579. return true;
  44580. }
  44581. return false;
  44582. };
  44583. /**
  44584. * Disposes the material
  44585. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  44586. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  44587. */
  44588. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44589. if (forceDisposeTextures) {
  44590. if (this._diffuseTexture) {
  44591. this._diffuseTexture.dispose();
  44592. }
  44593. if (this._ambientTexture) {
  44594. this._ambientTexture.dispose();
  44595. }
  44596. if (this._opacityTexture) {
  44597. this._opacityTexture.dispose();
  44598. }
  44599. if (this._reflectionTexture) {
  44600. this._reflectionTexture.dispose();
  44601. }
  44602. if (this._emissiveTexture) {
  44603. this._emissiveTexture.dispose();
  44604. }
  44605. if (this._specularTexture) {
  44606. this._specularTexture.dispose();
  44607. }
  44608. if (this._bumpTexture) {
  44609. this._bumpTexture.dispose();
  44610. }
  44611. if (this._lightmapTexture) {
  44612. this._lightmapTexture.dispose();
  44613. }
  44614. if (this._refractionTexture) {
  44615. this._refractionTexture.dispose();
  44616. }
  44617. }
  44618. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44619. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44620. }
  44621. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44622. };
  44623. /**
  44624. * Makes a duplicate of the material, and gives it a new name
  44625. * @param name defines the new name for the duplicated material
  44626. * @returns the cloned material
  44627. */
  44628. StandardMaterial.prototype.clone = function (name) {
  44629. var _this = this;
  44630. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44631. result.name = name;
  44632. result.id = name;
  44633. return result;
  44634. };
  44635. /**
  44636. * Serializes this material in a JSON representation
  44637. * @returns the serialized material object
  44638. */
  44639. StandardMaterial.prototype.serialize = function () {
  44640. return BABYLON.SerializationHelper.Serialize(this);
  44641. };
  44642. /**
  44643. * Creates a standard material from parsed material data
  44644. * @param source defines the JSON represnetation of the material
  44645. * @param scene defines the hosting scene
  44646. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  44647. * @returns a new material
  44648. */
  44649. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44650. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44651. };
  44652. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44653. /**
  44654. * Are diffuse textures enabled in the application.
  44655. */
  44656. get: function () {
  44657. return StandardMaterial._DiffuseTextureEnabled;
  44658. },
  44659. set: function (value) {
  44660. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44661. return;
  44662. }
  44663. StandardMaterial._DiffuseTextureEnabled = value;
  44664. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44665. },
  44666. enumerable: true,
  44667. configurable: true
  44668. });
  44669. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44670. /**
  44671. * Are ambient textures enabled in the application.
  44672. */
  44673. get: function () {
  44674. return StandardMaterial._AmbientTextureEnabled;
  44675. },
  44676. set: function (value) {
  44677. if (StandardMaterial._AmbientTextureEnabled === value) {
  44678. return;
  44679. }
  44680. StandardMaterial._AmbientTextureEnabled = value;
  44681. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44682. },
  44683. enumerable: true,
  44684. configurable: true
  44685. });
  44686. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44687. /**
  44688. * Are opacity textures enabled in the application.
  44689. */
  44690. get: function () {
  44691. return StandardMaterial._OpacityTextureEnabled;
  44692. },
  44693. set: function (value) {
  44694. if (StandardMaterial._OpacityTextureEnabled === value) {
  44695. return;
  44696. }
  44697. StandardMaterial._OpacityTextureEnabled = value;
  44698. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44699. },
  44700. enumerable: true,
  44701. configurable: true
  44702. });
  44703. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44704. /**
  44705. * Are reflection textures enabled in the application.
  44706. */
  44707. get: function () {
  44708. return StandardMaterial._ReflectionTextureEnabled;
  44709. },
  44710. set: function (value) {
  44711. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44712. return;
  44713. }
  44714. StandardMaterial._ReflectionTextureEnabled = value;
  44715. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44716. },
  44717. enumerable: true,
  44718. configurable: true
  44719. });
  44720. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44721. /**
  44722. * Are emissive textures enabled in the application.
  44723. */
  44724. get: function () {
  44725. return StandardMaterial._EmissiveTextureEnabled;
  44726. },
  44727. set: function (value) {
  44728. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44729. return;
  44730. }
  44731. StandardMaterial._EmissiveTextureEnabled = value;
  44732. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44733. },
  44734. enumerable: true,
  44735. configurable: true
  44736. });
  44737. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44738. /**
  44739. * Are specular textures enabled in the application.
  44740. */
  44741. get: function () {
  44742. return StandardMaterial._SpecularTextureEnabled;
  44743. },
  44744. set: function (value) {
  44745. if (StandardMaterial._SpecularTextureEnabled === value) {
  44746. return;
  44747. }
  44748. StandardMaterial._SpecularTextureEnabled = value;
  44749. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44750. },
  44751. enumerable: true,
  44752. configurable: true
  44753. });
  44754. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44755. /**
  44756. * Are bump textures enabled in the application.
  44757. */
  44758. get: function () {
  44759. return StandardMaterial._BumpTextureEnabled;
  44760. },
  44761. set: function (value) {
  44762. if (StandardMaterial._BumpTextureEnabled === value) {
  44763. return;
  44764. }
  44765. StandardMaterial._BumpTextureEnabled = value;
  44766. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44767. },
  44768. enumerable: true,
  44769. configurable: true
  44770. });
  44771. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44772. /**
  44773. * Are lightmap textures enabled in the application.
  44774. */
  44775. get: function () {
  44776. return StandardMaterial._LightmapTextureEnabled;
  44777. },
  44778. set: function (value) {
  44779. if (StandardMaterial._LightmapTextureEnabled === value) {
  44780. return;
  44781. }
  44782. StandardMaterial._LightmapTextureEnabled = value;
  44783. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44784. },
  44785. enumerable: true,
  44786. configurable: true
  44787. });
  44788. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44789. /**
  44790. * Are refraction textures enabled in the application.
  44791. */
  44792. get: function () {
  44793. return StandardMaterial._RefractionTextureEnabled;
  44794. },
  44795. set: function (value) {
  44796. if (StandardMaterial._RefractionTextureEnabled === value) {
  44797. return;
  44798. }
  44799. StandardMaterial._RefractionTextureEnabled = value;
  44800. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44801. },
  44802. enumerable: true,
  44803. configurable: true
  44804. });
  44805. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44806. /**
  44807. * Are color grading textures enabled in the application.
  44808. */
  44809. get: function () {
  44810. return StandardMaterial._ColorGradingTextureEnabled;
  44811. },
  44812. set: function (value) {
  44813. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44814. return;
  44815. }
  44816. StandardMaterial._ColorGradingTextureEnabled = value;
  44817. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44818. },
  44819. enumerable: true,
  44820. configurable: true
  44821. });
  44822. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44823. /**
  44824. * Are fresnels enabled in the application.
  44825. */
  44826. get: function () {
  44827. return StandardMaterial._FresnelEnabled;
  44828. },
  44829. set: function (value) {
  44830. if (StandardMaterial._FresnelEnabled === value) {
  44831. return;
  44832. }
  44833. StandardMaterial._FresnelEnabled = value;
  44834. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44835. },
  44836. enumerable: true,
  44837. configurable: true
  44838. });
  44839. // Flags used to enable or disable a type of texture for all Standard Materials
  44840. StandardMaterial._DiffuseTextureEnabled = true;
  44841. StandardMaterial._AmbientTextureEnabled = true;
  44842. StandardMaterial._OpacityTextureEnabled = true;
  44843. StandardMaterial._ReflectionTextureEnabled = true;
  44844. StandardMaterial._EmissiveTextureEnabled = true;
  44845. StandardMaterial._SpecularTextureEnabled = true;
  44846. StandardMaterial._BumpTextureEnabled = true;
  44847. StandardMaterial._LightmapTextureEnabled = true;
  44848. StandardMaterial._RefractionTextureEnabled = true;
  44849. StandardMaterial._ColorGradingTextureEnabled = true;
  44850. StandardMaterial._FresnelEnabled = true;
  44851. __decorate([
  44852. BABYLON.serializeAsTexture("diffuseTexture")
  44853. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44854. __decorate([
  44855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44856. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44857. __decorate([
  44858. BABYLON.serializeAsTexture("ambientTexture")
  44859. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44860. __decorate([
  44861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44862. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44863. __decorate([
  44864. BABYLON.serializeAsTexture("opacityTexture")
  44865. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44866. __decorate([
  44867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44868. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44869. __decorate([
  44870. BABYLON.serializeAsTexture("reflectionTexture")
  44871. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44872. __decorate([
  44873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44874. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44875. __decorate([
  44876. BABYLON.serializeAsTexture("emissiveTexture")
  44877. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44878. __decorate([
  44879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44880. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44881. __decorate([
  44882. BABYLON.serializeAsTexture("specularTexture")
  44883. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44884. __decorate([
  44885. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44886. ], StandardMaterial.prototype, "specularTexture", void 0);
  44887. __decorate([
  44888. BABYLON.serializeAsTexture("bumpTexture")
  44889. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44890. __decorate([
  44891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44892. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44893. __decorate([
  44894. BABYLON.serializeAsTexture("lightmapTexture")
  44895. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44896. __decorate([
  44897. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44898. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44899. __decorate([
  44900. BABYLON.serializeAsTexture("refractionTexture")
  44901. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44902. __decorate([
  44903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44904. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44905. __decorate([
  44906. BABYLON.serializeAsColor3("ambient")
  44907. ], StandardMaterial.prototype, "ambientColor", void 0);
  44908. __decorate([
  44909. BABYLON.serializeAsColor3("diffuse")
  44910. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44911. __decorate([
  44912. BABYLON.serializeAsColor3("specular")
  44913. ], StandardMaterial.prototype, "specularColor", void 0);
  44914. __decorate([
  44915. BABYLON.serializeAsColor3("emissive")
  44916. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44917. __decorate([
  44918. BABYLON.serialize()
  44919. ], StandardMaterial.prototype, "specularPower", void 0);
  44920. __decorate([
  44921. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44922. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44923. __decorate([
  44924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44925. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44926. __decorate([
  44927. BABYLON.serialize("useEmissiveAsIllumination")
  44928. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44929. __decorate([
  44930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44931. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44932. __decorate([
  44933. BABYLON.serialize("linkEmissiveWithDiffuse")
  44934. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44935. __decorate([
  44936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44937. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44938. __decorate([
  44939. BABYLON.serialize("useSpecularOverAlpha")
  44940. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44941. __decorate([
  44942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44943. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44944. __decorate([
  44945. BABYLON.serialize("useReflectionOverAlpha")
  44946. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44947. __decorate([
  44948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44949. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44950. __decorate([
  44951. BABYLON.serialize("disableLighting")
  44952. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44953. __decorate([
  44954. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44955. ], StandardMaterial.prototype, "disableLighting", void 0);
  44956. __decorate([
  44957. BABYLON.serialize("useObjectSpaceNormalMap")
  44958. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44959. __decorate([
  44960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44961. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44962. __decorate([
  44963. BABYLON.serialize("useParallax")
  44964. ], StandardMaterial.prototype, "_useParallax", void 0);
  44965. __decorate([
  44966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44967. ], StandardMaterial.prototype, "useParallax", void 0);
  44968. __decorate([
  44969. BABYLON.serialize("useParallaxOcclusion")
  44970. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44971. __decorate([
  44972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44973. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44974. __decorate([
  44975. BABYLON.serialize()
  44976. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44977. __decorate([
  44978. BABYLON.serialize("roughness")
  44979. ], StandardMaterial.prototype, "_roughness", void 0);
  44980. __decorate([
  44981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44982. ], StandardMaterial.prototype, "roughness", void 0);
  44983. __decorate([
  44984. BABYLON.serialize()
  44985. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44986. __decorate([
  44987. BABYLON.serialize()
  44988. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44989. __decorate([
  44990. BABYLON.serialize()
  44991. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44992. __decorate([
  44993. BABYLON.serialize("useLightmapAsShadowmap")
  44994. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44995. __decorate([
  44996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44997. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44998. __decorate([
  44999. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  45000. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  45001. __decorate([
  45002. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45003. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  45004. __decorate([
  45005. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  45006. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  45007. __decorate([
  45008. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  45009. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  45010. __decorate([
  45011. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  45012. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  45013. __decorate([
  45014. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45015. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  45016. __decorate([
  45017. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  45018. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  45019. __decorate([
  45020. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45021. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  45022. __decorate([
  45023. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  45024. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  45025. __decorate([
  45026. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45027. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  45028. __decorate([
  45029. BABYLON.serialize("useReflectionFresnelFromSpecular")
  45030. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  45031. __decorate([
  45032. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  45033. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  45034. __decorate([
  45035. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  45036. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  45037. __decorate([
  45038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45039. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  45040. __decorate([
  45041. BABYLON.serialize("maxSimultaneousLights")
  45042. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  45043. __decorate([
  45044. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45045. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  45046. __decorate([
  45047. BABYLON.serialize("invertNormalMapX")
  45048. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  45049. __decorate([
  45050. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45051. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  45052. __decorate([
  45053. BABYLON.serialize("invertNormalMapY")
  45054. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  45055. __decorate([
  45056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45057. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  45058. __decorate([
  45059. BABYLON.serialize("twoSidedLighting")
  45060. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  45061. __decorate([
  45062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45063. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  45064. __decorate([
  45065. BABYLON.serialize()
  45066. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  45067. return StandardMaterial;
  45068. }(BABYLON.PushMaterial));
  45069. BABYLON.StandardMaterial = StandardMaterial;
  45070. })(BABYLON || (BABYLON = {}));
  45071. //# sourceMappingURL=standardMaterial.js.map
  45072. var BABYLON;
  45073. (function (BABYLON) {
  45074. /**
  45075. * Class representing spherical polynomial coefficients to the 3rd degree
  45076. */
  45077. var SphericalPolynomial = /** @class */ (function () {
  45078. function SphericalPolynomial() {
  45079. /**
  45080. * The x coefficients of the spherical polynomial
  45081. */
  45082. this.x = BABYLON.Vector3.Zero();
  45083. /**
  45084. * The y coefficients of the spherical polynomial
  45085. */
  45086. this.y = BABYLON.Vector3.Zero();
  45087. /**
  45088. * The z coefficients of the spherical polynomial
  45089. */
  45090. this.z = BABYLON.Vector3.Zero();
  45091. /**
  45092. * The xx coefficients of the spherical polynomial
  45093. */
  45094. this.xx = BABYLON.Vector3.Zero();
  45095. /**
  45096. * The yy coefficients of the spherical polynomial
  45097. */
  45098. this.yy = BABYLON.Vector3.Zero();
  45099. /**
  45100. * The zz coefficients of the spherical polynomial
  45101. */
  45102. this.zz = BABYLON.Vector3.Zero();
  45103. /**
  45104. * The xy coefficients of the spherical polynomial
  45105. */
  45106. this.xy = BABYLON.Vector3.Zero();
  45107. /**
  45108. * The yz coefficients of the spherical polynomial
  45109. */
  45110. this.yz = BABYLON.Vector3.Zero();
  45111. /**
  45112. * The zx coefficients of the spherical polynomial
  45113. */
  45114. this.zx = BABYLON.Vector3.Zero();
  45115. }
  45116. /**
  45117. * Adds an ambient color to the spherical polynomial
  45118. * @param color the color to add
  45119. */
  45120. SphericalPolynomial.prototype.addAmbient = function (color) {
  45121. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  45122. this.xx = this.xx.add(colorVector);
  45123. this.yy = this.yy.add(colorVector);
  45124. this.zz = this.zz.add(colorVector);
  45125. };
  45126. /**
  45127. * Scales the spherical polynomial by the given amount
  45128. * @param scale the amount to scale
  45129. */
  45130. SphericalPolynomial.prototype.scale = function (scale) {
  45131. this.x = this.x.scale(scale);
  45132. this.y = this.y.scale(scale);
  45133. this.z = this.z.scale(scale);
  45134. this.xx = this.xx.scale(scale);
  45135. this.yy = this.yy.scale(scale);
  45136. this.zz = this.zz.scale(scale);
  45137. this.yz = this.yz.scale(scale);
  45138. this.zx = this.zx.scale(scale);
  45139. this.xy = this.xy.scale(scale);
  45140. };
  45141. /**
  45142. * Gets the spherical polynomial from harmonics
  45143. * @param harmonics the spherical harmonics
  45144. * @returns the spherical polynomial
  45145. */
  45146. SphericalPolynomial.FromHarmonics = function (harmonics) {
  45147. var result = new SphericalPolynomial();
  45148. result.x = harmonics.l11.scale(1.02333);
  45149. result.y = harmonics.l1_1.scale(1.02333);
  45150. result.z = harmonics.l10.scale(1.02333);
  45151. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  45152. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  45153. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  45154. result.yz = harmonics.l2_1.scale(0.858086);
  45155. result.zx = harmonics.l21.scale(0.858086);
  45156. result.xy = harmonics.l2_2.scale(0.858086);
  45157. result.scale(1.0 / Math.PI);
  45158. return result;
  45159. };
  45160. /**
  45161. * Constructs a spherical polynomial from an array.
  45162. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  45163. * @returns the spherical polynomial
  45164. */
  45165. SphericalPolynomial.FromArray = function (data) {
  45166. var sp = new SphericalPolynomial();
  45167. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  45168. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  45169. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  45170. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  45171. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  45172. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  45173. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  45174. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  45175. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  45176. return sp;
  45177. };
  45178. return SphericalPolynomial;
  45179. }());
  45180. BABYLON.SphericalPolynomial = SphericalPolynomial;
  45181. /**
  45182. * Class representing spherical harmonics coefficients to the 3rd degree
  45183. */
  45184. var SphericalHarmonics = /** @class */ (function () {
  45185. function SphericalHarmonics() {
  45186. /**
  45187. * The l0,0 coefficients of the spherical harmonics
  45188. */
  45189. this.l00 = BABYLON.Vector3.Zero();
  45190. /**
  45191. * The l1,-1 coefficients of the spherical harmonics
  45192. */
  45193. this.l1_1 = BABYLON.Vector3.Zero();
  45194. /**
  45195. * The l1,0 coefficients of the spherical harmonics
  45196. */
  45197. this.l10 = BABYLON.Vector3.Zero();
  45198. /**
  45199. * The l1,1 coefficients of the spherical harmonics
  45200. */
  45201. this.l11 = BABYLON.Vector3.Zero();
  45202. /**
  45203. * The l2,-2 coefficients of the spherical harmonics
  45204. */
  45205. this.l2_2 = BABYLON.Vector3.Zero();
  45206. /**
  45207. * The l2,-1 coefficients of the spherical harmonics
  45208. */
  45209. this.l2_1 = BABYLON.Vector3.Zero();
  45210. /**
  45211. * The l2,0 coefficients of the spherical harmonics
  45212. */
  45213. this.l20 = BABYLON.Vector3.Zero();
  45214. /**
  45215. * The l2,1 coefficients of the spherical harmonics
  45216. */
  45217. this.l21 = BABYLON.Vector3.Zero();
  45218. /**
  45219. * The l2,2 coefficients of the spherical harmonics
  45220. */
  45221. this.lL22 = BABYLON.Vector3.Zero();
  45222. }
  45223. /**
  45224. * Adds a light to the spherical harmonics
  45225. * @param direction the direction of the light
  45226. * @param color the color of the light
  45227. * @param deltaSolidAngle the delta solid angle of the light
  45228. */
  45229. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  45230. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  45231. var c = colorVector.scale(deltaSolidAngle);
  45232. this.l00 = this.l00.add(c.scale(0.282095));
  45233. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  45234. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  45235. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  45236. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  45237. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  45238. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  45239. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  45240. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  45241. };
  45242. /**
  45243. * Scales the spherical harmonics by the given amount
  45244. * @param scale the amount to scale
  45245. */
  45246. SphericalHarmonics.prototype.scale = function (scale) {
  45247. this.l00 = this.l00.scale(scale);
  45248. this.l1_1 = this.l1_1.scale(scale);
  45249. this.l10 = this.l10.scale(scale);
  45250. this.l11 = this.l11.scale(scale);
  45251. this.l2_2 = this.l2_2.scale(scale);
  45252. this.l2_1 = this.l2_1.scale(scale);
  45253. this.l20 = this.l20.scale(scale);
  45254. this.l21 = this.l21.scale(scale);
  45255. this.lL22 = this.lL22.scale(scale);
  45256. };
  45257. /**
  45258. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  45259. *
  45260. * ```
  45261. * E_lm = A_l * L_lm
  45262. * ```
  45263. *
  45264. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  45265. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  45266. * the scaling factors are given in equation 9.
  45267. */
  45268. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  45269. // Constant (Band 0)
  45270. this.l00 = this.l00.scale(3.141593);
  45271. // Linear (Band 1)
  45272. this.l1_1 = this.l1_1.scale(2.094395);
  45273. this.l10 = this.l10.scale(2.094395);
  45274. this.l11 = this.l11.scale(2.094395);
  45275. // Quadratic (Band 2)
  45276. this.l2_2 = this.l2_2.scale(0.785398);
  45277. this.l2_1 = this.l2_1.scale(0.785398);
  45278. this.l20 = this.l20.scale(0.785398);
  45279. this.l21 = this.l21.scale(0.785398);
  45280. this.lL22 = this.lL22.scale(0.785398);
  45281. };
  45282. /**
  45283. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  45284. *
  45285. * ```
  45286. * L = (1/pi) * E * rho
  45287. * ```
  45288. *
  45289. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  45290. */
  45291. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  45292. this.scale(1.0 / Math.PI);
  45293. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  45294. // (The pixel shader must apply albedo after texture fetches, etc).
  45295. };
  45296. /**
  45297. * Gets the spherical harmonics from polynomial
  45298. * @param polynomial the spherical polynomial
  45299. * @returns the spherical harmonics
  45300. */
  45301. SphericalHarmonics.FromPolynomial = function (polynomial) {
  45302. var result = new SphericalHarmonics();
  45303. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  45304. result.l1_1 = polynomial.y.scale(0.977204);
  45305. result.l10 = polynomial.z.scale(0.977204);
  45306. result.l11 = polynomial.x.scale(0.977204);
  45307. result.l2_2 = polynomial.xy.scale(1.16538);
  45308. result.l2_1 = polynomial.yz.scale(1.16538);
  45309. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  45310. result.l21 = polynomial.zx.scale(1.16538);
  45311. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  45312. result.scale(Math.PI);
  45313. return result;
  45314. };
  45315. /**
  45316. * Constructs a spherical harmonics from an array.
  45317. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  45318. * @returns the spherical harmonics
  45319. */
  45320. SphericalHarmonics.FromArray = function (data) {
  45321. var sh = new SphericalHarmonics();
  45322. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  45323. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  45324. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  45325. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  45326. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  45327. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  45328. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  45329. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  45330. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  45331. return sh;
  45332. };
  45333. return SphericalHarmonics;
  45334. }());
  45335. BABYLON.SphericalHarmonics = SphericalHarmonics;
  45336. })(BABYLON || (BABYLON = {}));
  45337. //# sourceMappingURL=sphericalPolynomial.js.map
  45338. var BABYLON;
  45339. (function (BABYLON) {
  45340. var FileFaceOrientation = /** @class */ (function () {
  45341. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  45342. this.name = name;
  45343. this.worldAxisForNormal = worldAxisForNormal;
  45344. this.worldAxisForFileX = worldAxisForFileX;
  45345. this.worldAxisForFileY = worldAxisForFileY;
  45346. }
  45347. return FileFaceOrientation;
  45348. }());
  45349. /**
  45350. * Helper class dealing with the extraction of spherical polynomial dataArray
  45351. * from a cube map.
  45352. */
  45353. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  45354. function CubeMapToSphericalPolynomialTools() {
  45355. }
  45356. /**
  45357. * Converts a texture to the according Spherical Polynomial data.
  45358. * This extracts the first 3 orders only as they are the only one used in the lighting.
  45359. *
  45360. * @param texture The texture to extract the information from.
  45361. * @return The Spherical Polynomial data.
  45362. */
  45363. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  45364. if (!texture.isCube) {
  45365. // Only supports cube Textures currently.
  45366. return null;
  45367. }
  45368. var size = texture.getSize().width;
  45369. var right = texture.readPixels(0);
  45370. var left = texture.readPixels(1);
  45371. var up;
  45372. var down;
  45373. if (texture.isRenderTarget) {
  45374. up = texture.readPixels(3);
  45375. down = texture.readPixels(2);
  45376. }
  45377. else {
  45378. up = texture.readPixels(2);
  45379. down = texture.readPixels(3);
  45380. }
  45381. var front = texture.readPixels(4);
  45382. var back = texture.readPixels(5);
  45383. var gammaSpace = texture.gammaSpace;
  45384. // Always read as RGBA.
  45385. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  45386. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  45387. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  45388. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  45389. }
  45390. var cubeInfo = {
  45391. size: size,
  45392. right: right,
  45393. left: left,
  45394. up: up,
  45395. down: down,
  45396. front: front,
  45397. back: back,
  45398. format: format,
  45399. type: type,
  45400. gammaSpace: gammaSpace,
  45401. };
  45402. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  45403. };
  45404. /**
  45405. * Converts a cubemap to the according Spherical Polynomial data.
  45406. * This extracts the first 3 orders only as they are the only one used in the lighting.
  45407. *
  45408. * @param cubeInfo The Cube map to extract the information from.
  45409. * @return The Spherical Polynomial data.
  45410. */
  45411. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  45412. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  45413. var totalSolidAngle = 0.0;
  45414. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  45415. var du = 2.0 / cubeInfo.size;
  45416. var dv = du;
  45417. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  45418. var minUV = du * 0.5 - 1.0;
  45419. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  45420. var fileFace = this.FileFaces[faceIndex];
  45421. var dataArray = cubeInfo[fileFace.name];
  45422. var v = minUV;
  45423. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  45424. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  45425. // Because SP is still linear, so summation is fine in that basis.
  45426. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  45427. for (var y = 0; y < cubeInfo.size; y++) {
  45428. var u = minUV;
  45429. for (var x = 0; x < cubeInfo.size; x++) {
  45430. // World direction (not normalised)
  45431. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  45432. worldDirection.normalize();
  45433. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  45434. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  45435. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  45436. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  45437. // Handle Integer types.
  45438. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  45439. r /= 255;
  45440. g /= 255;
  45441. b /= 255;
  45442. }
  45443. // Handle Gamma space textures.
  45444. if (cubeInfo.gammaSpace) {
  45445. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  45446. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  45447. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  45448. }
  45449. var color = new BABYLON.Color3(r, g, b);
  45450. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  45451. totalSolidAngle += deltaSolidAngle;
  45452. u += du;
  45453. }
  45454. v += dv;
  45455. }
  45456. }
  45457. // Solid angle for entire sphere is 4*pi
  45458. var sphereSolidAngle = 4.0 * Math.PI;
  45459. // Adjust the solid angle to allow for how many faces we processed.
  45460. var facesProcessed = 6.0;
  45461. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  45462. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  45463. // This is needed because the numerical integration over the cube uses a
  45464. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  45465. // and also to compensate for accumulative error due to float precision in the summation.
  45466. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  45467. sphericalHarmonics.scale(correctionFactor);
  45468. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  45469. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  45470. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  45471. };
  45472. CubeMapToSphericalPolynomialTools.FileFaces = [
  45473. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  45474. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  45475. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  45476. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  45477. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  45478. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  45479. ];
  45480. return CubeMapToSphericalPolynomialTools;
  45481. }());
  45482. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  45483. })(BABYLON || (BABYLON = {}));
  45484. //# sourceMappingURL=cubemapToSphericalPolynomial.js.map
  45485. var BABYLON;
  45486. (function (BABYLON) {
  45487. /**
  45488. * Manages the defines for the PBR Material.
  45489. * @hiddenChildren
  45490. */
  45491. var PBRMaterialDefines = /** @class */ (function (_super) {
  45492. __extends(PBRMaterialDefines, _super);
  45493. /**
  45494. * Initializes the PBR Material defines.
  45495. */
  45496. function PBRMaterialDefines() {
  45497. var _this = _super.call(this) || this;
  45498. _this.PBR = true;
  45499. _this.MAINUV1 = false;
  45500. _this.MAINUV2 = false;
  45501. _this.UV1 = false;
  45502. _this.UV2 = false;
  45503. _this.ALBEDO = false;
  45504. _this.ALBEDODIRECTUV = 0;
  45505. _this.VERTEXCOLOR = false;
  45506. _this.AMBIENT = false;
  45507. _this.AMBIENTDIRECTUV = 0;
  45508. _this.AMBIENTINGRAYSCALE = false;
  45509. _this.OPACITY = false;
  45510. _this.VERTEXALPHA = false;
  45511. _this.OPACITYDIRECTUV = 0;
  45512. _this.OPACITYRGB = false;
  45513. _this.ALPHATEST = false;
  45514. _this.DEPTHPREPASS = false;
  45515. _this.ALPHABLEND = false;
  45516. _this.ALPHAFROMALBEDO = false;
  45517. _this.ALPHATESTVALUE = "0.5";
  45518. _this.SPECULAROVERALPHA = false;
  45519. _this.RADIANCEOVERALPHA = false;
  45520. _this.ALPHAFRESNEL = false;
  45521. _this.LINEARALPHAFRESNEL = false;
  45522. _this.PREMULTIPLYALPHA = false;
  45523. _this.EMISSIVE = false;
  45524. _this.EMISSIVEDIRECTUV = 0;
  45525. _this.REFLECTIVITY = false;
  45526. _this.REFLECTIVITYDIRECTUV = 0;
  45527. _this.SPECULARTERM = false;
  45528. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  45529. _this.MICROSURFACEAUTOMATIC = false;
  45530. _this.LODBASEDMICROSFURACE = false;
  45531. _this.MICROSURFACEMAP = false;
  45532. _this.MICROSURFACEMAPDIRECTUV = 0;
  45533. _this.METALLICWORKFLOW = false;
  45534. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  45535. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  45536. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  45537. _this.AOSTOREINMETALMAPRED = false;
  45538. _this.ENVIRONMENTBRDF = false;
  45539. _this.NORMAL = false;
  45540. _this.TANGENT = false;
  45541. _this.BUMP = false;
  45542. _this.BUMPDIRECTUV = 0;
  45543. _this.OBJECTSPACE_NORMALMAP = false;
  45544. _this.PARALLAX = false;
  45545. _this.PARALLAXOCCLUSION = false;
  45546. _this.NORMALXYSCALE = true;
  45547. _this.LIGHTMAP = false;
  45548. _this.LIGHTMAPDIRECTUV = 0;
  45549. _this.USELIGHTMAPASSHADOWMAP = false;
  45550. _this.GAMMALIGHTMAP = false;
  45551. _this.REFLECTION = false;
  45552. _this.REFLECTIONMAP_3D = false;
  45553. _this.REFLECTIONMAP_SPHERICAL = false;
  45554. _this.REFLECTIONMAP_PLANAR = false;
  45555. _this.REFLECTIONMAP_CUBIC = false;
  45556. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45557. _this.REFLECTIONMAP_PROJECTION = false;
  45558. _this.REFLECTIONMAP_SKYBOX = false;
  45559. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  45560. _this.REFLECTIONMAP_EXPLICIT = false;
  45561. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45562. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45563. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45564. _this.INVERTCUBICMAP = false;
  45565. _this.USESPHERICALFROMREFLECTIONMAP = false;
  45566. _this.USESPHERICALINVERTEX = false;
  45567. _this.REFLECTIONMAP_OPPOSITEZ = false;
  45568. _this.LODINREFLECTIONALPHA = false;
  45569. _this.GAMMAREFLECTION = false;
  45570. _this.RGBDREFLECTION = false;
  45571. _this.RADIANCEOCCLUSION = false;
  45572. _this.HORIZONOCCLUSION = false;
  45573. _this.REFRACTION = false;
  45574. _this.REFRACTIONMAP_3D = false;
  45575. _this.REFRACTIONMAP_OPPOSITEZ = false;
  45576. _this.LODINREFRACTIONALPHA = false;
  45577. _this.GAMMAREFRACTION = false;
  45578. _this.RGBDREFRACTION = false;
  45579. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  45580. _this.INSTANCES = false;
  45581. _this.NUM_BONE_INFLUENCERS = 0;
  45582. _this.BonesPerMesh = 0;
  45583. _this.BONETEXTURE = false;
  45584. _this.NONUNIFORMSCALING = false;
  45585. _this.MORPHTARGETS = false;
  45586. _this.MORPHTARGETS_NORMAL = false;
  45587. _this.MORPHTARGETS_TANGENT = false;
  45588. _this.NUM_MORPH_INFLUENCERS = 0;
  45589. _this.IMAGEPROCESSING = false;
  45590. _this.VIGNETTE = false;
  45591. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  45592. _this.VIGNETTEBLENDMODEOPAQUE = false;
  45593. _this.TONEMAPPING = false;
  45594. _this.TONEMAPPING_ACES = false;
  45595. _this.CONTRAST = false;
  45596. _this.COLORCURVES = false;
  45597. _this.COLORGRADING = false;
  45598. _this.COLORGRADING3D = false;
  45599. _this.SAMPLER3DGREENDEPTH = false;
  45600. _this.SAMPLER3DBGRMAP = false;
  45601. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  45602. _this.EXPOSURE = false;
  45603. _this.USEPHYSICALLIGHTFALLOFF = false;
  45604. _this.USEGLTFLIGHTFALLOFF = false;
  45605. _this.TWOSIDEDLIGHTING = false;
  45606. _this.SHADOWFLOAT = false;
  45607. _this.CLIPPLANE = false;
  45608. _this.CLIPPLANE2 = false;
  45609. _this.CLIPPLANE3 = false;
  45610. _this.CLIPPLANE4 = false;
  45611. _this.POINTSIZE = false;
  45612. _this.FOG = false;
  45613. _this.LOGARITHMICDEPTH = false;
  45614. _this.FORCENORMALFORWARD = false;
  45615. _this.SPECULARAA = false;
  45616. _this.UNLIT = false;
  45617. _this.rebuild();
  45618. return _this;
  45619. }
  45620. /**
  45621. * Resets the PBR Material defines.
  45622. */
  45623. PBRMaterialDefines.prototype.reset = function () {
  45624. _super.prototype.reset.call(this);
  45625. this.ALPHATESTVALUE = "0.5";
  45626. this.PBR = true;
  45627. };
  45628. return PBRMaterialDefines;
  45629. }(BABYLON.MaterialDefines));
  45630. /**
  45631. * The Physically based material base class of BJS.
  45632. *
  45633. * This offers the main features of a standard PBR material.
  45634. * For more information, please refer to the documentation :
  45635. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45636. */
  45637. var PBRBaseMaterial = /** @class */ (function (_super) {
  45638. __extends(PBRBaseMaterial, _super);
  45639. /**
  45640. * Instantiates a new PBRMaterial instance.
  45641. *
  45642. * @param name The material name
  45643. * @param scene The scene the material will be use in.
  45644. */
  45645. function PBRBaseMaterial(name, scene) {
  45646. var _this = _super.call(this, name, scene) || this;
  45647. /**
  45648. * Intensity of the direct lights e.g. the four lights available in your scene.
  45649. * This impacts both the direct diffuse and specular highlights.
  45650. */
  45651. _this._directIntensity = 1.0;
  45652. /**
  45653. * Intensity of the emissive part of the material.
  45654. * This helps controlling the emissive effect without modifying the emissive color.
  45655. */
  45656. _this._emissiveIntensity = 1.0;
  45657. /**
  45658. * Intensity of the environment e.g. how much the environment will light the object
  45659. * either through harmonics for rough material or through the refelction for shiny ones.
  45660. */
  45661. _this._environmentIntensity = 1.0;
  45662. /**
  45663. * This is a special control allowing the reduction of the specular highlights coming from the
  45664. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45665. */
  45666. _this._specularIntensity = 1.0;
  45667. /**
  45668. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  45669. */
  45670. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  45671. /**
  45672. * Debug Control allowing disabling the bump map on this material.
  45673. */
  45674. _this._disableBumpMap = false;
  45675. /**
  45676. * AKA Occlusion Texture Intensity in other nomenclature.
  45677. */
  45678. _this._ambientTextureStrength = 1.0;
  45679. /**
  45680. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45681. * 1 means it completely occludes it
  45682. * 0 mean it has no impact
  45683. */
  45684. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45685. /**
  45686. * The color of a material in ambient lighting.
  45687. */
  45688. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  45689. /**
  45690. * AKA Diffuse Color in other nomenclature.
  45691. */
  45692. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  45693. /**
  45694. * AKA Specular Color in other nomenclature.
  45695. */
  45696. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45697. /**
  45698. * The color applied when light is reflected from a material.
  45699. */
  45700. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  45701. /**
  45702. * The color applied when light is emitted from a material.
  45703. */
  45704. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  45705. /**
  45706. * AKA Glossiness in other nomenclature.
  45707. */
  45708. _this._microSurface = 0.9;
  45709. /**
  45710. * source material index of refraction (IOR)' / 'destination material IOR.
  45711. */
  45712. _this._indexOfRefraction = 0.66;
  45713. /**
  45714. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45715. */
  45716. _this._invertRefractionY = false;
  45717. /**
  45718. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45719. * Materials half opaque for instance using refraction could benefit from this control.
  45720. */
  45721. _this._linkRefractionWithTransparency = false;
  45722. /**
  45723. * Specifies that the material will use the light map as a show map.
  45724. */
  45725. _this._useLightmapAsShadowmap = false;
  45726. /**
  45727. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45728. * makes the reflect vector face the model (under horizon).
  45729. */
  45730. _this._useHorizonOcclusion = true;
  45731. /**
  45732. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45733. * too much the area relying on ambient texture to define their ambient occlusion.
  45734. */
  45735. _this._useRadianceOcclusion = true;
  45736. /**
  45737. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45738. */
  45739. _this._useAlphaFromAlbedoTexture = false;
  45740. /**
  45741. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45742. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45743. */
  45744. _this._useSpecularOverAlpha = true;
  45745. /**
  45746. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45747. */
  45748. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  45749. /**
  45750. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45751. */
  45752. _this._useRoughnessFromMetallicTextureAlpha = true;
  45753. /**
  45754. * Specifies if the metallic texture contains the roughness information in its green channel.
  45755. */
  45756. _this._useRoughnessFromMetallicTextureGreen = false;
  45757. /**
  45758. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45759. */
  45760. _this._useMetallnessFromMetallicTextureBlue = false;
  45761. /**
  45762. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45763. */
  45764. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  45765. /**
  45766. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45767. */
  45768. _this._useAmbientInGrayScale = false;
  45769. /**
  45770. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45771. * The material will try to infer what glossiness each pixel should be.
  45772. */
  45773. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  45774. /**
  45775. * Defines the falloff type used in this material.
  45776. * It by default is Physical.
  45777. */
  45778. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45779. /**
  45780. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45781. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45782. */
  45783. _this._useRadianceOverAlpha = true;
  45784. /**
  45785. * Allows using an object space normal map (instead of tangent space).
  45786. */
  45787. _this._useObjectSpaceNormalMap = false;
  45788. /**
  45789. * Allows using the bump map in parallax mode.
  45790. */
  45791. _this._useParallax = false;
  45792. /**
  45793. * Allows using the bump map in parallax occlusion mode.
  45794. */
  45795. _this._useParallaxOcclusion = false;
  45796. /**
  45797. * Controls the scale bias of the parallax mode.
  45798. */
  45799. _this._parallaxScaleBias = 0.05;
  45800. /**
  45801. * If sets to true, disables all the lights affecting the material.
  45802. */
  45803. _this._disableLighting = false;
  45804. /**
  45805. * Number of Simultaneous lights allowed on the material.
  45806. */
  45807. _this._maxSimultaneousLights = 4;
  45808. /**
  45809. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  45810. */
  45811. _this._invertNormalMapX = false;
  45812. /**
  45813. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  45814. */
  45815. _this._invertNormalMapY = false;
  45816. /**
  45817. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45818. */
  45819. _this._twoSidedLighting = false;
  45820. /**
  45821. * Defines the alpha limits in alpha test mode.
  45822. */
  45823. _this._alphaCutOff = 0.4;
  45824. /**
  45825. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45826. */
  45827. _this._forceAlphaTest = false;
  45828. /**
  45829. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45830. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45831. */
  45832. _this._useAlphaFresnel = false;
  45833. /**
  45834. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45835. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45836. */
  45837. _this._useLinearAlphaFresnel = false;
  45838. /**
  45839. * The transparency mode of the material.
  45840. */
  45841. _this._transparencyMode = null;
  45842. /**
  45843. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  45844. * from cos thetav and roughness:
  45845. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  45846. */
  45847. _this._environmentBRDFTexture = null;
  45848. /**
  45849. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45850. */
  45851. _this._forceIrradianceInFragment = false;
  45852. /**
  45853. * Force normal to face away from face.
  45854. */
  45855. _this._forceNormalForward = false;
  45856. /**
  45857. * Enables specular anti aliasing in the PBR shader.
  45858. * It will both interacts on the Geometry for analytical and IBL lighting.
  45859. * It also prefilter the roughness map based on the bump values.
  45860. */
  45861. _this._enableSpecularAntiAliasing = false;
  45862. /**
  45863. * Stores the available render targets.
  45864. */
  45865. _this._renderTargets = new BABYLON.SmartArray(16);
  45866. /**
  45867. * Sets the global ambient color for the material used in lighting calculations.
  45868. */
  45869. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  45870. /**
  45871. * If set to true, no lighting calculations will be applied.
  45872. */
  45873. _this._unlit = false;
  45874. // Setup the default processing configuration to the scene.
  45875. _this._attachImageProcessingConfiguration(null);
  45876. _this.getRenderTargetTextures = function () {
  45877. _this._renderTargets.reset();
  45878. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  45879. _this._renderTargets.push(_this._reflectionTexture);
  45880. }
  45881. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  45882. _this._renderTargets.push(_this._refractionTexture);
  45883. }
  45884. return _this._renderTargets;
  45885. };
  45886. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45887. return _this;
  45888. }
  45889. /**
  45890. * Attaches a new image processing configuration to the PBR Material.
  45891. * @param configuration
  45892. */
  45893. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  45894. var _this = this;
  45895. if (configuration === this._imageProcessingConfiguration) {
  45896. return;
  45897. }
  45898. // Detaches observer.
  45899. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45900. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45901. }
  45902. // Pick the scene configuration if needed.
  45903. if (!configuration) {
  45904. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  45905. }
  45906. else {
  45907. this._imageProcessingConfiguration = configuration;
  45908. }
  45909. // Attaches observer.
  45910. if (this._imageProcessingConfiguration) {
  45911. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  45912. _this._markAllSubMeshesAsImageProcessingDirty();
  45913. });
  45914. }
  45915. };
  45916. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  45917. /**
  45918. * Gets a boolean indicating that current material needs to register RTT
  45919. */
  45920. get: function () {
  45921. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45922. return true;
  45923. }
  45924. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45925. return true;
  45926. }
  45927. return false;
  45928. },
  45929. enumerable: true,
  45930. configurable: true
  45931. });
  45932. /**
  45933. * Gets the name of the material class.
  45934. */
  45935. PBRBaseMaterial.prototype.getClassName = function () {
  45936. return "PBRBaseMaterial";
  45937. };
  45938. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  45939. /**
  45940. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45941. */
  45942. get: function () {
  45943. return this._useLogarithmicDepth;
  45944. },
  45945. /**
  45946. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45947. */
  45948. set: function (value) {
  45949. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  45950. },
  45951. enumerable: true,
  45952. configurable: true
  45953. });
  45954. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  45955. /**
  45956. * Gets the current transparency mode.
  45957. */
  45958. get: function () {
  45959. return this._transparencyMode;
  45960. },
  45961. /**
  45962. * Sets the transparency mode of the material.
  45963. *
  45964. * | Value | Type | Description |
  45965. * | ----- | ----------------------------------- | ----------- |
  45966. * | 0 | OPAQUE | |
  45967. * | 1 | ALPHATEST | |
  45968. * | 2 | ALPHABLEND | |
  45969. * | 3 | ALPHATESTANDBLEND | |
  45970. *
  45971. */
  45972. set: function (value) {
  45973. if (this._transparencyMode === value) {
  45974. return;
  45975. }
  45976. this._transparencyMode = value;
  45977. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  45978. this._markAllSubMeshesAsTexturesAndMiscDirty();
  45979. },
  45980. enumerable: true,
  45981. configurable: true
  45982. });
  45983. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  45984. /**
  45985. * Returns true if alpha blending should be disabled.
  45986. */
  45987. get: function () {
  45988. return (this._linkRefractionWithTransparency ||
  45989. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  45990. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45991. },
  45992. enumerable: true,
  45993. configurable: true
  45994. });
  45995. /**
  45996. * Specifies whether or not this material should be rendered in alpha blend mode.
  45997. */
  45998. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  45999. if (this._disableAlphaBlending) {
  46000. return false;
  46001. }
  46002. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  46003. };
  46004. /**
  46005. * Specifies if the mesh will require alpha blending.
  46006. * @param mesh - BJS mesh.
  46007. */
  46008. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  46009. if (this._disableAlphaBlending) {
  46010. return false;
  46011. }
  46012. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  46013. };
  46014. /**
  46015. * Specifies whether or not this material should be rendered in alpha test mode.
  46016. */
  46017. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  46018. if (this._forceAlphaTest) {
  46019. return true;
  46020. }
  46021. if (this._linkRefractionWithTransparency) {
  46022. return false;
  46023. }
  46024. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  46025. };
  46026. /**
  46027. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  46028. */
  46029. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  46030. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  46031. };
  46032. /**
  46033. * Gets the texture used for the alpha test.
  46034. */
  46035. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  46036. return this._albedoTexture;
  46037. };
  46038. /**
  46039. * Specifies that the submesh is ready to be used.
  46040. * @param mesh - BJS mesh.
  46041. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  46042. * @param useInstances - Specifies that instances should be used.
  46043. * @returns - boolean indicating that the submesh is ready or not.
  46044. */
  46045. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  46046. if (subMesh.effect && this.isFrozen) {
  46047. if (this._wasPreviouslyReady) {
  46048. return true;
  46049. }
  46050. }
  46051. if (!subMesh._materialDefines) {
  46052. subMesh._materialDefines = new PBRMaterialDefines();
  46053. }
  46054. var defines = subMesh._materialDefines;
  46055. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  46056. if (defines._renderId === this.getScene().getRenderId()) {
  46057. return true;
  46058. }
  46059. }
  46060. var scene = this.getScene();
  46061. var engine = scene.getEngine();
  46062. if (defines._areTexturesDirty) {
  46063. if (scene.texturesEnabled) {
  46064. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46065. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  46066. return false;
  46067. }
  46068. }
  46069. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46070. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  46071. return false;
  46072. }
  46073. }
  46074. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46075. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  46076. return false;
  46077. }
  46078. }
  46079. var reflectionTexture = this._getReflectionTexture();
  46080. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46081. if (!reflectionTexture.isReadyOrNotBlocking()) {
  46082. return false;
  46083. }
  46084. }
  46085. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46086. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  46087. return false;
  46088. }
  46089. }
  46090. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46091. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  46092. return false;
  46093. }
  46094. }
  46095. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46096. if (this._metallicTexture) {
  46097. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  46098. return false;
  46099. }
  46100. }
  46101. else if (this._reflectivityTexture) {
  46102. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  46103. return false;
  46104. }
  46105. }
  46106. if (this._microSurfaceTexture) {
  46107. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  46108. return false;
  46109. }
  46110. }
  46111. }
  46112. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46113. // Bump texture cannot be not blocking.
  46114. if (!this._bumpTexture.isReady()) {
  46115. return false;
  46116. }
  46117. }
  46118. var refractionTexture = this._getRefractionTexture();
  46119. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46120. if (!refractionTexture.isReadyOrNotBlocking()) {
  46121. return false;
  46122. }
  46123. }
  46124. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46125. // This is blocking.
  46126. if (!this._environmentBRDFTexture.isReady()) {
  46127. return false;
  46128. }
  46129. }
  46130. }
  46131. }
  46132. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  46133. if (!this._imageProcessingConfiguration.isReady()) {
  46134. return false;
  46135. }
  46136. }
  46137. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  46138. mesh.createNormals(true);
  46139. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  46140. }
  46141. var previousEffect = subMesh.effect;
  46142. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  46143. if (effect) {
  46144. // Use previous effect while new one is compiling
  46145. if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
  46146. effect = previousEffect;
  46147. defines.markAsUnprocessed();
  46148. }
  46149. else {
  46150. scene.resetCachedMaterial();
  46151. subMesh.setEffect(effect, defines);
  46152. this.buildUniformLayout();
  46153. }
  46154. }
  46155. if (!subMesh.effect || !subMesh.effect.isReady()) {
  46156. return false;
  46157. }
  46158. defines._renderId = scene.getRenderId();
  46159. this._wasPreviouslyReady = true;
  46160. return true;
  46161. };
  46162. /**
  46163. * Specifies if the material uses metallic roughness workflow.
  46164. * @returns boolean specifiying if the material uses metallic roughness workflow.
  46165. */
  46166. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  46167. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  46168. return true;
  46169. }
  46170. return false;
  46171. };
  46172. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  46173. if (onCompiled === void 0) { onCompiled = null; }
  46174. if (onError === void 0) { onError = null; }
  46175. if (useInstances === void 0) { useInstances = null; }
  46176. if (useClipPlane === void 0) { useClipPlane = null; }
  46177. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  46178. if (!defines.isDirty) {
  46179. return null;
  46180. }
  46181. defines.markAsProcessed();
  46182. var scene = this.getScene();
  46183. var engine = scene.getEngine();
  46184. // Fallbacks
  46185. var fallbacks = new BABYLON.EffectFallbacks();
  46186. var fallbackRank = 0;
  46187. if (defines.USESPHERICALINVERTEX) {
  46188. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  46189. }
  46190. if (defines.FOG) {
  46191. fallbacks.addFallback(fallbackRank, "FOG");
  46192. }
  46193. if (defines.SPECULARAA) {
  46194. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  46195. }
  46196. if (defines.POINTSIZE) {
  46197. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  46198. }
  46199. if (defines.LOGARITHMICDEPTH) {
  46200. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  46201. }
  46202. if (defines.PARALLAX) {
  46203. fallbacks.addFallback(fallbackRank, "PARALLAX");
  46204. }
  46205. if (defines.PARALLAXOCCLUSION) {
  46206. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  46207. }
  46208. if (defines.ENVIRONMENTBRDF) {
  46209. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  46210. }
  46211. if (defines.TANGENT) {
  46212. fallbacks.addFallback(fallbackRank++, "TANGENT");
  46213. }
  46214. if (defines.BUMP) {
  46215. fallbacks.addFallback(fallbackRank++, "BUMP");
  46216. }
  46217. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  46218. if (defines.SPECULARTERM) {
  46219. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  46220. }
  46221. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  46222. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  46223. }
  46224. if (defines.LIGHTMAP) {
  46225. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  46226. }
  46227. if (defines.NORMAL) {
  46228. fallbacks.addFallback(fallbackRank++, "NORMAL");
  46229. }
  46230. if (defines.AMBIENT) {
  46231. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  46232. }
  46233. if (defines.EMISSIVE) {
  46234. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  46235. }
  46236. if (defines.VERTEXCOLOR) {
  46237. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  46238. }
  46239. if (defines.NUM_BONE_INFLUENCERS > 0) {
  46240. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  46241. }
  46242. if (defines.MORPHTARGETS) {
  46243. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  46244. }
  46245. //Attributes
  46246. var attribs = [BABYLON.VertexBuffer.PositionKind];
  46247. if (defines.NORMAL) {
  46248. attribs.push(BABYLON.VertexBuffer.NormalKind);
  46249. }
  46250. if (defines.TANGENT) {
  46251. attribs.push(BABYLON.VertexBuffer.TangentKind);
  46252. }
  46253. if (defines.UV1) {
  46254. attribs.push(BABYLON.VertexBuffer.UVKind);
  46255. }
  46256. if (defines.UV2) {
  46257. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46258. }
  46259. if (defines.VERTEXCOLOR) {
  46260. attribs.push(BABYLON.VertexBuffer.ColorKind);
  46261. }
  46262. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  46263. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  46264. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  46265. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  46266. "vFogInfos", "vFogColor", "pointSize",
  46267. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  46268. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  46269. "mBones",
  46270. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  46271. "vLightingIntensity",
  46272. "logarithmicDepthConstant",
  46273. "vSphericalX", "vSphericalY", "vSphericalZ",
  46274. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  46275. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  46276. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  46277. "vTangentSpaceParams", "boneTextureWidth"
  46278. ];
  46279. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  46280. "bumpSampler", "lightmapSampler", "opacitySampler",
  46281. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  46282. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  46283. "microSurfaceSampler", "environmentBrdfSampler", "boneSampler"];
  46284. var uniformBuffers = ["Material", "Scene"];
  46285. if (BABYLON.ImageProcessingConfiguration) {
  46286. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  46287. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  46288. }
  46289. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  46290. uniformsNames: uniforms,
  46291. uniformBuffersNames: uniformBuffers,
  46292. samplers: samplers,
  46293. defines: defines,
  46294. maxSimultaneousLights: this._maxSimultaneousLights
  46295. });
  46296. var join = defines.toString();
  46297. return engine.createEffect("pbr", {
  46298. attributes: attribs,
  46299. uniformsNames: uniforms,
  46300. uniformBuffersNames: uniformBuffers,
  46301. samplers: samplers,
  46302. defines: join,
  46303. fallbacks: fallbacks,
  46304. onCompiled: onCompiled,
  46305. onError: onError,
  46306. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  46307. }, engine);
  46308. };
  46309. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  46310. if (useInstances === void 0) { useInstances = null; }
  46311. if (useClipPlane === void 0) { useClipPlane = null; }
  46312. var scene = this.getScene();
  46313. var engine = scene.getEngine();
  46314. // Lights
  46315. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  46316. defines._needNormals = true;
  46317. // Textures
  46318. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  46319. if (defines._areTexturesDirty) {
  46320. defines._needUVs = false;
  46321. if (scene.texturesEnabled) {
  46322. if (scene.getEngine().getCaps().textureLOD) {
  46323. defines.LODBASEDMICROSFURACE = true;
  46324. }
  46325. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46326. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  46327. }
  46328. else {
  46329. defines.ALBEDO = false;
  46330. }
  46331. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46332. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  46333. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  46334. }
  46335. else {
  46336. defines.AMBIENT = false;
  46337. }
  46338. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46339. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  46340. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  46341. }
  46342. else {
  46343. defines.OPACITY = false;
  46344. }
  46345. var reflectionTexture = this._getReflectionTexture();
  46346. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46347. defines.REFLECTION = true;
  46348. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  46349. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  46350. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  46351. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  46352. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  46353. defines.INVERTCUBICMAP = true;
  46354. }
  46355. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  46356. switch (reflectionTexture.coordinatesMode) {
  46357. case BABYLON.Texture.EXPLICIT_MODE:
  46358. defines.REFLECTIONMAP_EXPLICIT = true;
  46359. break;
  46360. case BABYLON.Texture.PLANAR_MODE:
  46361. defines.REFLECTIONMAP_PLANAR = true;
  46362. break;
  46363. case BABYLON.Texture.PROJECTION_MODE:
  46364. defines.REFLECTIONMAP_PROJECTION = true;
  46365. break;
  46366. case BABYLON.Texture.SKYBOX_MODE:
  46367. defines.REFLECTIONMAP_SKYBOX = true;
  46368. break;
  46369. case BABYLON.Texture.SPHERICAL_MODE:
  46370. defines.REFLECTIONMAP_SPHERICAL = true;
  46371. break;
  46372. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  46373. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  46374. break;
  46375. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  46376. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  46377. break;
  46378. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  46379. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  46380. break;
  46381. case BABYLON.Texture.CUBIC_MODE:
  46382. case BABYLON.Texture.INVCUBIC_MODE:
  46383. default:
  46384. defines.REFLECTIONMAP_CUBIC = true;
  46385. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  46386. break;
  46387. }
  46388. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  46389. if (reflectionTexture.sphericalPolynomial) {
  46390. defines.USESPHERICALFROMREFLECTIONMAP = true;
  46391. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  46392. defines.USESPHERICALINVERTEX = false;
  46393. }
  46394. else {
  46395. defines.USESPHERICALINVERTEX = true;
  46396. }
  46397. }
  46398. }
  46399. else {
  46400. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  46401. }
  46402. }
  46403. else {
  46404. defines.REFLECTION = false;
  46405. defines.REFLECTIONMAP_3D = false;
  46406. defines.REFLECTIONMAP_SPHERICAL = false;
  46407. defines.REFLECTIONMAP_PLANAR = false;
  46408. defines.REFLECTIONMAP_CUBIC = false;
  46409. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  46410. defines.REFLECTIONMAP_PROJECTION = false;
  46411. defines.REFLECTIONMAP_SKYBOX = false;
  46412. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  46413. defines.REFLECTIONMAP_EXPLICIT = false;
  46414. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  46415. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  46416. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  46417. defines.INVERTCUBICMAP = false;
  46418. defines.USESPHERICALFROMREFLECTIONMAP = false;
  46419. defines.USESPHERICALINVERTEX = false;
  46420. defines.REFLECTIONMAP_OPPOSITEZ = false;
  46421. defines.LODINREFLECTIONALPHA = false;
  46422. defines.GAMMAREFLECTION = false;
  46423. defines.RGBDREFLECTION = false;
  46424. }
  46425. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46426. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  46427. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  46428. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  46429. }
  46430. else {
  46431. defines.LIGHTMAP = false;
  46432. }
  46433. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46434. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  46435. }
  46436. else {
  46437. defines.EMISSIVE = false;
  46438. }
  46439. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46440. if (this._metallicTexture) {
  46441. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  46442. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  46443. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  46444. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  46445. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  46446. }
  46447. else if (this._reflectivityTexture) {
  46448. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  46449. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  46450. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  46451. }
  46452. else {
  46453. defines.REFLECTIVITY = false;
  46454. }
  46455. if (this._microSurfaceTexture) {
  46456. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  46457. }
  46458. else {
  46459. defines.MICROSURFACEMAP = false;
  46460. }
  46461. }
  46462. else {
  46463. defines.REFLECTIVITY = false;
  46464. defines.MICROSURFACEMAP = false;
  46465. }
  46466. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46467. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  46468. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46469. defines.PARALLAX = true;
  46470. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  46471. }
  46472. else {
  46473. defines.PARALLAX = false;
  46474. }
  46475. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  46476. }
  46477. else {
  46478. defines.BUMP = false;
  46479. }
  46480. var refractionTexture = this._getRefractionTexture();
  46481. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46482. defines.REFRACTION = true;
  46483. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  46484. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  46485. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  46486. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  46487. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  46488. if (this._linkRefractionWithTransparency) {
  46489. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  46490. }
  46491. }
  46492. else {
  46493. defines.REFRACTION = false;
  46494. }
  46495. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46496. defines.ENVIRONMENTBRDF = true;
  46497. }
  46498. else {
  46499. defines.ENVIRONMENTBRDF = false;
  46500. }
  46501. if (this._shouldUseAlphaFromAlbedoTexture()) {
  46502. defines.ALPHAFROMALBEDO = true;
  46503. }
  46504. else {
  46505. defines.ALPHAFROMALBEDO = false;
  46506. }
  46507. }
  46508. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  46509. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  46510. defines.USEPHYSICALLIGHTFALLOFF = false;
  46511. defines.USEGLTFLIGHTFALLOFF = false;
  46512. }
  46513. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  46514. defines.USEPHYSICALLIGHTFALLOFF = false;
  46515. defines.USEGLTFLIGHTFALLOFF = true;
  46516. }
  46517. else {
  46518. defines.USEPHYSICALLIGHTFALLOFF = true;
  46519. defines.USEGLTFLIGHTFALLOFF = false;
  46520. }
  46521. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  46522. if (!this.backFaceCulling && this._twoSidedLighting) {
  46523. defines.TWOSIDEDLIGHTING = true;
  46524. }
  46525. else {
  46526. defines.TWOSIDEDLIGHTING = false;
  46527. }
  46528. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  46529. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  46530. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  46531. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  46532. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  46533. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  46534. }
  46535. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  46536. this._imageProcessingConfiguration.prepareDefines(defines);
  46537. }
  46538. defines.FORCENORMALFORWARD = this._forceNormalForward;
  46539. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  46540. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  46541. // Misc.
  46542. if (defines._areMiscDirty) {
  46543. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  46544. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  46545. }
  46546. // Values that need to be evaluated on every frame
  46547. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  46548. // Attribs
  46549. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  46550. };
  46551. /**
  46552. * Force shader compilation
  46553. */
  46554. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  46555. var _this = this;
  46556. var localOptions = __assign({ clipPlane: false }, options);
  46557. var defines = new PBRMaterialDefines();
  46558. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  46559. if (effect.isReady()) {
  46560. if (onCompiled) {
  46561. onCompiled(this);
  46562. }
  46563. }
  46564. else {
  46565. effect.onCompileObservable.add(function () {
  46566. if (onCompiled) {
  46567. onCompiled(_this);
  46568. }
  46569. });
  46570. }
  46571. };
  46572. /**
  46573. * Initializes the uniform buffer layout for the shader.
  46574. */
  46575. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  46576. // Order is important !
  46577. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  46578. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  46579. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  46580. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  46581. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  46582. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  46583. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  46584. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  46585. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  46586. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  46587. this._uniformBuffer.addUniform("vReflectionSize", 3);
  46588. this._uniformBuffer.addUniform("vBumpInfos", 3);
  46589. this._uniformBuffer.addUniform("albedoMatrix", 16);
  46590. this._uniformBuffer.addUniform("ambientMatrix", 16);
  46591. this._uniformBuffer.addUniform("opacityMatrix", 16);
  46592. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  46593. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  46594. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  46595. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  46596. this._uniformBuffer.addUniform("bumpMatrix", 16);
  46597. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  46598. this._uniformBuffer.addUniform("refractionMatrix", 16);
  46599. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  46600. this._uniformBuffer.addUniform("vReflectionColor", 3);
  46601. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  46602. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  46603. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  46604. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  46605. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  46606. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  46607. this._uniformBuffer.addUniform("pointSize", 1);
  46608. this._uniformBuffer.create();
  46609. };
  46610. /**
  46611. * Unbinds the textures.
  46612. */
  46613. PBRBaseMaterial.prototype.unbind = function () {
  46614. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  46615. this._uniformBuffer.setTexture("reflectionSampler", null);
  46616. }
  46617. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  46618. this._uniformBuffer.setTexture("refractionSampler", null);
  46619. }
  46620. _super.prototype.unbind.call(this);
  46621. };
  46622. /**
  46623. * Binds the submesh data.
  46624. * @param world - The world matrix.
  46625. * @param mesh - The BJS mesh.
  46626. * @param subMesh - A submesh of the BJS mesh.
  46627. */
  46628. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  46629. var scene = this.getScene();
  46630. var defines = subMesh._materialDefines;
  46631. if (!defines) {
  46632. return;
  46633. }
  46634. var effect = subMesh.effect;
  46635. if (!effect) {
  46636. return;
  46637. }
  46638. this._activeEffect = effect;
  46639. // Matrices
  46640. this.bindOnlyWorldMatrix(world);
  46641. // Normal Matrix
  46642. if (defines.OBJECTSPACE_NORMALMAP) {
  46643. world.toNormalMatrix(this._normalMatrix);
  46644. this.bindOnlyNormalMatrix(this._normalMatrix);
  46645. }
  46646. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  46647. // Bones
  46648. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  46649. var reflectionTexture = null;
  46650. if (mustRebind) {
  46651. this._uniformBuffer.bindToEffect(effect, "Material");
  46652. this.bindViewProjection(effect);
  46653. reflectionTexture = this._getReflectionTexture();
  46654. var refractionTexture = this._getRefractionTexture();
  46655. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  46656. // Texture uniforms
  46657. if (scene.texturesEnabled) {
  46658. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46659. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  46660. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  46661. }
  46662. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46663. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  46664. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  46665. }
  46666. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46667. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  46668. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  46669. }
  46670. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46671. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  46672. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  46673. if (reflectionTexture.boundingBoxSize) {
  46674. var cubeTexture = reflectionTexture;
  46675. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  46676. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  46677. }
  46678. var polynomials = reflectionTexture.sphericalPolynomial;
  46679. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  46680. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  46681. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  46682. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  46683. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  46684. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  46685. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  46686. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  46687. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  46688. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  46689. }
  46690. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  46691. }
  46692. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46693. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  46694. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  46695. }
  46696. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46697. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  46698. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  46699. }
  46700. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46701. if (this._metallicTexture) {
  46702. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  46703. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  46704. }
  46705. else if (this._reflectivityTexture) {
  46706. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  46707. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  46708. }
  46709. if (this._microSurfaceTexture) {
  46710. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  46711. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  46712. }
  46713. }
  46714. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46715. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  46716. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  46717. if (scene._mirroredCameraPosition) {
  46718. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  46719. }
  46720. else {
  46721. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  46722. }
  46723. }
  46724. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46725. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  46726. var depth = 1.0;
  46727. if (!refractionTexture.isCube) {
  46728. if (refractionTexture.depth) {
  46729. depth = refractionTexture.depth;
  46730. }
  46731. }
  46732. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  46733. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  46734. }
  46735. }
  46736. // Point size
  46737. if (this.pointsCloud) {
  46738. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  46739. }
  46740. // Colors
  46741. if (defines.METALLICWORKFLOW) {
  46742. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  46743. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  46744. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  46745. }
  46746. else {
  46747. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  46748. }
  46749. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  46750. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  46751. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  46752. // Misc
  46753. this._lightingInfos.x = this._directIntensity;
  46754. this._lightingInfos.y = this._emissiveIntensity;
  46755. this._lightingInfos.z = this._environmentIntensity;
  46756. this._lightingInfos.w = this._specularIntensity;
  46757. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  46758. }
  46759. // Textures
  46760. if (scene.texturesEnabled) {
  46761. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46762. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  46763. }
  46764. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46765. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  46766. }
  46767. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46768. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  46769. }
  46770. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46771. if (defines.LODBASEDMICROSFURACE) {
  46772. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  46773. }
  46774. else {
  46775. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  46776. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  46777. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  46778. }
  46779. }
  46780. if (defines.ENVIRONMENTBRDF) {
  46781. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  46782. }
  46783. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46784. if (defines.LODBASEDMICROSFURACE) {
  46785. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  46786. }
  46787. else {
  46788. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  46789. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  46790. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  46791. }
  46792. }
  46793. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46794. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  46795. }
  46796. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46797. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  46798. }
  46799. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46800. if (this._metallicTexture) {
  46801. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  46802. }
  46803. else if (this._reflectivityTexture) {
  46804. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  46805. }
  46806. if (this._microSurfaceTexture) {
  46807. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  46808. }
  46809. }
  46810. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46811. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  46812. }
  46813. }
  46814. // Clip plane
  46815. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  46816. // Colors
  46817. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  46818. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  46819. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  46820. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  46821. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  46822. }
  46823. if (mustRebind || !this.isFrozen) {
  46824. // Lights
  46825. if (scene.lightsEnabled && !this._disableLighting) {
  46826. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  46827. }
  46828. // View
  46829. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  46830. this.bindView(effect);
  46831. }
  46832. // Fog
  46833. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  46834. // Morph targets
  46835. if (defines.NUM_MORPH_INFLUENCERS) {
  46836. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  46837. }
  46838. // image processing
  46839. this._imageProcessingConfiguration.bind(this._activeEffect);
  46840. // Log. depth
  46841. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  46842. }
  46843. this._uniformBuffer.update();
  46844. this._afterBind(mesh, this._activeEffect);
  46845. };
  46846. /**
  46847. * Returns the animatable textures.
  46848. * @returns - Array of animatable textures.
  46849. */
  46850. PBRBaseMaterial.prototype.getAnimatables = function () {
  46851. var results = [];
  46852. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  46853. results.push(this._albedoTexture);
  46854. }
  46855. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  46856. results.push(this._ambientTexture);
  46857. }
  46858. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  46859. results.push(this._opacityTexture);
  46860. }
  46861. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  46862. results.push(this._reflectionTexture);
  46863. }
  46864. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  46865. results.push(this._emissiveTexture);
  46866. }
  46867. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  46868. results.push(this._metallicTexture);
  46869. }
  46870. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  46871. results.push(this._reflectivityTexture);
  46872. }
  46873. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  46874. results.push(this._bumpTexture);
  46875. }
  46876. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  46877. results.push(this._lightmapTexture);
  46878. }
  46879. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  46880. results.push(this._refractionTexture);
  46881. }
  46882. return results;
  46883. };
  46884. /**
  46885. * Returns the texture used for reflections.
  46886. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  46887. */
  46888. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  46889. if (this._reflectionTexture) {
  46890. return this._reflectionTexture;
  46891. }
  46892. return this.getScene().environmentTexture;
  46893. };
  46894. /**
  46895. * Returns the texture used for refraction or null if none is used.
  46896. * @returns - Refection texture if present. If no refraction texture and refraction
  46897. * is linked with transparency, returns environment texture. Otherwise, returns null.
  46898. */
  46899. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  46900. if (this._refractionTexture) {
  46901. return this._refractionTexture;
  46902. }
  46903. if (this._linkRefractionWithTransparency) {
  46904. return this.getScene().environmentTexture;
  46905. }
  46906. return null;
  46907. };
  46908. /**
  46909. * Disposes the resources of the material.
  46910. * @param forceDisposeEffect - Forces the disposal of effects.
  46911. * @param forceDisposeTextures - Forces the disposal of all textures.
  46912. */
  46913. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46914. if (forceDisposeTextures) {
  46915. if (this._albedoTexture) {
  46916. this._albedoTexture.dispose();
  46917. }
  46918. if (this._ambientTexture) {
  46919. this._ambientTexture.dispose();
  46920. }
  46921. if (this._opacityTexture) {
  46922. this._opacityTexture.dispose();
  46923. }
  46924. if (this._reflectionTexture) {
  46925. this._reflectionTexture.dispose();
  46926. }
  46927. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  46928. this._environmentBRDFTexture.dispose();
  46929. }
  46930. if (this._emissiveTexture) {
  46931. this._emissiveTexture.dispose();
  46932. }
  46933. if (this._metallicTexture) {
  46934. this._metallicTexture.dispose();
  46935. }
  46936. if (this._reflectivityTexture) {
  46937. this._reflectivityTexture.dispose();
  46938. }
  46939. if (this._bumpTexture) {
  46940. this._bumpTexture.dispose();
  46941. }
  46942. if (this._lightmapTexture) {
  46943. this._lightmapTexture.dispose();
  46944. }
  46945. if (this._refractionTexture) {
  46946. this._refractionTexture.dispose();
  46947. }
  46948. }
  46949. this._renderTargets.dispose();
  46950. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  46951. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  46952. }
  46953. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46954. };
  46955. /**
  46956. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  46957. */
  46958. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  46959. /**
  46960. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  46961. * to enhance interoperability with other engines.
  46962. */
  46963. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  46964. /**
  46965. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  46966. * to enhance interoperability with other materials.
  46967. */
  46968. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  46969. /**
  46970. * Stores the reflectivity values based on metallic roughness workflow.
  46971. */
  46972. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  46973. __decorate([
  46974. BABYLON.serializeAsImageProcessingConfiguration()
  46975. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  46976. __decorate([
  46977. BABYLON.serialize()
  46978. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  46979. __decorate([
  46980. BABYLON.serialize()
  46981. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  46982. return PBRBaseMaterial;
  46983. }(BABYLON.PushMaterial));
  46984. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  46985. })(BABYLON || (BABYLON = {}));
  46986. //# sourceMappingURL=pbrBaseMaterial.js.map
  46987. var BABYLON;
  46988. (function (BABYLON) {
  46989. /**
  46990. * The Physically based simple base material of BJS.
  46991. *
  46992. * This enables better naming and convention enforcements on top of the pbrMaterial.
  46993. * It is used as the base class for both the specGloss and metalRough conventions.
  46994. */
  46995. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  46996. __extends(PBRBaseSimpleMaterial, _super);
  46997. /**
  46998. * Instantiates a new PBRMaterial instance.
  46999. *
  47000. * @param name The material name
  47001. * @param scene The scene the material will be use in.
  47002. */
  47003. function PBRBaseSimpleMaterial(name, scene) {
  47004. var _this = _super.call(this, name, scene) || this;
  47005. /**
  47006. * Number of Simultaneous lights allowed on the material.
  47007. */
  47008. _this.maxSimultaneousLights = 4;
  47009. /**
  47010. * If sets to true, disables all the lights affecting the material.
  47011. */
  47012. _this.disableLighting = false;
  47013. /**
  47014. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  47015. */
  47016. _this.invertNormalMapX = false;
  47017. /**
  47018. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  47019. */
  47020. _this.invertNormalMapY = false;
  47021. /**
  47022. * Emissivie color used to self-illuminate the model.
  47023. */
  47024. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  47025. /**
  47026. * Occlusion Channel Strenght.
  47027. */
  47028. _this.occlusionStrength = 1.0;
  47029. /**
  47030. * If true, the light map contains occlusion information instead of lighting info.
  47031. */
  47032. _this.useLightmapAsShadowmap = false;
  47033. _this._useAlphaFromAlbedoTexture = true;
  47034. _this._useAmbientInGrayScale = true;
  47035. return _this;
  47036. }
  47037. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  47038. /**
  47039. * Gets the current double sided mode.
  47040. */
  47041. get: function () {
  47042. return this._twoSidedLighting;
  47043. },
  47044. /**
  47045. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  47046. */
  47047. set: function (value) {
  47048. if (this._twoSidedLighting === value) {
  47049. return;
  47050. }
  47051. this._twoSidedLighting = value;
  47052. this.backFaceCulling = !value;
  47053. this._markAllSubMeshesAsTexturesDirty();
  47054. },
  47055. enumerable: true,
  47056. configurable: true
  47057. });
  47058. /**
  47059. * Return the active textures of the material.
  47060. */
  47061. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  47062. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47063. if (this.environmentTexture) {
  47064. activeTextures.push(this.environmentTexture);
  47065. }
  47066. if (this.normalTexture) {
  47067. activeTextures.push(this.normalTexture);
  47068. }
  47069. if (this.emissiveTexture) {
  47070. activeTextures.push(this.emissiveTexture);
  47071. }
  47072. if (this.occlusionTexture) {
  47073. activeTextures.push(this.occlusionTexture);
  47074. }
  47075. if (this.lightmapTexture) {
  47076. activeTextures.push(this.lightmapTexture);
  47077. }
  47078. return activeTextures;
  47079. };
  47080. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  47081. if (_super.prototype.hasTexture.call(this, texture)) {
  47082. return true;
  47083. }
  47084. if (this.lightmapTexture === texture) {
  47085. return true;
  47086. }
  47087. return false;
  47088. };
  47089. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  47090. return "PBRBaseSimpleMaterial";
  47091. };
  47092. __decorate([
  47093. BABYLON.serialize(),
  47094. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47095. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  47096. __decorate([
  47097. BABYLON.serialize(),
  47098. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47099. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  47100. __decorate([
  47101. BABYLON.serializeAsTexture(),
  47102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  47103. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  47104. __decorate([
  47105. BABYLON.serialize(),
  47106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47107. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  47108. __decorate([
  47109. BABYLON.serialize(),
  47110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47111. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  47112. __decorate([
  47113. BABYLON.serializeAsTexture(),
  47114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  47115. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  47116. __decorate([
  47117. BABYLON.serializeAsColor3("emissive"),
  47118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47119. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  47120. __decorate([
  47121. BABYLON.serializeAsTexture(),
  47122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47123. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  47124. __decorate([
  47125. BABYLON.serialize(),
  47126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  47127. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  47128. __decorate([
  47129. BABYLON.serializeAsTexture(),
  47130. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  47131. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  47132. __decorate([
  47133. BABYLON.serialize(),
  47134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  47135. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  47136. __decorate([
  47137. BABYLON.serialize()
  47138. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  47139. __decorate([
  47140. BABYLON.serializeAsTexture(),
  47141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  47142. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  47143. __decorate([
  47144. BABYLON.serialize(),
  47145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47146. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  47147. return PBRBaseSimpleMaterial;
  47148. }(BABYLON.PBRBaseMaterial));
  47149. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  47150. })(BABYLON || (BABYLON = {}));
  47151. //# sourceMappingURL=pbrBaseSimpleMaterial.js.map
  47152. var BABYLON;
  47153. (function (BABYLON) {
  47154. /**
  47155. * The Physically based material of BJS.
  47156. *
  47157. * This offers the main features of a standard PBR material.
  47158. * For more information, please refer to the documentation :
  47159. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  47160. */
  47161. var PBRMaterial = /** @class */ (function (_super) {
  47162. __extends(PBRMaterial, _super);
  47163. /**
  47164. * Instantiates a new PBRMaterial instance.
  47165. *
  47166. * @param name The material name
  47167. * @param scene The scene the material will be use in.
  47168. */
  47169. function PBRMaterial(name, scene) {
  47170. var _this = _super.call(this, name, scene) || this;
  47171. /**
  47172. * Intensity of the direct lights e.g. the four lights available in your scene.
  47173. * This impacts both the direct diffuse and specular highlights.
  47174. */
  47175. _this.directIntensity = 1.0;
  47176. /**
  47177. * Intensity of the emissive part of the material.
  47178. * This helps controlling the emissive effect without modifying the emissive color.
  47179. */
  47180. _this.emissiveIntensity = 1.0;
  47181. /**
  47182. * Intensity of the environment e.g. how much the environment will light the object
  47183. * either through harmonics for rough material or through the refelction for shiny ones.
  47184. */
  47185. _this.environmentIntensity = 1.0;
  47186. /**
  47187. * This is a special control allowing the reduction of the specular highlights coming from the
  47188. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  47189. */
  47190. _this.specularIntensity = 1.0;
  47191. /**
  47192. * Debug Control allowing disabling the bump map on this material.
  47193. */
  47194. _this.disableBumpMap = false;
  47195. /**
  47196. * AKA Occlusion Texture Intensity in other nomenclature.
  47197. */
  47198. _this.ambientTextureStrength = 1.0;
  47199. /**
  47200. * Defines how much the AO map is occluding the analytical lights (point spot...).
  47201. * 1 means it completely occludes it
  47202. * 0 mean it has no impact
  47203. */
  47204. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  47205. /**
  47206. * The color of a material in ambient lighting.
  47207. */
  47208. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  47209. /**
  47210. * AKA Diffuse Color in other nomenclature.
  47211. */
  47212. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  47213. /**
  47214. * AKA Specular Color in other nomenclature.
  47215. */
  47216. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  47217. /**
  47218. * The color reflected from the material.
  47219. */
  47220. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  47221. /**
  47222. * The color emitted from the material.
  47223. */
  47224. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  47225. /**
  47226. * AKA Glossiness in other nomenclature.
  47227. */
  47228. _this.microSurface = 1.0;
  47229. /**
  47230. * source material index of refraction (IOR)' / 'destination material IOR.
  47231. */
  47232. _this.indexOfRefraction = 0.66;
  47233. /**
  47234. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  47235. */
  47236. _this.invertRefractionY = false;
  47237. /**
  47238. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  47239. * Materials half opaque for instance using refraction could benefit from this control.
  47240. */
  47241. _this.linkRefractionWithTransparency = false;
  47242. /**
  47243. * If true, the light map contains occlusion information instead of lighting info.
  47244. */
  47245. _this.useLightmapAsShadowmap = false;
  47246. /**
  47247. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  47248. */
  47249. _this.useAlphaFromAlbedoTexture = false;
  47250. /**
  47251. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  47252. */
  47253. _this.forceAlphaTest = false;
  47254. /**
  47255. * Defines the alpha limits in alpha test mode.
  47256. */
  47257. _this.alphaCutOff = 0.4;
  47258. /**
  47259. * Specifies that the material will keep the specular highlights over a transparent surface (only the most limunous ones).
  47260. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  47261. */
  47262. _this.useSpecularOverAlpha = true;
  47263. /**
  47264. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  47265. */
  47266. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  47267. /**
  47268. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  47269. */
  47270. _this.useRoughnessFromMetallicTextureAlpha = true;
  47271. /**
  47272. * Specifies if the metallic texture contains the roughness information in its green channel.
  47273. */
  47274. _this.useRoughnessFromMetallicTextureGreen = false;
  47275. /**
  47276. * Specifies if the metallic texture contains the metallness information in its blue channel.
  47277. */
  47278. _this.useMetallnessFromMetallicTextureBlue = false;
  47279. /**
  47280. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  47281. */
  47282. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  47283. /**
  47284. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  47285. */
  47286. _this.useAmbientInGrayScale = false;
  47287. /**
  47288. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  47289. * The material will try to infer what glossiness each pixel should be.
  47290. */
  47291. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  47292. /**
  47293. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  47294. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  47295. */
  47296. _this.useRadianceOverAlpha = true;
  47297. /**
  47298. * Allows using an object space normal map (instead of tangent space).
  47299. */
  47300. _this.useObjectSpaceNormalMap = false;
  47301. /**
  47302. * Allows using the bump map in parallax mode.
  47303. */
  47304. _this.useParallax = false;
  47305. /**
  47306. * Allows using the bump map in parallax occlusion mode.
  47307. */
  47308. _this.useParallaxOcclusion = false;
  47309. /**
  47310. * Controls the scale bias of the parallax mode.
  47311. */
  47312. _this.parallaxScaleBias = 0.05;
  47313. /**
  47314. * If sets to true, disables all the lights affecting the material.
  47315. */
  47316. _this.disableLighting = false;
  47317. /**
  47318. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  47319. */
  47320. _this.forceIrradianceInFragment = false;
  47321. /**
  47322. * Number of Simultaneous lights allowed on the material.
  47323. */
  47324. _this.maxSimultaneousLights = 4;
  47325. /**
  47326. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  47327. */
  47328. _this.invertNormalMapX = false;
  47329. /**
  47330. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  47331. */
  47332. _this.invertNormalMapY = false;
  47333. /**
  47334. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  47335. */
  47336. _this.twoSidedLighting = false;
  47337. /**
  47338. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  47339. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  47340. */
  47341. _this.useAlphaFresnel = false;
  47342. /**
  47343. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  47344. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  47345. */
  47346. _this.useLinearAlphaFresnel = false;
  47347. /**
  47348. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  47349. * And/Or occlude the blended part.
  47350. */
  47351. _this.environmentBRDFTexture = null;
  47352. /**
  47353. * Force normal to face away from face.
  47354. */
  47355. _this.forceNormalForward = false;
  47356. /**
  47357. * Enables specular anti aliasing in the PBR shader.
  47358. * It will both interacts on the Geometry for analytical and IBL lighting.
  47359. * It also prefilter the roughness map based on the bump values.
  47360. */
  47361. _this.enableSpecularAntiAliasing = false;
  47362. /**
  47363. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  47364. * makes the reflect vector face the model (under horizon).
  47365. */
  47366. _this.useHorizonOcclusion = true;
  47367. /**
  47368. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  47369. * too much the area relying on ambient texture to define their ambient occlusion.
  47370. */
  47371. _this.useRadianceOcclusion = true;
  47372. /**
  47373. * If set to true, no lighting calculations will be applied.
  47374. */
  47375. _this.unlit = false;
  47376. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  47377. return _this;
  47378. }
  47379. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  47380. /**
  47381. * BJS is using an harcoded light falloff based on a manually sets up range.
  47382. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  47383. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  47384. */
  47385. get: function () {
  47386. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  47387. },
  47388. /**
  47389. * BJS is using an harcoded light falloff based on a manually sets up range.
  47390. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  47391. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  47392. */
  47393. set: function (value) {
  47394. if (value !== this.usePhysicalLightFalloff) {
  47395. // Ensure the effect will be rebuilt.
  47396. this._markAllSubMeshesAsTexturesDirty();
  47397. if (value) {
  47398. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  47399. }
  47400. else {
  47401. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  47402. }
  47403. }
  47404. },
  47405. enumerable: true,
  47406. configurable: true
  47407. });
  47408. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  47409. /**
  47410. * In order to support the falloff compatibility with gltf, a special mode has been added
  47411. * to reproduce the gltf light falloff.
  47412. */
  47413. get: function () {
  47414. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  47415. },
  47416. /**
  47417. * In order to support the falloff compatibility with gltf, a special mode has been added
  47418. * to reproduce the gltf light falloff.
  47419. */
  47420. set: function (value) {
  47421. if (value !== this.useGLTFLightFalloff) {
  47422. // Ensure the effect will be rebuilt.
  47423. this._markAllSubMeshesAsTexturesDirty();
  47424. if (value) {
  47425. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  47426. }
  47427. else {
  47428. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  47429. }
  47430. }
  47431. },
  47432. enumerable: true,
  47433. configurable: true
  47434. });
  47435. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  47436. /**
  47437. * Gets the image processing configuration used either in this material.
  47438. */
  47439. get: function () {
  47440. return this._imageProcessingConfiguration;
  47441. },
  47442. /**
  47443. * Sets the Default image processing configuration used either in the this material.
  47444. *
  47445. * If sets to null, the scene one is in use.
  47446. */
  47447. set: function (value) {
  47448. this._attachImageProcessingConfiguration(value);
  47449. // Ensure the effect will be rebuilt.
  47450. this._markAllSubMeshesAsTexturesDirty();
  47451. },
  47452. enumerable: true,
  47453. configurable: true
  47454. });
  47455. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  47456. /**
  47457. * Gets wether the color curves effect is enabled.
  47458. */
  47459. get: function () {
  47460. return this.imageProcessingConfiguration.colorCurvesEnabled;
  47461. },
  47462. /**
  47463. * Sets wether the color curves effect is enabled.
  47464. */
  47465. set: function (value) {
  47466. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  47467. },
  47468. enumerable: true,
  47469. configurable: true
  47470. });
  47471. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  47472. /**
  47473. * Gets wether the color grading effect is enabled.
  47474. */
  47475. get: function () {
  47476. return this.imageProcessingConfiguration.colorGradingEnabled;
  47477. },
  47478. /**
  47479. * Gets wether the color grading effect is enabled.
  47480. */
  47481. set: function (value) {
  47482. this.imageProcessingConfiguration.colorGradingEnabled = value;
  47483. },
  47484. enumerable: true,
  47485. configurable: true
  47486. });
  47487. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  47488. /**
  47489. * Gets wether tonemapping is enabled or not.
  47490. */
  47491. get: function () {
  47492. return this._imageProcessingConfiguration.toneMappingEnabled;
  47493. },
  47494. /**
  47495. * Sets wether tonemapping is enabled or not
  47496. */
  47497. set: function (value) {
  47498. this._imageProcessingConfiguration.toneMappingEnabled = value;
  47499. },
  47500. enumerable: true,
  47501. configurable: true
  47502. });
  47503. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  47504. /**
  47505. * The camera exposure used on this material.
  47506. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  47507. * This corresponds to a photographic exposure.
  47508. */
  47509. get: function () {
  47510. return this._imageProcessingConfiguration.exposure;
  47511. },
  47512. /**
  47513. * The camera exposure used on this material.
  47514. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  47515. * This corresponds to a photographic exposure.
  47516. */
  47517. set: function (value) {
  47518. this._imageProcessingConfiguration.exposure = value;
  47519. },
  47520. enumerable: true,
  47521. configurable: true
  47522. });
  47523. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  47524. /**
  47525. * Gets The camera contrast used on this material.
  47526. */
  47527. get: function () {
  47528. return this._imageProcessingConfiguration.contrast;
  47529. },
  47530. /**
  47531. * Sets The camera contrast used on this material.
  47532. */
  47533. set: function (value) {
  47534. this._imageProcessingConfiguration.contrast = value;
  47535. },
  47536. enumerable: true,
  47537. configurable: true
  47538. });
  47539. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  47540. /**
  47541. * Gets the Color Grading 2D Lookup Texture.
  47542. */
  47543. get: function () {
  47544. return this._imageProcessingConfiguration.colorGradingTexture;
  47545. },
  47546. /**
  47547. * Sets the Color Grading 2D Lookup Texture.
  47548. */
  47549. set: function (value) {
  47550. this._imageProcessingConfiguration.colorGradingTexture = value;
  47551. },
  47552. enumerable: true,
  47553. configurable: true
  47554. });
  47555. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  47556. /**
  47557. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  47558. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  47559. * 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;
  47560. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  47561. */
  47562. get: function () {
  47563. return this._imageProcessingConfiguration.colorCurves;
  47564. },
  47565. /**
  47566. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  47567. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  47568. * 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;
  47569. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  47570. */
  47571. set: function (value) {
  47572. this._imageProcessingConfiguration.colorCurves = value;
  47573. },
  47574. enumerable: true,
  47575. configurable: true
  47576. });
  47577. /**
  47578. * Returns the name of this material class.
  47579. */
  47580. PBRMaterial.prototype.getClassName = function () {
  47581. return "PBRMaterial";
  47582. };
  47583. /**
  47584. * Returns an array of the actively used textures.
  47585. * @returns - Array of BaseTextures
  47586. */
  47587. PBRMaterial.prototype.getActiveTextures = function () {
  47588. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47589. if (this._albedoTexture) {
  47590. activeTextures.push(this._albedoTexture);
  47591. }
  47592. if (this._ambientTexture) {
  47593. activeTextures.push(this._ambientTexture);
  47594. }
  47595. if (this._opacityTexture) {
  47596. activeTextures.push(this._opacityTexture);
  47597. }
  47598. if (this._reflectionTexture) {
  47599. activeTextures.push(this._reflectionTexture);
  47600. }
  47601. if (this._emissiveTexture) {
  47602. activeTextures.push(this._emissiveTexture);
  47603. }
  47604. if (this._reflectivityTexture) {
  47605. activeTextures.push(this._reflectivityTexture);
  47606. }
  47607. if (this._metallicTexture) {
  47608. activeTextures.push(this._metallicTexture);
  47609. }
  47610. if (this._microSurfaceTexture) {
  47611. activeTextures.push(this._microSurfaceTexture);
  47612. }
  47613. if (this._bumpTexture) {
  47614. activeTextures.push(this._bumpTexture);
  47615. }
  47616. if (this._lightmapTexture) {
  47617. activeTextures.push(this._lightmapTexture);
  47618. }
  47619. if (this._refractionTexture) {
  47620. activeTextures.push(this._refractionTexture);
  47621. }
  47622. return activeTextures;
  47623. };
  47624. /**
  47625. * Checks to see if a texture is used in the material.
  47626. * @param texture - Base texture to use.
  47627. * @returns - Boolean specifying if a texture is used in the material.
  47628. */
  47629. PBRMaterial.prototype.hasTexture = function (texture) {
  47630. if (_super.prototype.hasTexture.call(this, texture)) {
  47631. return true;
  47632. }
  47633. if (this._albedoTexture === texture) {
  47634. return true;
  47635. }
  47636. if (this._ambientTexture === texture) {
  47637. return true;
  47638. }
  47639. if (this._opacityTexture === texture) {
  47640. return true;
  47641. }
  47642. if (this._reflectionTexture === texture) {
  47643. return true;
  47644. }
  47645. if (this._reflectivityTexture === texture) {
  47646. return true;
  47647. }
  47648. if (this._metallicTexture === texture) {
  47649. return true;
  47650. }
  47651. if (this._microSurfaceTexture === texture) {
  47652. return true;
  47653. }
  47654. if (this._bumpTexture === texture) {
  47655. return true;
  47656. }
  47657. if (this._lightmapTexture === texture) {
  47658. return true;
  47659. }
  47660. if (this._refractionTexture === texture) {
  47661. return true;
  47662. }
  47663. return false;
  47664. };
  47665. /**
  47666. * Makes a duplicate of the current material.
  47667. * @param name - name to use for the new material.
  47668. */
  47669. PBRMaterial.prototype.clone = function (name) {
  47670. var _this = this;
  47671. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  47672. clone.id = name;
  47673. clone.name = name;
  47674. return clone;
  47675. };
  47676. /**
  47677. * Serializes this PBR Material.
  47678. * @returns - An object with the serialized material.
  47679. */
  47680. PBRMaterial.prototype.serialize = function () {
  47681. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47682. serializationObject.customType = "BABYLON.PBRMaterial";
  47683. return serializationObject;
  47684. };
  47685. // Statics
  47686. /**
  47687. * Parses a PBR Material from a serialized object.
  47688. * @param source - Serialized object.
  47689. * @param scene - BJS scene instance.
  47690. * @param rootUrl - url for the scene object
  47691. * @returns - PBRMaterial
  47692. */
  47693. PBRMaterial.Parse = function (source, scene, rootUrl) {
  47694. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  47695. };
  47696. /**
  47697. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  47698. */
  47699. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  47700. /**
  47701. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  47702. */
  47703. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  47704. /**
  47705. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47706. */
  47707. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  47708. /**
  47709. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47710. * They are also discarded below the alpha cutoff threshold to improve performances.
  47711. */
  47712. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  47713. /**
  47714. * Defines the default value of how much AO map is occluding the analytical lights
  47715. * (point spot...).
  47716. */
  47717. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  47718. __decorate([
  47719. BABYLON.serialize(),
  47720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47721. ], PBRMaterial.prototype, "directIntensity", void 0);
  47722. __decorate([
  47723. BABYLON.serialize(),
  47724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47725. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  47726. __decorate([
  47727. BABYLON.serialize(),
  47728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47729. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  47730. __decorate([
  47731. BABYLON.serialize(),
  47732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47733. ], PBRMaterial.prototype, "specularIntensity", void 0);
  47734. __decorate([
  47735. BABYLON.serialize(),
  47736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47737. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  47738. __decorate([
  47739. BABYLON.serializeAsTexture(),
  47740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47741. ], PBRMaterial.prototype, "albedoTexture", void 0);
  47742. __decorate([
  47743. BABYLON.serializeAsTexture(),
  47744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47745. ], PBRMaterial.prototype, "ambientTexture", void 0);
  47746. __decorate([
  47747. BABYLON.serialize(),
  47748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47749. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  47750. __decorate([
  47751. BABYLON.serialize(),
  47752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47753. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  47754. __decorate([
  47755. BABYLON.serializeAsTexture(),
  47756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47757. ], PBRMaterial.prototype, "opacityTexture", void 0);
  47758. __decorate([
  47759. BABYLON.serializeAsTexture(),
  47760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47761. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  47762. __decorate([
  47763. BABYLON.serializeAsTexture(),
  47764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47765. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  47766. __decorate([
  47767. BABYLON.serializeAsTexture(),
  47768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47769. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  47770. __decorate([
  47771. BABYLON.serializeAsTexture(),
  47772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47773. ], PBRMaterial.prototype, "metallicTexture", void 0);
  47774. __decorate([
  47775. BABYLON.serialize(),
  47776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47777. ], PBRMaterial.prototype, "metallic", void 0);
  47778. __decorate([
  47779. BABYLON.serialize(),
  47780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47781. ], PBRMaterial.prototype, "roughness", void 0);
  47782. __decorate([
  47783. BABYLON.serializeAsTexture(),
  47784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47785. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  47786. __decorate([
  47787. BABYLON.serializeAsTexture(),
  47788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47789. ], PBRMaterial.prototype, "bumpTexture", void 0);
  47790. __decorate([
  47791. BABYLON.serializeAsTexture(),
  47792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  47793. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  47794. __decorate([
  47795. BABYLON.serializeAsTexture(),
  47796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47797. ], PBRMaterial.prototype, "refractionTexture", void 0);
  47798. __decorate([
  47799. BABYLON.serializeAsColor3("ambient"),
  47800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47801. ], PBRMaterial.prototype, "ambientColor", void 0);
  47802. __decorate([
  47803. BABYLON.serializeAsColor3("albedo"),
  47804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47805. ], PBRMaterial.prototype, "albedoColor", void 0);
  47806. __decorate([
  47807. BABYLON.serializeAsColor3("reflectivity"),
  47808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47809. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  47810. __decorate([
  47811. BABYLON.serializeAsColor3("reflection"),
  47812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47813. ], PBRMaterial.prototype, "reflectionColor", void 0);
  47814. __decorate([
  47815. BABYLON.serializeAsColor3("emissive"),
  47816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47817. ], PBRMaterial.prototype, "emissiveColor", void 0);
  47818. __decorate([
  47819. BABYLON.serialize(),
  47820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47821. ], PBRMaterial.prototype, "microSurface", void 0);
  47822. __decorate([
  47823. BABYLON.serialize(),
  47824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47825. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  47826. __decorate([
  47827. BABYLON.serialize(),
  47828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47829. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  47830. __decorate([
  47831. BABYLON.serialize(),
  47832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47833. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  47834. __decorate([
  47835. BABYLON.serialize(),
  47836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47837. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  47838. __decorate([
  47839. BABYLON.serialize(),
  47840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47841. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  47842. __decorate([
  47843. BABYLON.serialize(),
  47844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47845. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  47846. __decorate([
  47847. BABYLON.serialize(),
  47848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47849. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  47850. __decorate([
  47851. BABYLON.serialize(),
  47852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47853. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  47854. __decorate([
  47855. BABYLON.serialize(),
  47856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47857. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  47858. __decorate([
  47859. BABYLON.serialize(),
  47860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47861. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  47862. __decorate([
  47863. BABYLON.serialize(),
  47864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47865. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  47866. __decorate([
  47867. BABYLON.serialize(),
  47868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47869. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  47870. __decorate([
  47871. BABYLON.serialize(),
  47872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47873. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  47874. __decorate([
  47875. BABYLON.serialize(),
  47876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47877. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  47878. __decorate([
  47879. BABYLON.serialize(),
  47880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47881. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  47882. __decorate([
  47883. BABYLON.serialize()
  47884. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  47885. __decorate([
  47886. BABYLON.serialize()
  47887. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  47888. __decorate([
  47889. BABYLON.serialize(),
  47890. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47891. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  47892. __decorate([
  47893. BABYLON.serialize(),
  47894. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47895. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  47896. __decorate([
  47897. BABYLON.serialize(),
  47898. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47899. ], PBRMaterial.prototype, "useParallax", void 0);
  47900. __decorate([
  47901. BABYLON.serialize(),
  47902. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47903. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  47904. __decorate([
  47905. BABYLON.serialize(),
  47906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47907. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  47908. __decorate([
  47909. BABYLON.serialize(),
  47910. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47911. ], PBRMaterial.prototype, "disableLighting", void 0);
  47912. __decorate([
  47913. BABYLON.serialize(),
  47914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47915. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  47916. __decorate([
  47917. BABYLON.serialize(),
  47918. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47919. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  47920. __decorate([
  47921. BABYLON.serialize(),
  47922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47923. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  47924. __decorate([
  47925. BABYLON.serialize(),
  47926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47927. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  47928. __decorate([
  47929. BABYLON.serialize(),
  47930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47931. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  47932. __decorate([
  47933. BABYLON.serialize(),
  47934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47935. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  47936. __decorate([
  47937. BABYLON.serialize(),
  47938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47939. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  47940. __decorate([
  47941. BABYLON.serializeAsTexture(),
  47942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47943. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  47944. __decorate([
  47945. BABYLON.serialize(),
  47946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47947. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  47948. __decorate([
  47949. BABYLON.serialize(),
  47950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47951. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  47952. __decorate([
  47953. BABYLON.serialize(),
  47954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47955. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  47956. __decorate([
  47957. BABYLON.serialize(),
  47958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47959. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  47960. __decorate([
  47961. BABYLON.serialize(),
  47962. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  47963. ], PBRMaterial.prototype, "unlit", void 0);
  47964. return PBRMaterial;
  47965. }(BABYLON.PBRBaseMaterial));
  47966. BABYLON.PBRMaterial = PBRMaterial;
  47967. })(BABYLON || (BABYLON = {}));
  47968. //# sourceMappingURL=pbrMaterial.js.map
  47969. var BABYLON;
  47970. (function (BABYLON) {
  47971. /**
  47972. * The PBR material of BJS following the metal roughness convention.
  47973. *
  47974. * This fits to the PBR convention in the GLTF definition:
  47975. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  47976. */
  47977. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  47978. __extends(PBRMetallicRoughnessMaterial, _super);
  47979. /**
  47980. * Instantiates a new PBRMetalRoughnessMaterial instance.
  47981. *
  47982. * @param name The material name
  47983. * @param scene The scene the material will be use in.
  47984. */
  47985. function PBRMetallicRoughnessMaterial(name, scene) {
  47986. var _this = _super.call(this, name, scene) || this;
  47987. _this._useRoughnessFromMetallicTextureAlpha = false;
  47988. _this._useRoughnessFromMetallicTextureGreen = true;
  47989. _this._useMetallnessFromMetallicTextureBlue = true;
  47990. _this.metallic = 1.0;
  47991. _this.roughness = 1.0;
  47992. return _this;
  47993. }
  47994. /**
  47995. * Return the currrent class name of the material.
  47996. */
  47997. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  47998. return "PBRMetallicRoughnessMaterial";
  47999. };
  48000. /**
  48001. * Return the active textures of the material.
  48002. */
  48003. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  48004. var activeTextures = _super.prototype.getActiveTextures.call(this);
  48005. if (this.baseTexture) {
  48006. activeTextures.push(this.baseTexture);
  48007. }
  48008. if (this.metallicRoughnessTexture) {
  48009. activeTextures.push(this.metallicRoughnessTexture);
  48010. }
  48011. return activeTextures;
  48012. };
  48013. /**
  48014. * Checks to see if a texture is used in the material.
  48015. * @param texture - Base texture to use.
  48016. * @returns - Boolean specifying if a texture is used in the material.
  48017. */
  48018. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  48019. if (_super.prototype.hasTexture.call(this, texture)) {
  48020. return true;
  48021. }
  48022. if (this.baseTexture === texture) {
  48023. return true;
  48024. }
  48025. if (this.metallicRoughnessTexture === texture) {
  48026. return true;
  48027. }
  48028. return false;
  48029. };
  48030. /**
  48031. * Makes a duplicate of the current material.
  48032. * @param name - name to use for the new material.
  48033. */
  48034. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  48035. var _this = this;
  48036. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  48037. clone.id = name;
  48038. clone.name = name;
  48039. return clone;
  48040. };
  48041. /**
  48042. * Serialize the material to a parsable JSON object.
  48043. */
  48044. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  48045. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48046. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  48047. return serializationObject;
  48048. };
  48049. /**
  48050. * Parses a JSON object correponding to the serialize function.
  48051. */
  48052. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  48053. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  48054. };
  48055. __decorate([
  48056. BABYLON.serializeAsColor3(),
  48057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  48058. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  48059. __decorate([
  48060. BABYLON.serializeAsTexture(),
  48061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  48062. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  48063. __decorate([
  48064. BABYLON.serialize(),
  48065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48066. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  48067. __decorate([
  48068. BABYLON.serialize(),
  48069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  48070. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  48071. __decorate([
  48072. BABYLON.serializeAsTexture(),
  48073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  48074. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  48075. return PBRMetallicRoughnessMaterial;
  48076. }(BABYLON.PBRBaseSimpleMaterial));
  48077. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  48078. })(BABYLON || (BABYLON = {}));
  48079. //# sourceMappingURL=pbrMetallicRoughnessMaterial.js.map
  48080. var BABYLON;
  48081. (function (BABYLON) {
  48082. /**
  48083. * The PBR material of BJS following the specular glossiness convention.
  48084. *
  48085. * This fits to the PBR convention in the GLTF definition:
  48086. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  48087. */
  48088. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  48089. __extends(PBRSpecularGlossinessMaterial, _super);
  48090. /**
  48091. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  48092. *
  48093. * @param name The material name
  48094. * @param scene The scene the material will be use in.
  48095. */
  48096. function PBRSpecularGlossinessMaterial(name, scene) {
  48097. var _this = _super.call(this, name, scene) || this;
  48098. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  48099. return _this;
  48100. }
  48101. /**
  48102. * Return the currrent class name of the material.
  48103. */
  48104. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  48105. return "PBRSpecularGlossinessMaterial";
  48106. };
  48107. /**
  48108. * Return the active textures of the material.
  48109. */
  48110. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  48111. var activeTextures = _super.prototype.getActiveTextures.call(this);
  48112. if (this.diffuseTexture) {
  48113. activeTextures.push(this.diffuseTexture);
  48114. }
  48115. if (this.specularGlossinessTexture) {
  48116. activeTextures.push(this.specularGlossinessTexture);
  48117. }
  48118. return activeTextures;
  48119. };
  48120. /**
  48121. * Checks to see if a texture is used in the material.
  48122. * @param texture - Base texture to use.
  48123. * @returns - Boolean specifying if a texture is used in the material.
  48124. */
  48125. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  48126. if (_super.prototype.hasTexture.call(this, texture)) {
  48127. return true;
  48128. }
  48129. if (this.diffuseTexture === texture) {
  48130. return true;
  48131. }
  48132. if (this.specularGlossinessTexture === texture) {
  48133. return true;
  48134. }
  48135. return false;
  48136. };
  48137. /**
  48138. * Makes a duplicate of the current material.
  48139. * @param name - name to use for the new material.
  48140. */
  48141. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  48142. var _this = this;
  48143. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  48144. clone.id = name;
  48145. clone.name = name;
  48146. return clone;
  48147. };
  48148. /**
  48149. * Serialize the material to a parsable JSON object.
  48150. */
  48151. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  48152. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48153. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  48154. return serializationObject;
  48155. };
  48156. /**
  48157. * Parses a JSON object correponding to the serialize function.
  48158. */
  48159. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  48160. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  48161. };
  48162. __decorate([
  48163. BABYLON.serializeAsColor3("diffuse"),
  48164. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  48165. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  48166. __decorate([
  48167. BABYLON.serializeAsTexture(),
  48168. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  48169. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  48170. __decorate([
  48171. BABYLON.serializeAsColor3("specular"),
  48172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  48173. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  48174. __decorate([
  48175. BABYLON.serialize(),
  48176. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  48177. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  48178. __decorate([
  48179. BABYLON.serializeAsTexture(),
  48180. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  48181. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  48182. return PBRSpecularGlossinessMaterial;
  48183. }(BABYLON.PBRBaseSimpleMaterial));
  48184. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  48185. })(BABYLON || (BABYLON = {}));
  48186. //# sourceMappingURL=pbrSpecularGlossinessMaterial.js.map
  48187. var BABYLON;
  48188. (function (BABYLON) {
  48189. /**
  48190. * @ignore
  48191. * This is a list of all the different input types that are available in the application.
  48192. * Fo instance: ArcRotateCameraGamepadInput...
  48193. */
  48194. BABYLON.CameraInputTypes = {};
  48195. /**
  48196. * This represents the input manager used within a camera.
  48197. * It helps dealing with all the different kind of input attached to a camera.
  48198. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48199. */
  48200. var CameraInputsManager = /** @class */ (function () {
  48201. /**
  48202. * Instantiate a new Camera Input Manager.
  48203. * @param camera Defines the camera the input manager blongs to
  48204. */
  48205. function CameraInputsManager(camera) {
  48206. this.attached = {};
  48207. this.camera = camera;
  48208. this.checkInputs = function () { };
  48209. }
  48210. /**
  48211. * Add an input method to a camera
  48212. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48213. * @param input camera input method
  48214. */
  48215. CameraInputsManager.prototype.add = function (input) {
  48216. var type = input.getSimpleName();
  48217. if (this.attached[type]) {
  48218. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  48219. return;
  48220. }
  48221. this.attached[type] = input;
  48222. input.camera = this.camera;
  48223. //for checkInputs, we are dynamically creating a function
  48224. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  48225. if (input.checkInputs) {
  48226. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  48227. }
  48228. if (this.attachedElement) {
  48229. input.attachControl(this.attachedElement);
  48230. }
  48231. };
  48232. /**
  48233. * Remove a specific input method from a camera
  48234. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  48235. * @param inputToRemove camera input method
  48236. */
  48237. CameraInputsManager.prototype.remove = function (inputToRemove) {
  48238. for (var cam in this.attached) {
  48239. var input = this.attached[cam];
  48240. if (input === inputToRemove) {
  48241. input.detachControl(this.attachedElement);
  48242. input.camera = null;
  48243. delete this.attached[cam];
  48244. this.rebuildInputCheck();
  48245. }
  48246. }
  48247. };
  48248. /**
  48249. * Remove a specific input type from a camera
  48250. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  48251. * @param inputType the type of the input to remove
  48252. */
  48253. CameraInputsManager.prototype.removeByType = function (inputType) {
  48254. for (var cam in this.attached) {
  48255. var input = this.attached[cam];
  48256. if (input.getClassName() === inputType) {
  48257. input.detachControl(this.attachedElement);
  48258. input.camera = null;
  48259. delete this.attached[cam];
  48260. this.rebuildInputCheck();
  48261. }
  48262. }
  48263. };
  48264. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  48265. var current = this.checkInputs;
  48266. return function () {
  48267. current();
  48268. fn();
  48269. };
  48270. };
  48271. /**
  48272. * Attach the input controls to the currently attached dom element to listen the events from.
  48273. * @param input Defines the input to attach
  48274. */
  48275. CameraInputsManager.prototype.attachInput = function (input) {
  48276. if (this.attachedElement) {
  48277. input.attachControl(this.attachedElement, this.noPreventDefault);
  48278. }
  48279. };
  48280. /**
  48281. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  48282. * @param element Defines the dom element to collect the events from
  48283. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48284. */
  48285. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  48286. if (noPreventDefault === void 0) { noPreventDefault = false; }
  48287. if (this.attachedElement) {
  48288. return;
  48289. }
  48290. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  48291. this.attachedElement = element;
  48292. this.noPreventDefault = noPreventDefault;
  48293. for (var cam in this.attached) {
  48294. this.attached[cam].attachControl(element, noPreventDefault);
  48295. }
  48296. };
  48297. /**
  48298. * Detach the current manager inputs controls from a specific dom element.
  48299. * @param element Defines the dom element to collect the events from
  48300. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  48301. */
  48302. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  48303. if (disconnect === void 0) { disconnect = false; }
  48304. if (this.attachedElement !== element) {
  48305. return;
  48306. }
  48307. for (var cam in this.attached) {
  48308. this.attached[cam].detachControl(element);
  48309. if (disconnect) {
  48310. this.attached[cam].camera = null;
  48311. }
  48312. }
  48313. this.attachedElement = null;
  48314. };
  48315. /**
  48316. * Rebuild the dynamic inputCheck function from the current list of
  48317. * defined inputs in the manager.
  48318. */
  48319. CameraInputsManager.prototype.rebuildInputCheck = function () {
  48320. this.checkInputs = function () { };
  48321. for (var cam in this.attached) {
  48322. var input = this.attached[cam];
  48323. if (input.checkInputs) {
  48324. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  48325. }
  48326. }
  48327. };
  48328. /**
  48329. * Remove all attached input methods from a camera
  48330. */
  48331. CameraInputsManager.prototype.clear = function () {
  48332. if (this.attachedElement) {
  48333. this.detachElement(this.attachedElement, true);
  48334. }
  48335. this.attached = {};
  48336. this.attachedElement = null;
  48337. this.checkInputs = function () { };
  48338. };
  48339. /**
  48340. * Serialize the current input manager attached to a camera.
  48341. * This ensures than once parsed,
  48342. * the input associated to the camera will be identical to the current ones
  48343. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  48344. */
  48345. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  48346. var inputs = {};
  48347. for (var cam in this.attached) {
  48348. var input = this.attached[cam];
  48349. var res = BABYLON.SerializationHelper.Serialize(input);
  48350. inputs[input.getClassName()] = res;
  48351. }
  48352. serializedCamera.inputsmgr = inputs;
  48353. };
  48354. /**
  48355. * Parses an input manager serialized JSON to restore the previous list of inputs
  48356. * and states associated to a camera.
  48357. * @param parsedCamera Defines the JSON to parse
  48358. */
  48359. CameraInputsManager.prototype.parse = function (parsedCamera) {
  48360. var parsedInputs = parsedCamera.inputsmgr;
  48361. if (parsedInputs) {
  48362. this.clear();
  48363. for (var n in parsedInputs) {
  48364. var construct = BABYLON.CameraInputTypes[n];
  48365. if (construct) {
  48366. var parsedinput = parsedInputs[n];
  48367. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  48368. this.add(input);
  48369. }
  48370. }
  48371. }
  48372. else {
  48373. //2016-03-08 this part is for managing backward compatibility
  48374. for (var n in this.attached) {
  48375. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  48376. if (construct) {
  48377. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  48378. this.remove(this.attached[n]);
  48379. this.add(input);
  48380. }
  48381. }
  48382. }
  48383. };
  48384. return CameraInputsManager;
  48385. }());
  48386. BABYLON.CameraInputsManager = CameraInputsManager;
  48387. })(BABYLON || (BABYLON = {}));
  48388. //# sourceMappingURL=cameraInputsManager.js.map
  48389. var BABYLON;
  48390. (function (BABYLON) {
  48391. /**
  48392. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  48393. * This is the base of the follow, arc rotate cameras and Free camera
  48394. * @see http://doc.babylonjs.com/features/cameras
  48395. */
  48396. var TargetCamera = /** @class */ (function (_super) {
  48397. __extends(TargetCamera, _super);
  48398. /**
  48399. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  48400. * This is the base of the follow, arc rotate cameras and Free camera
  48401. * @see http://doc.babylonjs.com/features/cameras
  48402. * @param name Defines the name of the camera in the scene
  48403. * @param position Defines the start position of the camera in the scene
  48404. * @param scene Defines the scene the camera belongs to
  48405. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48406. */
  48407. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  48408. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48409. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  48410. /**
  48411. * Define the current direction the camera is moving to
  48412. */
  48413. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48414. /**
  48415. * Define the current rotation the camera is rotating to
  48416. */
  48417. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  48418. /**
  48419. * Define the current rotation of the camera
  48420. */
  48421. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  48422. /**
  48423. * Define the current speed of the camera
  48424. */
  48425. _this.speed = 2.0;
  48426. /**
  48427. * Add cconstraint to the camera to prevent it to move freely in all directions and
  48428. * around all axis.
  48429. */
  48430. _this.noRotationConstraint = false;
  48431. /**
  48432. * Define the current target of the camera as an object or a position.
  48433. */
  48434. _this.lockedTarget = null;
  48435. /** @hidden */
  48436. _this._currentTarget = BABYLON.Vector3.Zero();
  48437. /** @hidden */
  48438. _this._viewMatrix = BABYLON.Matrix.Zero();
  48439. /** @hidden */
  48440. _this._camMatrix = BABYLON.Matrix.Zero();
  48441. /** @hidden */
  48442. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  48443. /** @hidden */
  48444. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  48445. /** @hidden */
  48446. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  48447. /** @hidden */
  48448. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  48449. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  48450. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  48451. _this._defaultUp = BABYLON.Vector3.Up();
  48452. _this._cachedRotationZ = 0;
  48453. _this._cachedQuaternionRotationZ = 0;
  48454. return _this;
  48455. }
  48456. /**
  48457. * Gets the position in front of the camera at a given distance.
  48458. * @param distance The distance from the camera we want the position to be
  48459. * @returns the position
  48460. */
  48461. TargetCamera.prototype.getFrontPosition = function (distance) {
  48462. this.getWorldMatrix();
  48463. var direction = this.getTarget().subtract(this.position);
  48464. direction.normalize();
  48465. direction.scaleInPlace(distance);
  48466. return this.globalPosition.add(direction);
  48467. };
  48468. /** @hidden */
  48469. TargetCamera.prototype._getLockedTargetPosition = function () {
  48470. if (!this.lockedTarget) {
  48471. return null;
  48472. }
  48473. if (this.lockedTarget.absolutePosition) {
  48474. this.lockedTarget.computeWorldMatrix();
  48475. }
  48476. return this.lockedTarget.absolutePosition || this.lockedTarget;
  48477. };
  48478. /**
  48479. * Store current camera state of the camera (fov, position, rotation, etc..)
  48480. * @returns the camera
  48481. */
  48482. TargetCamera.prototype.storeState = function () {
  48483. this._storedPosition = this.position.clone();
  48484. this._storedRotation = this.rotation.clone();
  48485. if (this.rotationQuaternion) {
  48486. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  48487. }
  48488. return _super.prototype.storeState.call(this);
  48489. };
  48490. /**
  48491. * Restored camera state. You must call storeState() first
  48492. * @returns whether it was successful or not
  48493. * @hidden
  48494. */
  48495. TargetCamera.prototype._restoreStateValues = function () {
  48496. if (!_super.prototype._restoreStateValues.call(this)) {
  48497. return false;
  48498. }
  48499. this.position = this._storedPosition.clone();
  48500. this.rotation = this._storedRotation.clone();
  48501. if (this.rotationQuaternion) {
  48502. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  48503. }
  48504. this.cameraDirection.copyFromFloats(0, 0, 0);
  48505. this.cameraRotation.copyFromFloats(0, 0);
  48506. return true;
  48507. };
  48508. /** @hidden */
  48509. TargetCamera.prototype._initCache = function () {
  48510. _super.prototype._initCache.call(this);
  48511. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48512. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48513. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48514. };
  48515. /** @hidden */
  48516. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  48517. if (!ignoreParentClass) {
  48518. _super.prototype._updateCache.call(this);
  48519. }
  48520. var lockedTargetPosition = this._getLockedTargetPosition();
  48521. if (!lockedTargetPosition) {
  48522. this._cache.lockedTarget = null;
  48523. }
  48524. else {
  48525. if (!this._cache.lockedTarget) {
  48526. this._cache.lockedTarget = lockedTargetPosition.clone();
  48527. }
  48528. else {
  48529. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  48530. }
  48531. }
  48532. this._cache.rotation.copyFrom(this.rotation);
  48533. if (this.rotationQuaternion) {
  48534. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48535. }
  48536. };
  48537. // Synchronized
  48538. /** @hidden */
  48539. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  48540. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  48541. return false;
  48542. }
  48543. var lockedTargetPosition = this._getLockedTargetPosition();
  48544. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  48545. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  48546. };
  48547. // Methods
  48548. /** @hidden */
  48549. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  48550. var engine = this.getEngine();
  48551. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  48552. };
  48553. // Target
  48554. /** @hidden */
  48555. TargetCamera.prototype.setTarget = function (target) {
  48556. this.upVector.normalize();
  48557. if (this.position.z === target.z) {
  48558. this.position.z += BABYLON.Epsilon;
  48559. }
  48560. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  48561. this._camMatrix.invert();
  48562. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  48563. var vDir = target.subtract(this.position);
  48564. if (vDir.x >= 0.0) {
  48565. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  48566. }
  48567. else {
  48568. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  48569. }
  48570. this.rotation.z = 0;
  48571. if (isNaN(this.rotation.x)) {
  48572. this.rotation.x = 0;
  48573. }
  48574. if (isNaN(this.rotation.y)) {
  48575. this.rotation.y = 0;
  48576. }
  48577. if (isNaN(this.rotation.z)) {
  48578. this.rotation.z = 0;
  48579. }
  48580. if (this.rotationQuaternion) {
  48581. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  48582. }
  48583. };
  48584. /**
  48585. * Return the current target position of the camera. This value is expressed in local space.
  48586. * @returns the target position
  48587. */
  48588. TargetCamera.prototype.getTarget = function () {
  48589. return this._currentTarget;
  48590. };
  48591. /** @hidden */
  48592. TargetCamera.prototype._decideIfNeedsToMove = function () {
  48593. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48594. };
  48595. /** @hidden */
  48596. TargetCamera.prototype._updatePosition = function () {
  48597. if (this.parent) {
  48598. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  48599. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  48600. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  48601. return;
  48602. }
  48603. this.position.addInPlace(this.cameraDirection);
  48604. };
  48605. /** @hidden */
  48606. TargetCamera.prototype._checkInputs = function () {
  48607. var needToMove = this._decideIfNeedsToMove();
  48608. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  48609. // Move
  48610. if (needToMove) {
  48611. this._updatePosition();
  48612. }
  48613. // Rotate
  48614. if (needToRotate) {
  48615. this.rotation.x += this.cameraRotation.x;
  48616. this.rotation.y += this.cameraRotation.y;
  48617. //rotate, if quaternion is set and rotation was used
  48618. if (this.rotationQuaternion) {
  48619. var len = this.rotation.lengthSquared();
  48620. if (len) {
  48621. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  48622. }
  48623. }
  48624. if (!this.noRotationConstraint) {
  48625. var limit = (Math.PI / 2) * 0.95;
  48626. if (this.rotation.x > limit) {
  48627. this.rotation.x = limit;
  48628. }
  48629. if (this.rotation.x < -limit) {
  48630. this.rotation.x = -limit;
  48631. }
  48632. }
  48633. }
  48634. // Inertia
  48635. if (needToMove) {
  48636. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  48637. this.cameraDirection.x = 0;
  48638. }
  48639. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  48640. this.cameraDirection.y = 0;
  48641. }
  48642. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  48643. this.cameraDirection.z = 0;
  48644. }
  48645. this.cameraDirection.scaleInPlace(this.inertia);
  48646. }
  48647. if (needToRotate) {
  48648. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  48649. this.cameraRotation.x = 0;
  48650. }
  48651. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  48652. this.cameraRotation.y = 0;
  48653. }
  48654. this.cameraRotation.scaleInPlace(this.inertia);
  48655. }
  48656. _super.prototype._checkInputs.call(this);
  48657. };
  48658. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  48659. if (this.rotationQuaternion) {
  48660. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  48661. }
  48662. else {
  48663. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  48664. }
  48665. };
  48666. /**
  48667. * 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)
  48668. * @returns the current camera
  48669. */
  48670. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  48671. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  48672. return this;
  48673. };
  48674. /** @hidden */
  48675. TargetCamera.prototype._getViewMatrix = function () {
  48676. if (this.lockedTarget) {
  48677. this.setTarget(this._getLockedTargetPosition());
  48678. }
  48679. // Compute
  48680. this._updateCameraRotationMatrix();
  48681. // Apply the changed rotation to the upVector
  48682. if (this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z) {
  48683. this._rotateUpVectorWithCameraRotationMatrix();
  48684. this._cachedQuaternionRotationZ = this.rotationQuaternion.z;
  48685. }
  48686. else if (this._cachedRotationZ != this.rotation.z) {
  48687. this._rotateUpVectorWithCameraRotationMatrix();
  48688. this._cachedRotationZ = this.rotation.z;
  48689. }
  48690. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  48691. // Computing target and final matrix
  48692. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  48693. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  48694. return this._viewMatrix;
  48695. };
  48696. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  48697. if (this.parent) {
  48698. var parentWorldMatrix = this.parent.getWorldMatrix();
  48699. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  48700. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  48701. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  48702. this._markSyncedWithParent();
  48703. }
  48704. else {
  48705. this._globalPosition.copyFrom(position);
  48706. this._globalCurrentTarget.copyFrom(target);
  48707. this._globalCurrentUpVector.copyFrom(up);
  48708. }
  48709. if (this.getScene().useRightHandedSystem) {
  48710. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  48711. }
  48712. else {
  48713. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  48714. }
  48715. };
  48716. /**
  48717. * @hidden
  48718. */
  48719. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48720. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  48721. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  48722. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  48723. if (!this.rotationQuaternion) {
  48724. this.rotationQuaternion = new BABYLON.Quaternion();
  48725. }
  48726. rigCamera._cameraRigParams = {};
  48727. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  48728. }
  48729. return rigCamera;
  48730. }
  48731. return null;
  48732. };
  48733. /**
  48734. * @hidden
  48735. */
  48736. TargetCamera.prototype._updateRigCameras = function () {
  48737. var camLeft = this._rigCameras[0];
  48738. var camRight = this._rigCameras[1];
  48739. switch (this.cameraRigMode) {
  48740. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48741. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48742. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48743. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48744. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  48745. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  48746. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  48747. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  48748. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  48749. camLeft.setTarget(this.getTarget());
  48750. camRight.setTarget(this.getTarget());
  48751. break;
  48752. case BABYLON.Camera.RIG_MODE_VR:
  48753. if (camLeft.rotationQuaternion) {
  48754. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48755. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48756. }
  48757. else {
  48758. camLeft.rotation.copyFrom(this.rotation);
  48759. camRight.rotation.copyFrom(this.rotation);
  48760. }
  48761. camLeft.position.copyFrom(this.position);
  48762. camRight.position.copyFrom(this.position);
  48763. break;
  48764. }
  48765. _super.prototype._updateRigCameras.call(this);
  48766. };
  48767. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  48768. if (!this._rigCamTransformMatrix) {
  48769. this._rigCamTransformMatrix = new BABYLON.Matrix();
  48770. }
  48771. var target = this.getTarget();
  48772. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  48773. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  48774. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  48775. };
  48776. /**
  48777. * Gets the current object class name.
  48778. * @return the class name
  48779. */
  48780. TargetCamera.prototype.getClassName = function () {
  48781. return "TargetCamera";
  48782. };
  48783. __decorate([
  48784. BABYLON.serializeAsVector3()
  48785. ], TargetCamera.prototype, "rotation", void 0);
  48786. __decorate([
  48787. BABYLON.serialize()
  48788. ], TargetCamera.prototype, "speed", void 0);
  48789. __decorate([
  48790. BABYLON.serializeAsMeshReference("lockedTargetId")
  48791. ], TargetCamera.prototype, "lockedTarget", void 0);
  48792. return TargetCamera;
  48793. }(BABYLON.Camera));
  48794. BABYLON.TargetCamera = TargetCamera;
  48795. })(BABYLON || (BABYLON = {}));
  48796. //# sourceMappingURL=targetCamera.js.map
  48797. var BABYLON;
  48798. (function (BABYLON) {
  48799. /**
  48800. * Manage the mouse inputs to control the movement of a free camera.
  48801. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48802. */
  48803. var FreeCameraMouseInput = /** @class */ (function () {
  48804. /**
  48805. * Manage the mouse inputs to control the movement of a free camera.
  48806. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48807. * @param touchEnabled Defines if touch is enabled or not
  48808. */
  48809. function FreeCameraMouseInput(
  48810. /**
  48811. * Define if touch is enabled in the mouse input
  48812. */
  48813. touchEnabled) {
  48814. if (touchEnabled === void 0) { touchEnabled = true; }
  48815. this.touchEnabled = touchEnabled;
  48816. /**
  48817. * Defines the buttons associated with the input to handle camera move.
  48818. */
  48819. this.buttons = [0, 1, 2];
  48820. /**
  48821. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  48822. */
  48823. this.angularSensibility = 2000.0;
  48824. this.previousPosition = null;
  48825. }
  48826. /**
  48827. * Attach the input controls to a specific dom element to get the input from.
  48828. * @param element Defines the element the controls should be listened from
  48829. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48830. */
  48831. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  48832. var _this = this;
  48833. var engine = this.camera.getEngine();
  48834. if (!this._pointerInput) {
  48835. this._pointerInput = function (p, s) {
  48836. var evt = p.event;
  48837. if (engine.isInVRExclusivePointerMode) {
  48838. return;
  48839. }
  48840. if (!_this.touchEnabled && evt.pointerType === "touch") {
  48841. return;
  48842. }
  48843. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48844. return;
  48845. }
  48846. var srcElement = (evt.srcElement || evt.target);
  48847. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48848. try {
  48849. srcElement.setPointerCapture(evt.pointerId);
  48850. }
  48851. catch (e) {
  48852. //Nothing to do with the error. Execution will continue.
  48853. }
  48854. _this.previousPosition = {
  48855. x: evt.clientX,
  48856. y: evt.clientY
  48857. };
  48858. if (!noPreventDefault) {
  48859. evt.preventDefault();
  48860. element.focus();
  48861. }
  48862. }
  48863. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48864. try {
  48865. srcElement.releasePointerCapture(evt.pointerId);
  48866. }
  48867. catch (e) {
  48868. //Nothing to do with the error.
  48869. }
  48870. _this.previousPosition = null;
  48871. if (!noPreventDefault) {
  48872. evt.preventDefault();
  48873. }
  48874. }
  48875. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48876. if (!_this.previousPosition || engine.isPointerLock) {
  48877. return;
  48878. }
  48879. var offsetX = evt.clientX - _this.previousPosition.x;
  48880. if (_this.camera.getScene().useRightHandedSystem) {
  48881. offsetX *= -1;
  48882. }
  48883. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
  48884. offsetX *= -1;
  48885. }
  48886. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  48887. var offsetY = evt.clientY - _this.previousPosition.y;
  48888. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  48889. _this.previousPosition = {
  48890. x: evt.clientX,
  48891. y: evt.clientY
  48892. };
  48893. if (!noPreventDefault) {
  48894. evt.preventDefault();
  48895. }
  48896. }
  48897. };
  48898. }
  48899. this._onMouseMove = function (evt) {
  48900. if (!engine.isPointerLock) {
  48901. return;
  48902. }
  48903. if (engine.isInVRExclusivePointerMode) {
  48904. return;
  48905. }
  48906. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48907. if (_this.camera.getScene().useRightHandedSystem) {
  48908. offsetX *= -1;
  48909. }
  48910. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
  48911. offsetX *= -1;
  48912. }
  48913. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  48914. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48915. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  48916. _this.previousPosition = null;
  48917. if (!noPreventDefault) {
  48918. evt.preventDefault();
  48919. }
  48920. };
  48921. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  48922. element.addEventListener("mousemove", this._onMouseMove, false);
  48923. };
  48924. /**
  48925. * Detach the current controls from the specified dom element.
  48926. * @param element Defines the element to stop listening the inputs from
  48927. */
  48928. FreeCameraMouseInput.prototype.detachControl = function (element) {
  48929. if (this._observer && element) {
  48930. this.camera.getScene().onPointerObservable.remove(this._observer);
  48931. if (this._onMouseMove) {
  48932. element.removeEventListener("mousemove", this._onMouseMove);
  48933. }
  48934. this._observer = null;
  48935. this._onMouseMove = null;
  48936. this.previousPosition = null;
  48937. }
  48938. };
  48939. /**
  48940. * Gets the class name of the current intput.
  48941. * @returns the class name
  48942. */
  48943. FreeCameraMouseInput.prototype.getClassName = function () {
  48944. return "FreeCameraMouseInput";
  48945. };
  48946. /**
  48947. * Get the friendly name associated with the input class.
  48948. * @returns the input friendly name
  48949. */
  48950. FreeCameraMouseInput.prototype.getSimpleName = function () {
  48951. return "mouse";
  48952. };
  48953. __decorate([
  48954. BABYLON.serialize()
  48955. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  48956. __decorate([
  48957. BABYLON.serialize()
  48958. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  48959. return FreeCameraMouseInput;
  48960. }());
  48961. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  48962. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  48963. })(BABYLON || (BABYLON = {}));
  48964. //# sourceMappingURL=freeCameraMouseInput.js.map
  48965. var BABYLON;
  48966. (function (BABYLON) {
  48967. /**
  48968. * Manage the keyboard inputs to control the movement of a free camera.
  48969. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48970. */
  48971. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  48972. function FreeCameraKeyboardMoveInput() {
  48973. /**
  48974. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48975. */
  48976. this.keysUp = [38];
  48977. /**
  48978. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48979. */
  48980. this.keysDown = [40];
  48981. /**
  48982. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48983. */
  48984. this.keysLeft = [37];
  48985. /**
  48986. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48987. */
  48988. this.keysRight = [39];
  48989. this._keys = new Array();
  48990. }
  48991. /**
  48992. * Attach the input controls to a specific dom element to get the input from.
  48993. * @param element Defines the element the controls should be listened from
  48994. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48995. */
  48996. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48997. var _this = this;
  48998. if (this._onCanvasBlurObserver) {
  48999. return;
  49000. }
  49001. this._scene = this.camera.getScene();
  49002. this._engine = this._scene.getEngine();
  49003. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  49004. _this._keys = [];
  49005. });
  49006. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  49007. var evt = info.event;
  49008. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  49009. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  49010. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  49011. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  49012. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  49013. var index = _this._keys.indexOf(evt.keyCode);
  49014. if (index === -1) {
  49015. _this._keys.push(evt.keyCode);
  49016. }
  49017. if (!noPreventDefault) {
  49018. evt.preventDefault();
  49019. }
  49020. }
  49021. }
  49022. else {
  49023. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  49024. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  49025. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  49026. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  49027. var index = _this._keys.indexOf(evt.keyCode);
  49028. if (index >= 0) {
  49029. _this._keys.splice(index, 1);
  49030. }
  49031. if (!noPreventDefault) {
  49032. evt.preventDefault();
  49033. }
  49034. }
  49035. }
  49036. });
  49037. };
  49038. /**
  49039. * Detach the current controls from the specified dom element.
  49040. * @param element Defines the element to stop listening the inputs from
  49041. */
  49042. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  49043. if (this._scene) {
  49044. if (this._onKeyboardObserver) {
  49045. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  49046. }
  49047. if (this._onCanvasBlurObserver) {
  49048. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  49049. }
  49050. this._onKeyboardObserver = null;
  49051. this._onCanvasBlurObserver = null;
  49052. }
  49053. this._keys = [];
  49054. };
  49055. /**
  49056. * Update the current camera state depending on the inputs that have been used this frame.
  49057. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  49058. */
  49059. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  49060. if (this._onKeyboardObserver) {
  49061. var camera = this.camera;
  49062. // Keyboard
  49063. for (var index = 0; index < this._keys.length; index++) {
  49064. var keyCode = this._keys[index];
  49065. var speed = camera._computeLocalCameraSpeed();
  49066. if (this.keysLeft.indexOf(keyCode) !== -1) {
  49067. camera._localDirection.copyFromFloats(-speed, 0, 0);
  49068. }
  49069. else if (this.keysUp.indexOf(keyCode) !== -1) {
  49070. camera._localDirection.copyFromFloats(0, 0, speed);
  49071. }
  49072. else if (this.keysRight.indexOf(keyCode) !== -1) {
  49073. camera._localDirection.copyFromFloats(speed, 0, 0);
  49074. }
  49075. else if (this.keysDown.indexOf(keyCode) !== -1) {
  49076. camera._localDirection.copyFromFloats(0, 0, -speed);
  49077. }
  49078. if (camera.getScene().useRightHandedSystem) {
  49079. camera._localDirection.z *= -1;
  49080. }
  49081. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  49082. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  49083. camera.cameraDirection.addInPlace(camera._transformedDirection);
  49084. }
  49085. }
  49086. };
  49087. /**
  49088. * Gets the class name of the current intput.
  49089. * @returns the class name
  49090. */
  49091. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  49092. return "FreeCameraKeyboardMoveInput";
  49093. };
  49094. /** @hidden */
  49095. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  49096. this._keys = [];
  49097. };
  49098. /**
  49099. * Get the friendly name associated with the input class.
  49100. * @returns the input friendly name
  49101. */
  49102. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  49103. return "keyboard";
  49104. };
  49105. __decorate([
  49106. BABYLON.serialize()
  49107. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  49108. __decorate([
  49109. BABYLON.serialize()
  49110. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  49111. __decorate([
  49112. BABYLON.serialize()
  49113. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  49114. __decorate([
  49115. BABYLON.serialize()
  49116. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  49117. return FreeCameraKeyboardMoveInput;
  49118. }());
  49119. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  49120. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  49121. })(BABYLON || (BABYLON = {}));
  49122. //# sourceMappingURL=freeCameraKeyboardMoveInput.js.map
  49123. var BABYLON;
  49124. (function (BABYLON) {
  49125. /**
  49126. * Default Inputs manager for the FreeCamera.
  49127. * It groups all the default supported inputs for ease of use.
  49128. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49129. */
  49130. var FreeCameraInputsManager = /** @class */ (function (_super) {
  49131. __extends(FreeCameraInputsManager, _super);
  49132. /**
  49133. * Instantiates a new FreeCameraInputsManager.
  49134. * @param camera Defines the camera the inputs belong to
  49135. */
  49136. function FreeCameraInputsManager(camera) {
  49137. return _super.call(this, camera) || this;
  49138. }
  49139. /**
  49140. * Add keyboard input support to the input manager.
  49141. * @returns the current input manager
  49142. */
  49143. FreeCameraInputsManager.prototype.addKeyboard = function () {
  49144. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  49145. return this;
  49146. };
  49147. /**
  49148. * Add mouse input support to the input manager.
  49149. * @param touchEnabled if the FreeCameraMouseInput should support touch (default: true)
  49150. * @returns the current input manager
  49151. */
  49152. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  49153. if (touchEnabled === void 0) { touchEnabled = true; }
  49154. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  49155. return this;
  49156. };
  49157. /**
  49158. * Add orientation input support to the input manager.
  49159. * @returns the current input manager
  49160. */
  49161. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  49162. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  49163. return this;
  49164. };
  49165. /**
  49166. * Add touch input support to the input manager.
  49167. * @returns the current input manager
  49168. */
  49169. FreeCameraInputsManager.prototype.addTouch = function () {
  49170. this.add(new BABYLON.FreeCameraTouchInput());
  49171. return this;
  49172. };
  49173. /**
  49174. * Add virtual joystick input support to the input manager.
  49175. * @returns the current input manager
  49176. */
  49177. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  49178. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  49179. return this;
  49180. };
  49181. return FreeCameraInputsManager;
  49182. }(BABYLON.CameraInputsManager));
  49183. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  49184. })(BABYLON || (BABYLON = {}));
  49185. //# sourceMappingURL=freeCameraInputsManager.js.map
  49186. var BABYLON;
  49187. (function (BABYLON) {
  49188. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  49189. // Forcing to use the Universal camera
  49190. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  49191. });
  49192. /**
  49193. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  49194. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  49195. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  49196. */
  49197. var FreeCamera = /** @class */ (function (_super) {
  49198. __extends(FreeCamera, _super);
  49199. /**
  49200. * Instantiates a Free Camera.
  49201. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  49202. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  49203. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  49204. * @param name Define the name of the camera in the scene
  49205. * @param position Define the start position of the camera in the scene
  49206. * @param scene Define the scene the camera belongs to
  49207. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  49208. */
  49209. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  49210. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  49211. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  49212. /**
  49213. * Define the collision ellipsoid of the camera.
  49214. * This is helpful to simulate a camera body like the player body around the camera
  49215. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  49216. */
  49217. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  49218. /**
  49219. * Define an offset for the position of the ellipsoid around the camera.
  49220. * This can be helpful to determine the center of the body near the gravity center of the body
  49221. * instead of its head.
  49222. */
  49223. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  49224. /**
  49225. * Enable or disable collisions of the camera with the rest of the scene objects.
  49226. */
  49227. _this.checkCollisions = false;
  49228. /**
  49229. * Enable or disable gravity on the camera.
  49230. */
  49231. _this.applyGravity = false;
  49232. _this._needMoveForGravity = false;
  49233. _this._oldPosition = BABYLON.Vector3.Zero();
  49234. _this._diffPosition = BABYLON.Vector3.Zero();
  49235. _this._newPosition = BABYLON.Vector3.Zero();
  49236. // Collisions
  49237. _this._collisionMask = -1;
  49238. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  49239. if (collidedMesh === void 0) { collidedMesh = null; }
  49240. //TODO move this to the collision coordinator!
  49241. if (_this.getScene().workerCollisions) {
  49242. newPosition.multiplyInPlace(_this._collider._radius);
  49243. }
  49244. var updatePosition = function (newPos) {
  49245. _this._newPosition.copyFrom(newPos);
  49246. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  49247. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  49248. _this.position.addInPlace(_this._diffPosition);
  49249. if (_this.onCollide && collidedMesh) {
  49250. _this.onCollide(collidedMesh);
  49251. }
  49252. }
  49253. };
  49254. updatePosition(newPosition);
  49255. };
  49256. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  49257. _this.inputs.addKeyboard().addMouse();
  49258. return _this;
  49259. }
  49260. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  49261. /**
  49262. * Gets the input sensibility for a mouse input. (default is 2000.0)
  49263. * Higher values reduce sensitivity.
  49264. */
  49265. get: function () {
  49266. var mouse = this.inputs.attached["mouse"];
  49267. if (mouse) {
  49268. return mouse.angularSensibility;
  49269. }
  49270. return 0;
  49271. },
  49272. /**
  49273. * Sets the input sensibility for a mouse input. (default is 2000.0)
  49274. * Higher values reduce sensitivity.
  49275. */
  49276. set: function (value) {
  49277. var mouse = this.inputs.attached["mouse"];
  49278. if (mouse) {
  49279. mouse.angularSensibility = value;
  49280. }
  49281. },
  49282. enumerable: true,
  49283. configurable: true
  49284. });
  49285. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  49286. /**
  49287. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  49288. */
  49289. get: function () {
  49290. var keyboard = this.inputs.attached["keyboard"];
  49291. if (keyboard) {
  49292. return keyboard.keysUp;
  49293. }
  49294. return [];
  49295. },
  49296. set: function (value) {
  49297. var keyboard = this.inputs.attached["keyboard"];
  49298. if (keyboard) {
  49299. keyboard.keysUp = value;
  49300. }
  49301. },
  49302. enumerable: true,
  49303. configurable: true
  49304. });
  49305. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  49306. /**
  49307. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  49308. */
  49309. get: function () {
  49310. var keyboard = this.inputs.attached["keyboard"];
  49311. if (keyboard) {
  49312. return keyboard.keysDown;
  49313. }
  49314. return [];
  49315. },
  49316. set: function (value) {
  49317. var keyboard = this.inputs.attached["keyboard"];
  49318. if (keyboard) {
  49319. keyboard.keysDown = value;
  49320. }
  49321. },
  49322. enumerable: true,
  49323. configurable: true
  49324. });
  49325. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  49326. /**
  49327. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  49328. */
  49329. get: function () {
  49330. var keyboard = this.inputs.attached["keyboard"];
  49331. if (keyboard) {
  49332. return keyboard.keysLeft;
  49333. }
  49334. return [];
  49335. },
  49336. set: function (value) {
  49337. var keyboard = this.inputs.attached["keyboard"];
  49338. if (keyboard) {
  49339. keyboard.keysLeft = value;
  49340. }
  49341. },
  49342. enumerable: true,
  49343. configurable: true
  49344. });
  49345. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  49346. /**
  49347. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  49348. */
  49349. get: function () {
  49350. var keyboard = this.inputs.attached["keyboard"];
  49351. if (keyboard) {
  49352. return keyboard.keysRight;
  49353. }
  49354. return [];
  49355. },
  49356. set: function (value) {
  49357. var keyboard = this.inputs.attached["keyboard"];
  49358. if (keyboard) {
  49359. keyboard.keysRight = value;
  49360. }
  49361. },
  49362. enumerable: true,
  49363. configurable: true
  49364. });
  49365. /**
  49366. * Attached controls to the current camera.
  49367. * @param element Defines the element the controls should be listened from
  49368. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49369. */
  49370. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  49371. this.inputs.attachElement(element, noPreventDefault);
  49372. };
  49373. /**
  49374. * Detach the current controls from the camera.
  49375. * The camera will stop reacting to inputs.
  49376. * @param element Defines the element to stop listening the inputs from
  49377. */
  49378. FreeCamera.prototype.detachControl = function (element) {
  49379. this.inputs.detachElement(element);
  49380. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  49381. this.cameraRotation = new BABYLON.Vector2(0, 0);
  49382. };
  49383. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  49384. /**
  49385. * Define a collision mask to limit the list of object the camera can collide with
  49386. */
  49387. get: function () {
  49388. return this._collisionMask;
  49389. },
  49390. set: function (mask) {
  49391. this._collisionMask = !isNaN(mask) ? mask : -1;
  49392. },
  49393. enumerable: true,
  49394. configurable: true
  49395. });
  49396. /** @hidden */
  49397. FreeCamera.prototype._collideWithWorld = function (displacement) {
  49398. var globalPosition;
  49399. if (this.parent) {
  49400. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  49401. }
  49402. else {
  49403. globalPosition = this.position;
  49404. }
  49405. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  49406. this._oldPosition.addInPlace(this.ellipsoidOffset);
  49407. if (!this._collider) {
  49408. this._collider = new BABYLON.Collider();
  49409. }
  49410. this._collider._radius = this.ellipsoid;
  49411. this._collider.collisionMask = this._collisionMask;
  49412. //no need for clone, as long as gravity is not on.
  49413. var actualDisplacement = displacement;
  49414. //add gravity to the direction to prevent the dual-collision checking
  49415. if (this.applyGravity) {
  49416. //this prevents mending with cameraDirection, a global variable of the free camera class.
  49417. actualDisplacement = displacement.add(this.getScene().gravity);
  49418. }
  49419. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49420. };
  49421. /** @hidden */
  49422. FreeCamera.prototype._checkInputs = function () {
  49423. if (!this._localDirection) {
  49424. this._localDirection = BABYLON.Vector3.Zero();
  49425. this._transformedDirection = BABYLON.Vector3.Zero();
  49426. }
  49427. this.inputs.checkInputs();
  49428. _super.prototype._checkInputs.call(this);
  49429. };
  49430. /** @hidden */
  49431. FreeCamera.prototype._decideIfNeedsToMove = function () {
  49432. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  49433. };
  49434. /** @hidden */
  49435. FreeCamera.prototype._updatePosition = function () {
  49436. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  49437. this._collideWithWorld(this.cameraDirection);
  49438. }
  49439. else {
  49440. _super.prototype._updatePosition.call(this);
  49441. }
  49442. };
  49443. /**
  49444. * Destroy the camera and release the current resources hold by it.
  49445. */
  49446. FreeCamera.prototype.dispose = function () {
  49447. this.inputs.clear();
  49448. _super.prototype.dispose.call(this);
  49449. };
  49450. /**
  49451. * Gets the current object class name.
  49452. * @return the class name
  49453. */
  49454. FreeCamera.prototype.getClassName = function () {
  49455. return "FreeCamera";
  49456. };
  49457. __decorate([
  49458. BABYLON.serializeAsVector3()
  49459. ], FreeCamera.prototype, "ellipsoid", void 0);
  49460. __decorate([
  49461. BABYLON.serializeAsVector3()
  49462. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  49463. __decorate([
  49464. BABYLON.serialize()
  49465. ], FreeCamera.prototype, "checkCollisions", void 0);
  49466. __decorate([
  49467. BABYLON.serialize()
  49468. ], FreeCamera.prototype, "applyGravity", void 0);
  49469. return FreeCamera;
  49470. }(BABYLON.TargetCamera));
  49471. BABYLON.FreeCamera = FreeCamera;
  49472. })(BABYLON || (BABYLON = {}));
  49473. //# sourceMappingURL=freeCamera.js.map
  49474. var BABYLON;
  49475. (function (BABYLON) {
  49476. /**
  49477. * Listen to mouse events to control the camera.
  49478. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49479. */
  49480. var FlyCameraMouseInput = /** @class */ (function () {
  49481. /**
  49482. * Listen to mouse events to control the camera.
  49483. * @param touchEnabled Define if touch is enabled. (Default is true.)
  49484. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49485. */
  49486. function FlyCameraMouseInput(touchEnabled) {
  49487. if (touchEnabled === void 0) { touchEnabled = true; }
  49488. /**
  49489. * Defines the buttons associated with the input to handle camera rotation.
  49490. */
  49491. this.buttons = [0, 1, 2];
  49492. /**
  49493. * Assign buttons for Yaw control.
  49494. */
  49495. this.buttonsYaw = [-1, 0, 1];
  49496. /**
  49497. * Assign buttons for Pitch control.
  49498. */
  49499. this.buttonsPitch = [-1, 0, 1];
  49500. /**
  49501. * Assign buttons for Roll control.
  49502. */
  49503. this.buttonsRoll = [2];
  49504. /**
  49505. * Detect if any button is being pressed while mouse is moved.
  49506. * -1 = Mouse locked.
  49507. * 0 = Left button.
  49508. * 1 = Middle Button.
  49509. * 2 = Right Button.
  49510. */
  49511. this.activeButton = -1;
  49512. /**
  49513. * Defines the pointer's angular sensibility, to control the camera rotation speed.
  49514. * Higher values reduce its sensitivity.
  49515. */
  49516. this.angularSensibility = 1000.0;
  49517. this.previousPosition = null;
  49518. }
  49519. /**
  49520. * Attach the mouse control to the HTML DOM element.
  49521. * @param element Defines the element that listens to the input events.
  49522. * @param noPreventDefault Defines whether events caught by the controls should call preventdefault().
  49523. */
  49524. FlyCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  49525. var _this = this;
  49526. this.element = element;
  49527. this.noPreventDefault = noPreventDefault;
  49528. this._observer = this.camera.getScene().onPointerObservable.add(function (p, s) {
  49529. _this._pointerInput(p, s);
  49530. }, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  49531. // Correct Roll by rate, if enabled.
  49532. this._rollObserver = this.camera.getScene().onBeforeRenderObservable.add(function () {
  49533. if (_this.camera.rollCorrect) {
  49534. _this.camera.restoreRoll(_this.camera.rollCorrect);
  49535. }
  49536. });
  49537. // Helper function to keep 'this'.
  49538. this._mousemoveCallback = function (e) {
  49539. _this._onMouseMove(e);
  49540. };
  49541. element.addEventListener("mousemove", this._mousemoveCallback, false);
  49542. };
  49543. /**
  49544. * Detach the current controls from the specified dom element.
  49545. * @param element Defines the element to stop listening the inputs from
  49546. */
  49547. FlyCameraMouseInput.prototype.detachControl = function (element) {
  49548. if (this._observer && element) {
  49549. this.camera.getScene().onPointerObservable.remove(this._observer);
  49550. this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver);
  49551. if (this._mousemoveCallback) {
  49552. element.removeEventListener("mousemove", this._mousemoveCallback);
  49553. }
  49554. this._observer = null;
  49555. this._rollObserver = null;
  49556. this.previousPosition = null;
  49557. this.noPreventDefault = undefined;
  49558. }
  49559. };
  49560. /**
  49561. * Gets the class name of the current input.
  49562. * @returns the class name.
  49563. */
  49564. FlyCameraMouseInput.prototype.getClassName = function () {
  49565. return "FlyCameraMouseInput";
  49566. };
  49567. /**
  49568. * Get the friendly name associated with the input class.
  49569. * @returns the input's friendly name.
  49570. */
  49571. FlyCameraMouseInput.prototype.getSimpleName = function () {
  49572. return "mouse";
  49573. };
  49574. // Track mouse movement, when the pointer is not locked.
  49575. FlyCameraMouseInput.prototype._pointerInput = function (p, s) {
  49576. var e = p.event;
  49577. var camera = this.camera;
  49578. var engine = camera.getEngine();
  49579. if (engine.isInVRExclusivePointerMode) {
  49580. return;
  49581. }
  49582. if (!this.touchEnabled && e.pointerType === "touch") {
  49583. return;
  49584. }
  49585. // Mouse is moved but an unknown mouse button is pressed.
  49586. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && this.buttons.indexOf(e.button) === -1) {
  49587. return;
  49588. }
  49589. var srcElement = (e.srcElement || e.target);
  49590. // Mouse down.
  49591. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  49592. try {
  49593. srcElement.setPointerCapture(e.pointerId);
  49594. }
  49595. catch (e) {
  49596. // Nothing to do with the error. Execution continues.
  49597. }
  49598. this.previousPosition = {
  49599. x: e.clientX,
  49600. y: e.clientY
  49601. };
  49602. this.activeButton = e.button;
  49603. if (!this.noPreventDefault) {
  49604. e.preventDefault();
  49605. this.element.focus();
  49606. }
  49607. }
  49608. else
  49609. // Mouse up.
  49610. if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  49611. try {
  49612. srcElement.releasePointerCapture(e.pointerId);
  49613. }
  49614. catch (e) {
  49615. // Nothing to do with the error. Execution continues.
  49616. }
  49617. this.activeButton = -1;
  49618. this.previousPosition = null;
  49619. if (!this.noPreventDefault) {
  49620. e.preventDefault();
  49621. }
  49622. }
  49623. else
  49624. // Mouse move.
  49625. if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  49626. if (!this.previousPosition || engine.isPointerLock) {
  49627. return;
  49628. }
  49629. var offsetX = e.clientX - this.previousPosition.x;
  49630. var offsetY = e.clientY - this.previousPosition.y;
  49631. this.rotateCamera(offsetX, offsetY);
  49632. this.previousPosition = {
  49633. x: e.clientX,
  49634. y: e.clientY
  49635. };
  49636. if (!this.noPreventDefault) {
  49637. e.preventDefault();
  49638. }
  49639. }
  49640. };
  49641. // Track mouse movement, when pointer is locked.
  49642. FlyCameraMouseInput.prototype._onMouseMove = function (e) {
  49643. var camera = this.camera;
  49644. var engine = camera.getEngine();
  49645. if (!engine.isPointerLock || engine.isInVRExclusivePointerMode) {
  49646. return;
  49647. }
  49648. var offsetX = e.movementX || e.mozMovementX || e.webkitMovementX || e.msMovementX || 0;
  49649. var offsetY = e.movementY || e.mozMovementY || e.webkitMovementY || e.msMovementY || 0;
  49650. this.rotateCamera(offsetX, offsetY);
  49651. this.previousPosition = null;
  49652. if (!this.noPreventDefault) {
  49653. e.preventDefault();
  49654. }
  49655. };
  49656. /**
  49657. * Rotate camera by mouse offset.
  49658. */
  49659. FlyCameraMouseInput.prototype.rotateCamera = function (offsetX, offsetY) {
  49660. var _this = this;
  49661. var camera = this.camera;
  49662. var scene = this.camera.getScene();
  49663. if (scene.useRightHandedSystem) {
  49664. offsetX *= -1;
  49665. }
  49666. if (camera.parent && camera.parent._getWorldMatrixDeterminant() < 0) {
  49667. offsetX *= -1;
  49668. }
  49669. var x = offsetX / this.angularSensibility;
  49670. var y = offsetY / this.angularSensibility;
  49671. // Initialize to current rotation.
  49672. var currentRotation = BABYLON.Quaternion.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, camera.rotation.z);
  49673. var rotationChange;
  49674. // Pitch.
  49675. if (this.buttonsPitch.some(function (v) { return v === _this.activeButton; })) {
  49676. // Apply change in Radians to vector Angle.
  49677. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.X, y);
  49678. // Apply Pitch to quaternion.
  49679. currentRotation.multiplyInPlace(rotationChange);
  49680. }
  49681. // Yaw.
  49682. if (this.buttonsYaw.some(function (v) { return v === _this.activeButton; })) {
  49683. // Apply change in Radians to vector Angle.
  49684. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.Y, x);
  49685. // Apply Yaw to quaternion.
  49686. currentRotation.multiplyInPlace(rotationChange);
  49687. // Add Roll, if banked turning is enabled, within Roll limit.
  49688. var limit = (camera.bankedTurnLimit) + camera._trackRoll; // Defaults to 90° plus manual roll.
  49689. if (camera.bankedTurn && -limit < camera.rotation.z && camera.rotation.z < limit) {
  49690. var bankingDelta = camera.bankedTurnMultiplier * -x;
  49691. // Apply change in Radians to vector Angle.
  49692. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.Z, bankingDelta);
  49693. // Apply Yaw to quaternion.
  49694. currentRotation.multiplyInPlace(rotationChange);
  49695. }
  49696. }
  49697. // Roll.
  49698. if (this.buttonsRoll.some(function (v) { return v === _this.activeButton; })) {
  49699. // Apply change in Radians to vector Angle.
  49700. rotationChange = BABYLON.Quaternion.RotationAxis(BABYLON.Axis.Z, -x);
  49701. // Track Rolling.
  49702. camera._trackRoll -= x;
  49703. // Apply Pitch to quaternion.
  49704. currentRotation.multiplyInPlace(rotationChange);
  49705. }
  49706. // Apply rotationQuaternion to Euler camera.rotation.
  49707. currentRotation.toEulerAnglesToRef(camera.rotation);
  49708. };
  49709. __decorate([
  49710. BABYLON.serialize()
  49711. ], FlyCameraMouseInput.prototype, "buttons", void 0);
  49712. __decorate([
  49713. BABYLON.serialize()
  49714. ], FlyCameraMouseInput.prototype, "angularSensibility", void 0);
  49715. return FlyCameraMouseInput;
  49716. }());
  49717. BABYLON.FlyCameraMouseInput = FlyCameraMouseInput;
  49718. BABYLON.CameraInputTypes["FlyCameraMouseInput"] = FlyCameraMouseInput;
  49719. })(BABYLON || (BABYLON = {}));
  49720. //# sourceMappingURL=flyCameraMouseInput.js.map
  49721. var BABYLON;
  49722. (function (BABYLON) {
  49723. /**
  49724. * Listen to keyboard events to control the camera.
  49725. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49726. */
  49727. var FlyCameraKeyboardInput = /** @class */ (function () {
  49728. function FlyCameraKeyboardInput() {
  49729. /**
  49730. * The list of keyboard keys used to control the forward move of the camera.
  49731. */
  49732. this.keysForward = [87];
  49733. /**
  49734. * The list of keyboard keys used to control the backward move of the camera.
  49735. */
  49736. this.keysBackward = [83];
  49737. /**
  49738. * The list of keyboard keys used to control the forward move of the camera.
  49739. */
  49740. this.keysUp = [69];
  49741. /**
  49742. * The list of keyboard keys used to control the backward move of the camera.
  49743. */
  49744. this.keysDown = [81];
  49745. /**
  49746. * The list of keyboard keys used to control the right strafe move of the camera.
  49747. */
  49748. this.keysRight = [68];
  49749. /**
  49750. * The list of keyboard keys used to control the left strafe move of the camera.
  49751. */
  49752. this.keysLeft = [65];
  49753. this._keys = new Array();
  49754. }
  49755. /**
  49756. * Attach the input controls to a specific dom element to get the input from.
  49757. * @param element Defines the element the controls should be listened from
  49758. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49759. */
  49760. FlyCameraKeyboardInput.prototype.attachControl = function (element, noPreventDefault) {
  49761. var _this = this;
  49762. if (this._onCanvasBlurObserver) {
  49763. return;
  49764. }
  49765. this._scene = this.camera.getScene();
  49766. this._engine = this._scene.getEngine();
  49767. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  49768. _this._keys = [];
  49769. });
  49770. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  49771. var evt = info.event;
  49772. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  49773. if (_this.keysForward.indexOf(evt.keyCode) !== -1 ||
  49774. _this.keysBackward.indexOf(evt.keyCode) !== -1 ||
  49775. _this.keysUp.indexOf(evt.keyCode) !== -1 ||
  49776. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  49777. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  49778. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  49779. var index = _this._keys.indexOf(evt.keyCode);
  49780. if (index === -1) {
  49781. _this._keys.push(evt.keyCode);
  49782. }
  49783. if (!noPreventDefault) {
  49784. evt.preventDefault();
  49785. }
  49786. }
  49787. }
  49788. else {
  49789. if (_this.keysForward.indexOf(evt.keyCode) !== -1 ||
  49790. _this.keysBackward.indexOf(evt.keyCode) !== -1 ||
  49791. _this.keysUp.indexOf(evt.keyCode) !== -1 ||
  49792. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  49793. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  49794. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  49795. var index = _this._keys.indexOf(evt.keyCode);
  49796. if (index >= 0) {
  49797. _this._keys.splice(index, 1);
  49798. }
  49799. if (!noPreventDefault) {
  49800. evt.preventDefault();
  49801. }
  49802. }
  49803. }
  49804. });
  49805. };
  49806. /**
  49807. * Detach the current controls from the specified dom element.
  49808. * @param element Defines the element to stop listening the inputs from
  49809. */
  49810. FlyCameraKeyboardInput.prototype.detachControl = function (element) {
  49811. if (this._scene) {
  49812. if (this._onKeyboardObserver) {
  49813. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  49814. }
  49815. if (this._onCanvasBlurObserver) {
  49816. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  49817. }
  49818. this._onKeyboardObserver = null;
  49819. this._onCanvasBlurObserver = null;
  49820. }
  49821. this._keys = [];
  49822. };
  49823. /**
  49824. * Gets the class name of the current intput.
  49825. * @returns the class name
  49826. */
  49827. FlyCameraKeyboardInput.prototype.getClassName = function () {
  49828. return "FlyCameraKeyboardInput";
  49829. };
  49830. /** @hidden */
  49831. FlyCameraKeyboardInput.prototype._onLostFocus = function (e) {
  49832. this._keys = [];
  49833. };
  49834. /**
  49835. * Get the friendly name associated with the input class.
  49836. * @returns the input friendly name
  49837. */
  49838. FlyCameraKeyboardInput.prototype.getSimpleName = function () {
  49839. return "keyboard";
  49840. };
  49841. /**
  49842. * Update the current camera state depending on the inputs that have been used this frame.
  49843. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  49844. */
  49845. FlyCameraKeyboardInput.prototype.checkInputs = function () {
  49846. if (this._onKeyboardObserver) {
  49847. var camera = this.camera;
  49848. // Keyboard
  49849. for (var index = 0; index < this._keys.length; index++) {
  49850. var keyCode = this._keys[index];
  49851. var speed = camera._computeLocalCameraSpeed();
  49852. if (this.keysForward.indexOf(keyCode) !== -1) {
  49853. camera._localDirection.copyFromFloats(0, 0, speed);
  49854. }
  49855. else if (this.keysBackward.indexOf(keyCode) !== -1) {
  49856. camera._localDirection.copyFromFloats(0, 0, -speed);
  49857. }
  49858. else if (this.keysUp.indexOf(keyCode) !== -1) {
  49859. camera._localDirection.copyFromFloats(0, speed, 0);
  49860. }
  49861. else if (this.keysDown.indexOf(keyCode) !== -1) {
  49862. camera._localDirection.copyFromFloats(0, -speed, 0);
  49863. }
  49864. else if (this.keysRight.indexOf(keyCode) !== -1) {
  49865. camera._localDirection.copyFromFloats(speed, 0, 0);
  49866. }
  49867. else if (this.keysLeft.indexOf(keyCode) !== -1) {
  49868. camera._localDirection.copyFromFloats(-speed, 0, 0);
  49869. }
  49870. if (camera.getScene().useRightHandedSystem) {
  49871. camera._localDirection.z *= -1;
  49872. }
  49873. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  49874. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  49875. camera.cameraDirection.addInPlace(camera._transformedDirection);
  49876. }
  49877. }
  49878. };
  49879. __decorate([
  49880. BABYLON.serialize()
  49881. ], FlyCameraKeyboardInput.prototype, "keysForward", void 0);
  49882. __decorate([
  49883. BABYLON.serialize()
  49884. ], FlyCameraKeyboardInput.prototype, "keysBackward", void 0);
  49885. __decorate([
  49886. BABYLON.serialize()
  49887. ], FlyCameraKeyboardInput.prototype, "keysUp", void 0);
  49888. __decorate([
  49889. BABYLON.serialize()
  49890. ], FlyCameraKeyboardInput.prototype, "keysDown", void 0);
  49891. __decorate([
  49892. BABYLON.serialize()
  49893. ], FlyCameraKeyboardInput.prototype, "keysRight", void 0);
  49894. __decorate([
  49895. BABYLON.serialize()
  49896. ], FlyCameraKeyboardInput.prototype, "keysLeft", void 0);
  49897. return FlyCameraKeyboardInput;
  49898. }());
  49899. BABYLON.FlyCameraKeyboardInput = FlyCameraKeyboardInput;
  49900. BABYLON.CameraInputTypes["FlyCameraKeyboardInput"] = FlyCameraKeyboardInput;
  49901. })(BABYLON || (BABYLON = {}));
  49902. //# sourceMappingURL=flyCameraKeyboardInput.js.map
  49903. var BABYLON;
  49904. (function (BABYLON) {
  49905. /**
  49906. * Default Inputs manager for the FlyCamera.
  49907. * It groups all the default supported inputs for ease of use.
  49908. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49909. */
  49910. var FlyCameraInputsManager = /** @class */ (function (_super) {
  49911. __extends(FlyCameraInputsManager, _super);
  49912. /**
  49913. * Instantiates a new FlyCameraInputsManager.
  49914. * @param camera Defines the camera the inputs belong to.
  49915. */
  49916. function FlyCameraInputsManager(camera) {
  49917. return _super.call(this, camera) || this;
  49918. }
  49919. /**
  49920. * Add keyboard input support to the input manager.
  49921. * @returns the new FlyCameraKeyboardMoveInput().
  49922. */
  49923. FlyCameraInputsManager.prototype.addKeyboard = function () {
  49924. this.add(new BABYLON.FlyCameraKeyboardInput());
  49925. return this;
  49926. };
  49927. /**
  49928. * Add mouse input support to the input manager.
  49929. * @param touchEnabled Enable touch screen support.
  49930. * @returns the new FlyCameraMouseInput().
  49931. */
  49932. FlyCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  49933. if (touchEnabled === void 0) { touchEnabled = true; }
  49934. this.add(new BABYLON.FlyCameraMouseInput(touchEnabled));
  49935. return this;
  49936. };
  49937. return FlyCameraInputsManager;
  49938. }(BABYLON.CameraInputsManager));
  49939. BABYLON.FlyCameraInputsManager = FlyCameraInputsManager;
  49940. })(BABYLON || (BABYLON = {}));
  49941. //# sourceMappingURL=flyCameraInputsManager.js.map
  49942. var BABYLON;
  49943. (function (BABYLON) {
  49944. /**
  49945. * This is a flying camera, designed for 3D movement and rotation in all directions,
  49946. * such as in a 3D Space Shooter or a Flight Simulator.
  49947. */
  49948. var FlyCamera = /** @class */ (function (_super) {
  49949. __extends(FlyCamera, _super);
  49950. /**
  49951. * Instantiates a FlyCamera.
  49952. * This is a flying camera, designed for 3D movement and rotation in all directions,
  49953. * such as in a 3D Space Shooter or a Flight Simulator.
  49954. * @param name Define the name of the camera in the scene.
  49955. * @param position Define the starting position of the camera in the scene.
  49956. * @param scene Define the scene the camera belongs to.
  49957. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active, if no other camera has been defined as active.
  49958. */
  49959. function FlyCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  49960. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  49961. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  49962. /**
  49963. * Define the collision ellipsoid of the camera.
  49964. * This is helpful for simulating a camera body, like a player's body.
  49965. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  49966. */
  49967. _this.ellipsoid = new BABYLON.Vector3(1, 1, 1);
  49968. /**
  49969. * Define an offset for the position of the ellipsoid around the camera.
  49970. * This can be helpful if the camera is attached away from the player's body center,
  49971. * such as at its head.
  49972. */
  49973. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  49974. /**
  49975. * Enable or disable collisions of the camera with the rest of the scene objects.
  49976. */
  49977. _this.checkCollisions = false;
  49978. /**
  49979. * Enable or disable gravity on the camera.
  49980. */
  49981. _this.applyGravity = false;
  49982. /**
  49983. * Define the current direction the camera is moving to.
  49984. */
  49985. _this.cameraDirection = BABYLON.Vector3.Zero();
  49986. /**
  49987. * Track Roll to maintain the wanted Rolling when looking around.
  49988. */
  49989. _this._trackRoll = 0;
  49990. /**
  49991. * Slowly correct the Roll to its original value after a Pitch+Yaw rotation.
  49992. */
  49993. _this.rollCorrect = 100;
  49994. /**
  49995. * Mimic a banked turn, Rolling the camera when Yawing.
  49996. * It's recommended to use rollCorrect = 10 for faster banking correction.
  49997. */
  49998. _this.bankedTurn = false;
  49999. /**
  50000. * Limit in radians for how much Roll banking will add. (Default: 90°)
  50001. */
  50002. _this.bankedTurnLimit = Math.PI / 2;
  50003. /**
  50004. * Value of 0 disables the banked Roll.
  50005. * Value of 1 is equal to the Yaw angle in radians.
  50006. */
  50007. _this.bankedTurnMultiplier = 1;
  50008. _this._needMoveForGravity = false;
  50009. _this._oldPosition = BABYLON.Vector3.Zero();
  50010. _this._diffPosition = BABYLON.Vector3.Zero();
  50011. _this._newPosition = BABYLON.Vector3.Zero();
  50012. // Collisions.
  50013. _this._collisionMask = -1;
  50014. /** @hidden */
  50015. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  50016. if (collidedMesh === void 0) { collidedMesh = null; }
  50017. // TODO Move this to the collision coordinator!
  50018. if (_this.getScene().workerCollisions) {
  50019. newPosition.multiplyInPlace(_this._collider._radius);
  50020. }
  50021. var updatePosition = function (newPos) {
  50022. _this._newPosition.copyFrom(newPos);
  50023. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  50024. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  50025. _this.position.addInPlace(_this._diffPosition);
  50026. if (_this.onCollide && collidedMesh) {
  50027. _this.onCollide(collidedMesh);
  50028. }
  50029. }
  50030. };
  50031. updatePosition(newPosition);
  50032. };
  50033. _this.inputs = new BABYLON.FlyCameraInputsManager(_this);
  50034. _this.inputs.addKeyboard().addMouse();
  50035. return _this;
  50036. }
  50037. Object.defineProperty(FlyCamera.prototype, "angularSensibility", {
  50038. /**
  50039. * Gets the input sensibility for mouse input.
  50040. * Higher values reduce sensitivity.
  50041. */
  50042. get: function () {
  50043. var mouse = this.inputs.attached["mouse"];
  50044. if (mouse) {
  50045. return mouse.angularSensibility;
  50046. }
  50047. return 0;
  50048. },
  50049. /**
  50050. * Sets the input sensibility for a mouse input.
  50051. * Higher values reduce sensitivity.
  50052. */
  50053. set: function (value) {
  50054. var mouse = this.inputs.attached["mouse"];
  50055. if (mouse) {
  50056. mouse.angularSensibility = value;
  50057. }
  50058. },
  50059. enumerable: true,
  50060. configurable: true
  50061. });
  50062. Object.defineProperty(FlyCamera.prototype, "keysForward", {
  50063. /**
  50064. * Get the keys for camera movement forward.
  50065. */
  50066. get: function () {
  50067. var keyboard = this.inputs.attached["keyboard"];
  50068. if (keyboard) {
  50069. return keyboard.keysForward;
  50070. }
  50071. return [];
  50072. },
  50073. /**
  50074. * Set the keys for camera movement forward.
  50075. */
  50076. set: function (value) {
  50077. var keyboard = this.inputs.attached["keyboard"];
  50078. if (keyboard) {
  50079. keyboard.keysForward = value;
  50080. }
  50081. },
  50082. enumerable: true,
  50083. configurable: true
  50084. });
  50085. Object.defineProperty(FlyCamera.prototype, "keysBackward", {
  50086. /**
  50087. * Get the keys for camera movement backward.
  50088. */
  50089. get: function () {
  50090. var keyboard = this.inputs.attached["keyboard"];
  50091. if (keyboard) {
  50092. return keyboard.keysBackward;
  50093. }
  50094. return [];
  50095. },
  50096. set: function (value) {
  50097. var keyboard = this.inputs.attached["keyboard"];
  50098. if (keyboard) {
  50099. keyboard.keysBackward = value;
  50100. }
  50101. },
  50102. enumerable: true,
  50103. configurable: true
  50104. });
  50105. Object.defineProperty(FlyCamera.prototype, "keysUp", {
  50106. /**
  50107. * Get the keys for camera movement up.
  50108. */
  50109. get: function () {
  50110. var keyboard = this.inputs.attached["keyboard"];
  50111. if (keyboard) {
  50112. return keyboard.keysUp;
  50113. }
  50114. return [];
  50115. },
  50116. /**
  50117. * Set the keys for camera movement up.
  50118. */
  50119. set: function (value) {
  50120. var keyboard = this.inputs.attached["keyboard"];
  50121. if (keyboard) {
  50122. keyboard.keysUp = value;
  50123. }
  50124. },
  50125. enumerable: true,
  50126. configurable: true
  50127. });
  50128. Object.defineProperty(FlyCamera.prototype, "keysDown", {
  50129. /**
  50130. * Get the keys for camera movement down.
  50131. */
  50132. get: function () {
  50133. var keyboard = this.inputs.attached["keyboard"];
  50134. if (keyboard) {
  50135. return keyboard.keysDown;
  50136. }
  50137. return [];
  50138. },
  50139. /**
  50140. * Set the keys for camera movement down.
  50141. */
  50142. set: function (value) {
  50143. var keyboard = this.inputs.attached["keyboard"];
  50144. if (keyboard) {
  50145. keyboard.keysDown = value;
  50146. }
  50147. },
  50148. enumerable: true,
  50149. configurable: true
  50150. });
  50151. Object.defineProperty(FlyCamera.prototype, "keysLeft", {
  50152. /**
  50153. * Get the keys for camera movement left.
  50154. */
  50155. get: function () {
  50156. var keyboard = this.inputs.attached["keyboard"];
  50157. if (keyboard) {
  50158. return keyboard.keysLeft;
  50159. }
  50160. return [];
  50161. },
  50162. /**
  50163. * Set the keys for camera movement left.
  50164. */
  50165. set: function (value) {
  50166. var keyboard = this.inputs.attached["keyboard"];
  50167. if (keyboard) {
  50168. keyboard.keysLeft = value;
  50169. }
  50170. },
  50171. enumerable: true,
  50172. configurable: true
  50173. });
  50174. Object.defineProperty(FlyCamera.prototype, "keysRight", {
  50175. /**
  50176. * Set the keys for camera movement right.
  50177. */
  50178. get: function () {
  50179. var keyboard = this.inputs.attached["keyboard"];
  50180. if (keyboard) {
  50181. return keyboard.keysRight;
  50182. }
  50183. return [];
  50184. },
  50185. /**
  50186. * Set the keys for camera movement right.
  50187. */
  50188. set: function (value) {
  50189. var keyboard = this.inputs.attached["keyboard"];
  50190. if (keyboard) {
  50191. keyboard.keysRight = value;
  50192. }
  50193. },
  50194. enumerable: true,
  50195. configurable: true
  50196. });
  50197. /**
  50198. * Attach a control to the HTML DOM element.
  50199. * @param element Defines the element that listens to the input events.
  50200. * @param noPreventDefault Defines whether events caught by the controls should call preventdefault(). https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
  50201. */
  50202. FlyCamera.prototype.attachControl = function (element, noPreventDefault) {
  50203. this.inputs.attachElement(element, noPreventDefault);
  50204. };
  50205. /**
  50206. * Detach a control from the HTML DOM element.
  50207. * The camera will stop reacting to that input.
  50208. * @param element Defines the element that listens to the input events.
  50209. */
  50210. FlyCamera.prototype.detachControl = function (element) {
  50211. this.inputs.detachElement(element);
  50212. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  50213. };
  50214. Object.defineProperty(FlyCamera.prototype, "collisionMask", {
  50215. /**
  50216. * Get the mask that the camera ignores in collision events.
  50217. */
  50218. get: function () {
  50219. return this._collisionMask;
  50220. },
  50221. /**
  50222. * Set the mask that the camera ignores in collision events.
  50223. */
  50224. set: function (mask) {
  50225. this._collisionMask = !isNaN(mask) ? mask : -1;
  50226. },
  50227. enumerable: true,
  50228. configurable: true
  50229. });
  50230. /** @hidden */
  50231. FlyCamera.prototype._collideWithWorld = function (displacement) {
  50232. var globalPosition;
  50233. if (this.parent) {
  50234. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  50235. }
  50236. else {
  50237. globalPosition = this.position;
  50238. }
  50239. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  50240. this._oldPosition.addInPlace(this.ellipsoidOffset);
  50241. if (!this._collider) {
  50242. this._collider = new BABYLON.Collider();
  50243. }
  50244. this._collider._radius = this.ellipsoid;
  50245. this._collider.collisionMask = this._collisionMask;
  50246. // No need for clone, as long as gravity is not on.
  50247. var actualDisplacement = displacement;
  50248. // Add gravity to direction to prevent dual-collision checking.
  50249. if (this.applyGravity) {
  50250. // This prevents mending with cameraDirection, a global variable of the fly camera class.
  50251. actualDisplacement = displacement.add(this.getScene().gravity);
  50252. }
  50253. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  50254. };
  50255. /** @hidden */
  50256. FlyCamera.prototype._checkInputs = function () {
  50257. if (!this._localDirection) {
  50258. this._localDirection = BABYLON.Vector3.Zero();
  50259. this._transformedDirection = BABYLON.Vector3.Zero();
  50260. }
  50261. this.inputs.checkInputs();
  50262. _super.prototype._checkInputs.call(this);
  50263. };
  50264. /** @hidden */
  50265. FlyCamera.prototype._decideIfNeedsToMove = function () {
  50266. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  50267. };
  50268. /** @hidden */
  50269. FlyCamera.prototype._updatePosition = function () {
  50270. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  50271. this._collideWithWorld(this.cameraDirection);
  50272. }
  50273. else {
  50274. _super.prototype._updatePosition.call(this);
  50275. }
  50276. };
  50277. /**
  50278. * Restore the Roll to its target value at the rate specified.
  50279. * @param rate - Higher means slower restoring.
  50280. * @hidden
  50281. */
  50282. FlyCamera.prototype.restoreRoll = function (rate) {
  50283. var limit = this._trackRoll; // Target Roll.
  50284. var z = this.rotation.z; // Current Roll.
  50285. var delta = limit - z; // Difference in Roll.
  50286. var minRad = 0.001; // Tenth of a radian is a barely noticable difference.
  50287. // If the difference is noticable, restore the Roll.
  50288. if (Math.abs(delta) >= minRad) {
  50289. // Change Z rotation towards the target Roll.
  50290. this.rotation.z += delta / rate;
  50291. // Match when near enough.
  50292. if (Math.abs(limit - this.rotation.z) <= minRad) {
  50293. this.rotation.z = limit;
  50294. }
  50295. }
  50296. };
  50297. /**
  50298. * Destroy the camera and release the current resources held by it.
  50299. */
  50300. FlyCamera.prototype.dispose = function () {
  50301. this.inputs.clear();
  50302. _super.prototype.dispose.call(this);
  50303. };
  50304. /**
  50305. * Get the current object class name.
  50306. * @returns the class name.
  50307. */
  50308. FlyCamera.prototype.getClassName = function () {
  50309. return "FlyCamera";
  50310. };
  50311. __decorate([
  50312. BABYLON.serializeAsVector3()
  50313. ], FlyCamera.prototype, "ellipsoid", void 0);
  50314. __decorate([
  50315. BABYLON.serializeAsVector3()
  50316. ], FlyCamera.prototype, "ellipsoidOffset", void 0);
  50317. __decorate([
  50318. BABYLON.serialize()
  50319. ], FlyCamera.prototype, "checkCollisions", void 0);
  50320. __decorate([
  50321. BABYLON.serialize()
  50322. ], FlyCamera.prototype, "applyGravity", void 0);
  50323. return FlyCamera;
  50324. }(BABYLON.TargetCamera));
  50325. BABYLON.FlyCamera = FlyCamera;
  50326. })(BABYLON || (BABYLON = {}));
  50327. //# sourceMappingURL=flyCamera.js.map
  50328. var BABYLON;
  50329. (function (BABYLON) {
  50330. /**
  50331. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  50332. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50333. */
  50334. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  50335. function ArcRotateCameraKeyboardMoveInput() {
  50336. /**
  50337. * Defines the list of key codes associated with the up action (increase alpha)
  50338. */
  50339. this.keysUp = [38];
  50340. /**
  50341. * Defines the list of key codes associated with the down action (decrease alpha)
  50342. */
  50343. this.keysDown = [40];
  50344. /**
  50345. * Defines the list of key codes associated with the left action (increase beta)
  50346. */
  50347. this.keysLeft = [37];
  50348. /**
  50349. * Defines the list of key codes associated with the right action (decrease beta)
  50350. */
  50351. this.keysRight = [39];
  50352. /**
  50353. * Defines the list of key codes associated with the reset action.
  50354. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  50355. */
  50356. this.keysReset = [220];
  50357. /**
  50358. * Defines the panning sensibility of the inputs.
  50359. * (How fast is the camera paning)
  50360. */
  50361. this.panningSensibility = 50.0;
  50362. /**
  50363. * Defines the zooming sensibility of the inputs.
  50364. * (How fast is the camera zooming)
  50365. */
  50366. this.zoomingSensibility = 25.0;
  50367. /**
  50368. * Defines wether maintaining the alt key down switch the movement mode from
  50369. * orientation to zoom.
  50370. */
  50371. this.useAltToZoom = true;
  50372. /**
  50373. * Rotation speed of the camera
  50374. */
  50375. this.angularSpeed = 0.01;
  50376. this._keys = new Array();
  50377. }
  50378. /**
  50379. * Attach the input controls to a specific dom element to get the input from.
  50380. * @param element Defines the element the controls should be listened from
  50381. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50382. */
  50383. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  50384. var _this = this;
  50385. if (this._onCanvasBlurObserver) {
  50386. return;
  50387. }
  50388. this._scene = this.camera.getScene();
  50389. this._engine = this._scene.getEngine();
  50390. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  50391. _this._keys = [];
  50392. });
  50393. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  50394. var evt = info.event;
  50395. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  50396. _this._ctrlPressed = evt.ctrlKey;
  50397. _this._altPressed = evt.altKey;
  50398. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  50399. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  50400. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  50401. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  50402. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  50403. var index = _this._keys.indexOf(evt.keyCode);
  50404. if (index === -1) {
  50405. _this._keys.push(evt.keyCode);
  50406. }
  50407. if (evt.preventDefault) {
  50408. if (!noPreventDefault) {
  50409. evt.preventDefault();
  50410. }
  50411. }
  50412. }
  50413. }
  50414. else {
  50415. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  50416. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  50417. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  50418. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  50419. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  50420. var index = _this._keys.indexOf(evt.keyCode);
  50421. if (index >= 0) {
  50422. _this._keys.splice(index, 1);
  50423. }
  50424. if (evt.preventDefault) {
  50425. if (!noPreventDefault) {
  50426. evt.preventDefault();
  50427. }
  50428. }
  50429. }
  50430. }
  50431. });
  50432. };
  50433. /**
  50434. * Detach the current controls from the specified dom element.
  50435. * @param element Defines the element to stop listening the inputs from
  50436. */
  50437. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  50438. if (this._scene) {
  50439. if (this._onKeyboardObserver) {
  50440. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  50441. }
  50442. if (this._onCanvasBlurObserver) {
  50443. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  50444. }
  50445. this._onKeyboardObserver = null;
  50446. this._onCanvasBlurObserver = null;
  50447. }
  50448. this._keys = [];
  50449. };
  50450. /**
  50451. * Update the current camera state depending on the inputs that have been used this frame.
  50452. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  50453. */
  50454. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  50455. if (this._onKeyboardObserver) {
  50456. var camera = this.camera;
  50457. for (var index = 0; index < this._keys.length; index++) {
  50458. var keyCode = this._keys[index];
  50459. if (this.keysLeft.indexOf(keyCode) !== -1) {
  50460. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  50461. camera.inertialPanningX -= 1 / this.panningSensibility;
  50462. }
  50463. else {
  50464. camera.inertialAlphaOffset -= this.angularSpeed;
  50465. }
  50466. }
  50467. else if (this.keysUp.indexOf(keyCode) !== -1) {
  50468. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  50469. camera.inertialPanningY += 1 / this.panningSensibility;
  50470. }
  50471. else if (this._altPressed && this.useAltToZoom) {
  50472. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  50473. }
  50474. else {
  50475. camera.inertialBetaOffset -= this.angularSpeed;
  50476. }
  50477. }
  50478. else if (this.keysRight.indexOf(keyCode) !== -1) {
  50479. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  50480. camera.inertialPanningX += 1 / this.panningSensibility;
  50481. }
  50482. else {
  50483. camera.inertialAlphaOffset += this.angularSpeed;
  50484. }
  50485. }
  50486. else if (this.keysDown.indexOf(keyCode) !== -1) {
  50487. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  50488. camera.inertialPanningY -= 1 / this.panningSensibility;
  50489. }
  50490. else if (this._altPressed && this.useAltToZoom) {
  50491. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  50492. }
  50493. else {
  50494. camera.inertialBetaOffset += this.angularSpeed;
  50495. }
  50496. }
  50497. else if (this.keysReset.indexOf(keyCode) !== -1) {
  50498. if (camera.useInputToRestoreState) {
  50499. camera.restoreState();
  50500. }
  50501. }
  50502. }
  50503. }
  50504. };
  50505. /**
  50506. * Gets the class name of the current intput.
  50507. * @returns the class name
  50508. */
  50509. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  50510. return "ArcRotateCameraKeyboardMoveInput";
  50511. };
  50512. /**
  50513. * Get the friendly name associated with the input class.
  50514. * @returns the input friendly name
  50515. */
  50516. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  50517. return "keyboard";
  50518. };
  50519. __decorate([
  50520. BABYLON.serialize()
  50521. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  50522. __decorate([
  50523. BABYLON.serialize()
  50524. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  50525. __decorate([
  50526. BABYLON.serialize()
  50527. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  50528. __decorate([
  50529. BABYLON.serialize()
  50530. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  50531. __decorate([
  50532. BABYLON.serialize()
  50533. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  50534. __decorate([
  50535. BABYLON.serialize()
  50536. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  50537. __decorate([
  50538. BABYLON.serialize()
  50539. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  50540. __decorate([
  50541. BABYLON.serialize()
  50542. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  50543. __decorate([
  50544. BABYLON.serialize()
  50545. ], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", void 0);
  50546. return ArcRotateCameraKeyboardMoveInput;
  50547. }());
  50548. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  50549. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  50550. })(BABYLON || (BABYLON = {}));
  50551. //# sourceMappingURL=arcRotateCameraKeyboardMoveInput.js.map
  50552. var BABYLON;
  50553. (function (BABYLON) {
  50554. /**
  50555. * Manage the mouse wheel inputs to control an arc rotate camera.
  50556. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50557. */
  50558. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  50559. function ArcRotateCameraMouseWheelInput() {
  50560. /**
  50561. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  50562. */
  50563. this.wheelPrecision = 3.0;
  50564. /**
  50565. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  50566. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  50567. */
  50568. this.wheelDeltaPercentage = 0;
  50569. }
  50570. /**
  50571. * Attach the input controls to a specific dom element to get the input from.
  50572. * @param element Defines the element the controls should be listened from
  50573. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50574. */
  50575. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  50576. var _this = this;
  50577. this._wheel = function (p, s) {
  50578. //sanity check - this should be a PointerWheel event.
  50579. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL) {
  50580. return;
  50581. }
  50582. var event = p.event;
  50583. var delta = 0;
  50584. if (event.wheelDelta) {
  50585. if (_this.wheelDeltaPercentage) {
  50586. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  50587. if (event.wheelDelta > 0) {
  50588. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  50589. }
  50590. else {
  50591. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  50592. }
  50593. }
  50594. else {
  50595. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  50596. }
  50597. }
  50598. else {
  50599. var deltaValue = event.deltaY || event.detail;
  50600. delta = -deltaValue / _this.wheelPrecision;
  50601. }
  50602. if (delta) {
  50603. _this.camera.inertialRadiusOffset += delta;
  50604. }
  50605. if (event.preventDefault) {
  50606. if (!noPreventDefault) {
  50607. event.preventDefault();
  50608. }
  50609. }
  50610. };
  50611. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  50612. };
  50613. /**
  50614. * Detach the current controls from the specified dom element.
  50615. * @param element Defines the element to stop listening the inputs from
  50616. */
  50617. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  50618. if (this._observer && element) {
  50619. this.camera.getScene().onPointerObservable.remove(this._observer);
  50620. this._observer = null;
  50621. this._wheel = null;
  50622. }
  50623. };
  50624. /**
  50625. * Gets the class name of the current intput.
  50626. * @returns the class name
  50627. */
  50628. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  50629. return "ArcRotateCameraMouseWheelInput";
  50630. };
  50631. /**
  50632. * Get the friendly name associated with the input class.
  50633. * @returns the input friendly name
  50634. */
  50635. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  50636. return "mousewheel";
  50637. };
  50638. __decorate([
  50639. BABYLON.serialize()
  50640. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  50641. __decorate([
  50642. BABYLON.serialize()
  50643. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  50644. return ArcRotateCameraMouseWheelInput;
  50645. }());
  50646. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  50647. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  50648. })(BABYLON || (BABYLON = {}));
  50649. //# sourceMappingURL=arcRotateCameraMouseWheelInput.js.map
  50650. var BABYLON;
  50651. (function (BABYLON) {
  50652. /**
  50653. * Manage the pointers inputs to control an arc rotate camera.
  50654. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  50655. */
  50656. var ArcRotateCameraPointersInput = /** @class */ (function () {
  50657. function ArcRotateCameraPointersInput() {
  50658. /**
  50659. * Defines the buttons associated with the input to handle camera move.
  50660. */
  50661. this.buttons = [0, 1, 2];
  50662. /**
  50663. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  50664. */
  50665. this.angularSensibilityX = 1000.0;
  50666. /**
  50667. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  50668. */
  50669. this.angularSensibilityY = 1000.0;
  50670. /**
  50671. * Defines the pointer pinch precision or how fast is the camera zooming.
  50672. */
  50673. this.pinchPrecision = 12.0;
  50674. /**
  50675. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  50676. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  50677. */
  50678. this.pinchDeltaPercentage = 0;
  50679. /**
  50680. * Defines the pointer panning sensibility or how fast is the camera moving.
  50681. */
  50682. this.panningSensibility = 1000.0;
  50683. /**
  50684. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  50685. */
  50686. this.multiTouchPanning = true;
  50687. /**
  50688. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  50689. */
  50690. this.multiTouchPanAndZoom = true;
  50691. /**
  50692. * Revers pinch action direction.
  50693. */
  50694. this.pinchInwards = true;
  50695. this._isPanClick = false;
  50696. }
  50697. /**
  50698. * Attach the input controls to a specific dom element to get the input from.
  50699. * @param element Defines the element the controls should be listened from
  50700. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50701. */
  50702. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  50703. var _this = this;
  50704. var engine = this.camera.getEngine();
  50705. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  50706. var pointA = null;
  50707. var pointB = null;
  50708. var previousPinchSquaredDistance = 0;
  50709. var initialDistance = 0;
  50710. var twoFingerActivityCount = 0;
  50711. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  50712. this._pointerInput = function (p, s) {
  50713. var evt = p.event;
  50714. var isTouch = p.event.pointerType === "touch";
  50715. if (engine.isInVRExclusivePointerMode) {
  50716. return;
  50717. }
  50718. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  50719. return;
  50720. }
  50721. var srcElement = (evt.srcElement || evt.target);
  50722. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  50723. try {
  50724. srcElement.setPointerCapture(evt.pointerId);
  50725. }
  50726. catch (e) {
  50727. //Nothing to do with the error. Execution will continue.
  50728. }
  50729. // Manage panning with pan button click
  50730. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  50731. // manage pointers
  50732. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  50733. if (pointA === null) {
  50734. pointA = cacheSoloPointer;
  50735. }
  50736. else if (pointB === null) {
  50737. pointB = cacheSoloPointer;
  50738. }
  50739. if (!noPreventDefault) {
  50740. evt.preventDefault();
  50741. element.focus();
  50742. }
  50743. }
  50744. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  50745. if (_this.camera.useInputToRestoreState) {
  50746. _this.camera.restoreState();
  50747. }
  50748. }
  50749. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  50750. try {
  50751. srcElement.releasePointerCapture(evt.pointerId);
  50752. }
  50753. catch (e) {
  50754. //Nothing to do with the error.
  50755. }
  50756. cacheSoloPointer = null;
  50757. previousPinchSquaredDistance = 0;
  50758. previousMultiTouchPanPosition.isPaning = false;
  50759. previousMultiTouchPanPosition.isPinching = false;
  50760. twoFingerActivityCount = 0;
  50761. initialDistance = 0;
  50762. if (!isTouch) {
  50763. pointB = null; // Mouse and pen are mono pointer
  50764. }
  50765. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  50766. //but emptying completly pointers collection is required to fix a bug on iPhone :
  50767. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  50768. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  50769. if (engine._badOS) {
  50770. pointA = pointB = null;
  50771. }
  50772. else {
  50773. //only remove the impacted pointer in case of multitouch allowing on most
  50774. //platforms switching from rotate to zoom and pan seamlessly.
  50775. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  50776. pointA = pointB;
  50777. pointB = null;
  50778. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  50779. }
  50780. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  50781. pointB = null;
  50782. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  50783. }
  50784. else {
  50785. pointA = pointB = null;
  50786. }
  50787. }
  50788. if (!noPreventDefault) {
  50789. evt.preventDefault();
  50790. }
  50791. }
  50792. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  50793. if (!noPreventDefault) {
  50794. evt.preventDefault();
  50795. }
  50796. // One button down
  50797. if (pointA && pointB === null && cacheSoloPointer) {
  50798. if (_this.panningSensibility !== 0 &&
  50799. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  50800. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  50801. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  50802. }
  50803. else {
  50804. var offsetX = evt.clientX - cacheSoloPointer.x;
  50805. var offsetY = evt.clientY - cacheSoloPointer.y;
  50806. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  50807. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  50808. }
  50809. cacheSoloPointer.x = evt.clientX;
  50810. cacheSoloPointer.y = evt.clientY;
  50811. }
  50812. // Two buttons down: pinch/pan
  50813. else if (pointA && pointB) {
  50814. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  50815. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  50816. ed.x = evt.clientX;
  50817. ed.y = evt.clientY;
  50818. var direction = _this.pinchInwards ? 1 : -1;
  50819. var distX = pointA.x - pointB.x;
  50820. var distY = pointA.y - pointB.y;
  50821. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  50822. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  50823. if (previousPinchSquaredDistance === 0) {
  50824. initialDistance = pinchDistance;
  50825. previousPinchSquaredDistance = pinchSquaredDistance;
  50826. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  50827. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  50828. return;
  50829. }
  50830. if (_this.multiTouchPanAndZoom) {
  50831. if (_this.pinchDeltaPercentage) {
  50832. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  50833. }
  50834. else {
  50835. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  50836. (_this.pinchPrecision *
  50837. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  50838. direction);
  50839. }
  50840. if (_this.panningSensibility !== 0) {
  50841. var pointersCenterX = (pointA.x + pointB.x) / 2;
  50842. var pointersCenterY = (pointA.y + pointB.y) / 2;
  50843. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  50844. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  50845. previousMultiTouchPanPosition.x = pointersCenterX;
  50846. previousMultiTouchPanPosition.y = pointersCenterY;
  50847. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  50848. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  50849. }
  50850. }
  50851. else {
  50852. twoFingerActivityCount++;
  50853. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  50854. if (_this.pinchDeltaPercentage) {
  50855. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  50856. }
  50857. else {
  50858. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  50859. (_this.pinchPrecision *
  50860. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  50861. direction);
  50862. }
  50863. previousMultiTouchPanPosition.isPaning = false;
  50864. previousMultiTouchPanPosition.isPinching = true;
  50865. }
  50866. else {
  50867. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  50868. if (!previousMultiTouchPanPosition.isPaning) {
  50869. previousMultiTouchPanPosition.isPaning = true;
  50870. previousMultiTouchPanPosition.isPinching = false;
  50871. previousMultiTouchPanPosition.x = ed.x;
  50872. previousMultiTouchPanPosition.y = ed.y;
  50873. return;
  50874. }
  50875. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  50876. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  50877. }
  50878. }
  50879. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  50880. previousMultiTouchPanPosition.x = ed.x;
  50881. previousMultiTouchPanPosition.y = ed.y;
  50882. }
  50883. }
  50884. previousPinchSquaredDistance = pinchSquaredDistance;
  50885. }
  50886. }
  50887. };
  50888. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  50889. this._onContextMenu = function (evt) {
  50890. evt.preventDefault();
  50891. };
  50892. if (!this.camera._useCtrlForPanning) {
  50893. element.addEventListener("contextmenu", this._onContextMenu, false);
  50894. }
  50895. this._onLostFocus = function () {
  50896. //this._keys = [];
  50897. pointA = pointB = null;
  50898. previousPinchSquaredDistance = 0;
  50899. previousMultiTouchPanPosition.isPaning = false;
  50900. previousMultiTouchPanPosition.isPinching = false;
  50901. twoFingerActivityCount = 0;
  50902. cacheSoloPointer = null;
  50903. initialDistance = 0;
  50904. };
  50905. this._onMouseMove = function (evt) {
  50906. if (!engine.isPointerLock) {
  50907. return;
  50908. }
  50909. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  50910. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  50911. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  50912. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  50913. if (!noPreventDefault) {
  50914. evt.preventDefault();
  50915. }
  50916. };
  50917. this._onGestureStart = function (e) {
  50918. if (window.MSGesture === undefined) {
  50919. return;
  50920. }
  50921. if (!_this._MSGestureHandler) {
  50922. _this._MSGestureHandler = new MSGesture();
  50923. _this._MSGestureHandler.target = element;
  50924. }
  50925. _this._MSGestureHandler.addPointer(e.pointerId);
  50926. };
  50927. this._onGesture = function (e) {
  50928. _this.camera.radius *= e.scale;
  50929. if (e.preventDefault) {
  50930. if (!noPreventDefault) {
  50931. e.stopPropagation();
  50932. e.preventDefault();
  50933. }
  50934. }
  50935. };
  50936. element.addEventListener("mousemove", this._onMouseMove, false);
  50937. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  50938. element.addEventListener("MSGestureChange", this._onGesture, false);
  50939. BABYLON.Tools.RegisterTopRootEvents([
  50940. { name: "blur", handler: this._onLostFocus }
  50941. ]);
  50942. };
  50943. /**
  50944. * Detach the current controls from the specified dom element.
  50945. * @param element Defines the element to stop listening the inputs from
  50946. */
  50947. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  50948. if (this._onLostFocus) {
  50949. BABYLON.Tools.UnregisterTopRootEvents([
  50950. { name: "blur", handler: this._onLostFocus }
  50951. ]);
  50952. }
  50953. if (element && this._observer) {
  50954. this.camera.getScene().onPointerObservable.remove(this._observer);
  50955. this._observer = null;
  50956. if (this._onContextMenu) {
  50957. element.removeEventListener("contextmenu", this._onContextMenu);
  50958. }
  50959. if (this._onMouseMove) {
  50960. element.removeEventListener("mousemove", this._onMouseMove);
  50961. }
  50962. if (this._onGestureStart) {
  50963. element.removeEventListener("MSPointerDown", this._onGestureStart);
  50964. }
  50965. if (this._onGesture) {
  50966. element.removeEventListener("MSGestureChange", this._onGesture);
  50967. }
  50968. this._isPanClick = false;
  50969. this.pinchInwards = true;
  50970. this._onMouseMove = null;
  50971. this._onGestureStart = null;
  50972. this._onGesture = null;
  50973. this._MSGestureHandler = null;
  50974. this._onLostFocus = null;
  50975. this._onContextMenu = null;
  50976. }
  50977. };
  50978. /**
  50979. * Gets the class name of the current intput.
  50980. * @returns the class name
  50981. */
  50982. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  50983. return "ArcRotateCameraPointersInput";
  50984. };
  50985. /**
  50986. * Get the friendly name associated with the input class.
  50987. * @returns the input friendly name
  50988. */
  50989. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  50990. return "pointers";
  50991. };
  50992. __decorate([
  50993. BABYLON.serialize()
  50994. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  50995. __decorate([
  50996. BABYLON.serialize()
  50997. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  50998. __decorate([
  50999. BABYLON.serialize()
  51000. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  51001. __decorate([
  51002. BABYLON.serialize()
  51003. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  51004. __decorate([
  51005. BABYLON.serialize()
  51006. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  51007. __decorate([
  51008. BABYLON.serialize()
  51009. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  51010. __decorate([
  51011. BABYLON.serialize()
  51012. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  51013. __decorate([
  51014. BABYLON.serialize()
  51015. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  51016. return ArcRotateCameraPointersInput;
  51017. }());
  51018. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  51019. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  51020. })(BABYLON || (BABYLON = {}));
  51021. //# sourceMappingURL=arcRotateCameraPointersInput.js.map
  51022. var BABYLON;
  51023. (function (BABYLON) {
  51024. /**
  51025. * Default Inputs manager for the ArcRotateCamera.
  51026. * It groups all the default supported inputs for ease of use.
  51027. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  51028. */
  51029. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  51030. __extends(ArcRotateCameraInputsManager, _super);
  51031. /**
  51032. * Instantiates a new ArcRotateCameraInputsManager.
  51033. * @param camera Defines the camera the inputs belong to
  51034. */
  51035. function ArcRotateCameraInputsManager(camera) {
  51036. return _super.call(this, camera) || this;
  51037. }
  51038. /**
  51039. * Add mouse wheel input support to the input manager.
  51040. * @returns the current input manager
  51041. */
  51042. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  51043. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  51044. return this;
  51045. };
  51046. /**
  51047. * Add pointers input support to the input manager.
  51048. * @returns the current input manager
  51049. */
  51050. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  51051. this.add(new BABYLON.ArcRotateCameraPointersInput());
  51052. return this;
  51053. };
  51054. /**
  51055. * Add keyboard input support to the input manager.
  51056. * @returns the current input manager
  51057. */
  51058. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  51059. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  51060. return this;
  51061. };
  51062. /**
  51063. * Add orientation input support to the input manager.
  51064. * @returns the current input manager
  51065. */
  51066. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  51067. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  51068. return this;
  51069. };
  51070. return ArcRotateCameraInputsManager;
  51071. }(BABYLON.CameraInputsManager));
  51072. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  51073. })(BABYLON || (BABYLON = {}));
  51074. //# sourceMappingURL=arcRotateCameraInputsManager.js.map
  51075. var BABYLON;
  51076. (function (BABYLON) {
  51077. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  51078. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  51079. });
  51080. /**
  51081. * This represents an orbital type of camera.
  51082. *
  51083. * 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.
  51084. * 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.
  51085. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  51086. */
  51087. var ArcRotateCamera = /** @class */ (function (_super) {
  51088. __extends(ArcRotateCamera, _super);
  51089. /**
  51090. * Instantiates a new ArcRotateCamera in a given scene
  51091. * @param name Defines the name of the camera
  51092. * @param alpha Defines the camera rotation along the logitudinal axis
  51093. * @param beta Defines the camera rotation along the latitudinal axis
  51094. * @param radius Defines the camera distance from its target
  51095. * @param target Defines the camera target
  51096. * @param scene Defines the scene the camera belongs to
  51097. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  51098. */
  51099. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  51100. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  51101. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  51102. /**
  51103. * Current inertia value on the longitudinal axis.
  51104. * The bigger this number the longer it will take for the camera to stop.
  51105. */
  51106. _this.inertialAlphaOffset = 0;
  51107. /**
  51108. * Current inertia value on the latitudinal axis.
  51109. * The bigger this number the longer it will take for the camera to stop.
  51110. */
  51111. _this.inertialBetaOffset = 0;
  51112. /**
  51113. * Current inertia value on the radius axis.
  51114. * The bigger this number the longer it will take for the camera to stop.
  51115. */
  51116. _this.inertialRadiusOffset = 0;
  51117. /**
  51118. * Minimum allowed angle on the longitudinal axis.
  51119. * This can help limiting how the Camera is able to move in the scene.
  51120. */
  51121. _this.lowerAlphaLimit = null;
  51122. /**
  51123. * Maximum allowed angle on the longitudinal axis.
  51124. * This can help limiting how the Camera is able to move in the scene.
  51125. */
  51126. _this.upperAlphaLimit = null;
  51127. /**
  51128. * Minimum allowed angle on the latitudinal axis.
  51129. * This can help limiting how the Camera is able to move in the scene.
  51130. */
  51131. _this.lowerBetaLimit = 0.01;
  51132. /**
  51133. * Maximum allowed angle on the latitudinal axis.
  51134. * This can help limiting how the Camera is able to move in the scene.
  51135. */
  51136. _this.upperBetaLimit = Math.PI;
  51137. /**
  51138. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  51139. * This can help limiting how the Camera is able to move in the scene.
  51140. */
  51141. _this.lowerRadiusLimit = null;
  51142. /**
  51143. * Maximum allowed distance of the camera to the target (The camera can not get further).
  51144. * This can help limiting how the Camera is able to move in the scene.
  51145. */
  51146. _this.upperRadiusLimit = null;
  51147. /**
  51148. * Defines the current inertia value used during panning of the camera along the X axis.
  51149. */
  51150. _this.inertialPanningX = 0;
  51151. /**
  51152. * Defines the current inertia value used during panning of the camera along the Y axis.
  51153. */
  51154. _this.inertialPanningY = 0;
  51155. /**
  51156. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  51157. * Basically if your fingers moves away from more than this distance you will be considered
  51158. * in pinch mode.
  51159. */
  51160. _this.pinchToPanMaxDistance = 20;
  51161. /**
  51162. * Defines the maximum distance the camera can pan.
  51163. * This could help keeping the cammera always in your scene.
  51164. */
  51165. _this.panningDistanceLimit = null;
  51166. /**
  51167. * Defines the target of the camera before paning.
  51168. */
  51169. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  51170. /**
  51171. * Defines the value of the inertia used during panning.
  51172. * 0 would mean stop inertia and one would mean no decelleration at all.
  51173. */
  51174. _this.panningInertia = 0.9;
  51175. //-- end properties for backward compatibility for inputs
  51176. /**
  51177. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  51178. */
  51179. _this.zoomOnFactor = 1;
  51180. /**
  51181. * Defines a screen offset for the camera position.
  51182. */
  51183. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  51184. /**
  51185. * Allows the camera to be completely reversed.
  51186. * If false the camera can not arrive upside down.
  51187. */
  51188. _this.allowUpsideDown = true;
  51189. /**
  51190. * Define if double tap/click is used to restore the previously saved state of the camera.
  51191. */
  51192. _this.useInputToRestoreState = true;
  51193. /** @hidden */
  51194. _this._viewMatrix = new BABYLON.Matrix();
  51195. /**
  51196. * Defines the allowed panning axis.
  51197. */
  51198. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  51199. /**
  51200. * Observable triggered when the mesh target has been changed on the camera.
  51201. */
  51202. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  51203. /**
  51204. * Defines whether the camera should check collision with the objects oh the scene.
  51205. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  51206. */
  51207. _this.checkCollisions = false;
  51208. /**
  51209. * Defines the collision radius of the camera.
  51210. * This simulates a sphere around the camera.
  51211. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  51212. */
  51213. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51214. _this._previousPosition = BABYLON.Vector3.Zero();
  51215. _this._collisionVelocity = BABYLON.Vector3.Zero();
  51216. _this._newPosition = BABYLON.Vector3.Zero();
  51217. _this._computationVector = BABYLON.Vector3.Zero();
  51218. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  51219. if (collidedMesh === void 0) { collidedMesh = null; }
  51220. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  51221. newPosition.multiplyInPlace(_this._collider._radius);
  51222. }
  51223. if (!collidedMesh) {
  51224. _this._previousPosition.copyFrom(_this.position);
  51225. }
  51226. else {
  51227. _this.setPosition(newPosition);
  51228. if (_this.onCollide) {
  51229. _this.onCollide(collidedMesh);
  51230. }
  51231. }
  51232. // Recompute because of constraints
  51233. var cosa = Math.cos(_this.alpha);
  51234. var sina = Math.sin(_this.alpha);
  51235. var cosb = Math.cos(_this.beta);
  51236. var sinb = Math.sin(_this.beta);
  51237. if (sinb === 0) {
  51238. sinb = 0.0001;
  51239. }
  51240. var target = _this._getTargetPosition();
  51241. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  51242. target.addToRef(_this._computationVector, _this._newPosition);
  51243. _this.position.copyFrom(_this._newPosition);
  51244. var up = _this.upVector;
  51245. if (_this.allowUpsideDown && _this.beta < 0) {
  51246. up = up.clone();
  51247. up = up.negate();
  51248. }
  51249. _this._computeViewMatrix(_this.position, target, up);
  51250. _this._viewMatrix.addAtIndex(12, _this.targetScreenOffset.x);
  51251. _this._viewMatrix.addAtIndex(13, _this.targetScreenOffset.y);
  51252. _this._collisionTriggered = false;
  51253. };
  51254. _this._target = BABYLON.Vector3.Zero();
  51255. if (target) {
  51256. _this.setTarget(target);
  51257. }
  51258. _this.alpha = alpha;
  51259. _this.beta = beta;
  51260. _this.radius = radius;
  51261. _this.getViewMatrix();
  51262. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  51263. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  51264. return _this;
  51265. }
  51266. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  51267. /**
  51268. * Defines the target point of the camera.
  51269. * The camera looks towards it form the radius distance.
  51270. */
  51271. get: function () {
  51272. return this._target;
  51273. },
  51274. set: function (value) {
  51275. this.setTarget(value);
  51276. },
  51277. enumerable: true,
  51278. configurable: true
  51279. });
  51280. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  51281. //-- begin properties for backward compatibility for inputs
  51282. /**
  51283. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  51284. */
  51285. get: function () {
  51286. var pointers = this.inputs.attached["pointers"];
  51287. if (pointers) {
  51288. return pointers.angularSensibilityX;
  51289. }
  51290. return 0;
  51291. },
  51292. set: function (value) {
  51293. var pointers = this.inputs.attached["pointers"];
  51294. if (pointers) {
  51295. pointers.angularSensibilityX = value;
  51296. }
  51297. },
  51298. enumerable: true,
  51299. configurable: true
  51300. });
  51301. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  51302. /**
  51303. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  51304. */
  51305. get: function () {
  51306. var pointers = this.inputs.attached["pointers"];
  51307. if (pointers) {
  51308. return pointers.angularSensibilityY;
  51309. }
  51310. return 0;
  51311. },
  51312. set: function (value) {
  51313. var pointers = this.inputs.attached["pointers"];
  51314. if (pointers) {
  51315. pointers.angularSensibilityY = value;
  51316. }
  51317. },
  51318. enumerable: true,
  51319. configurable: true
  51320. });
  51321. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  51322. /**
  51323. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  51324. */
  51325. get: function () {
  51326. var pointers = this.inputs.attached["pointers"];
  51327. if (pointers) {
  51328. return pointers.pinchPrecision;
  51329. }
  51330. return 0;
  51331. },
  51332. set: function (value) {
  51333. var pointers = this.inputs.attached["pointers"];
  51334. if (pointers) {
  51335. pointers.pinchPrecision = value;
  51336. }
  51337. },
  51338. enumerable: true,
  51339. configurable: true
  51340. });
  51341. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  51342. /**
  51343. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  51344. * It will be used instead of pinchDeltaPrecision if different from 0.
  51345. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  51346. */
  51347. get: function () {
  51348. var pointers = this.inputs.attached["pointers"];
  51349. if (pointers) {
  51350. return pointers.pinchDeltaPercentage;
  51351. }
  51352. return 0;
  51353. },
  51354. set: function (value) {
  51355. var pointers = this.inputs.attached["pointers"];
  51356. if (pointers) {
  51357. pointers.pinchDeltaPercentage = value;
  51358. }
  51359. },
  51360. enumerable: true,
  51361. configurable: true
  51362. });
  51363. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  51364. /**
  51365. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  51366. */
  51367. get: function () {
  51368. var pointers = this.inputs.attached["pointers"];
  51369. if (pointers) {
  51370. return pointers.panningSensibility;
  51371. }
  51372. return 0;
  51373. },
  51374. set: function (value) {
  51375. var pointers = this.inputs.attached["pointers"];
  51376. if (pointers) {
  51377. pointers.panningSensibility = value;
  51378. }
  51379. },
  51380. enumerable: true,
  51381. configurable: true
  51382. });
  51383. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  51384. /**
  51385. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  51386. */
  51387. get: function () {
  51388. var keyboard = this.inputs.attached["keyboard"];
  51389. if (keyboard) {
  51390. return keyboard.keysUp;
  51391. }
  51392. return [];
  51393. },
  51394. set: function (value) {
  51395. var keyboard = this.inputs.attached["keyboard"];
  51396. if (keyboard) {
  51397. keyboard.keysUp = value;
  51398. }
  51399. },
  51400. enumerable: true,
  51401. configurable: true
  51402. });
  51403. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  51404. /**
  51405. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  51406. */
  51407. get: function () {
  51408. var keyboard = this.inputs.attached["keyboard"];
  51409. if (keyboard) {
  51410. return keyboard.keysDown;
  51411. }
  51412. return [];
  51413. },
  51414. set: function (value) {
  51415. var keyboard = this.inputs.attached["keyboard"];
  51416. if (keyboard) {
  51417. keyboard.keysDown = value;
  51418. }
  51419. },
  51420. enumerable: true,
  51421. configurable: true
  51422. });
  51423. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  51424. /**
  51425. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  51426. */
  51427. get: function () {
  51428. var keyboard = this.inputs.attached["keyboard"];
  51429. if (keyboard) {
  51430. return keyboard.keysLeft;
  51431. }
  51432. return [];
  51433. },
  51434. set: function (value) {
  51435. var keyboard = this.inputs.attached["keyboard"];
  51436. if (keyboard) {
  51437. keyboard.keysLeft = value;
  51438. }
  51439. },
  51440. enumerable: true,
  51441. configurable: true
  51442. });
  51443. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  51444. /**
  51445. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  51446. */
  51447. get: function () {
  51448. var keyboard = this.inputs.attached["keyboard"];
  51449. if (keyboard) {
  51450. return keyboard.keysRight;
  51451. }
  51452. return [];
  51453. },
  51454. set: function (value) {
  51455. var keyboard = this.inputs.attached["keyboard"];
  51456. if (keyboard) {
  51457. keyboard.keysRight = value;
  51458. }
  51459. },
  51460. enumerable: true,
  51461. configurable: true
  51462. });
  51463. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  51464. /**
  51465. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  51466. */
  51467. get: function () {
  51468. var mousewheel = this.inputs.attached["mousewheel"];
  51469. if (mousewheel) {
  51470. return mousewheel.wheelPrecision;
  51471. }
  51472. return 0;
  51473. },
  51474. set: function (value) {
  51475. var mousewheel = this.inputs.attached["mousewheel"];
  51476. if (mousewheel) {
  51477. mousewheel.wheelPrecision = value;
  51478. }
  51479. },
  51480. enumerable: true,
  51481. configurable: true
  51482. });
  51483. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  51484. /**
  51485. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  51486. * It will be used instead of pinchDeltaPrecision if different from 0.
  51487. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  51488. */
  51489. get: function () {
  51490. var mousewheel = this.inputs.attached["mousewheel"];
  51491. if (mousewheel) {
  51492. return mousewheel.wheelDeltaPercentage;
  51493. }
  51494. return 0;
  51495. },
  51496. set: function (value) {
  51497. var mousewheel = this.inputs.attached["mousewheel"];
  51498. if (mousewheel) {
  51499. mousewheel.wheelDeltaPercentage = value;
  51500. }
  51501. },
  51502. enumerable: true,
  51503. configurable: true
  51504. });
  51505. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  51506. /**
  51507. * Gets the bouncing behavior of the camera if it has been enabled.
  51508. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  51509. */
  51510. get: function () {
  51511. return this._bouncingBehavior;
  51512. },
  51513. enumerable: true,
  51514. configurable: true
  51515. });
  51516. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  51517. /**
  51518. * Defines if the bouncing behavior of the camera is enabled on the camera.
  51519. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  51520. */
  51521. get: function () {
  51522. return this._bouncingBehavior != null;
  51523. },
  51524. set: function (value) {
  51525. if (value === this.useBouncingBehavior) {
  51526. return;
  51527. }
  51528. if (value) {
  51529. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  51530. this.addBehavior(this._bouncingBehavior);
  51531. }
  51532. else if (this._bouncingBehavior) {
  51533. this.removeBehavior(this._bouncingBehavior);
  51534. this._bouncingBehavior = null;
  51535. }
  51536. },
  51537. enumerable: true,
  51538. configurable: true
  51539. });
  51540. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  51541. /**
  51542. * Gets the framing behavior of the camera if it has been enabled.
  51543. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  51544. */
  51545. get: function () {
  51546. return this._framingBehavior;
  51547. },
  51548. enumerable: true,
  51549. configurable: true
  51550. });
  51551. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  51552. /**
  51553. * Defines if the framing behavior of the camera is enabled on the camera.
  51554. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  51555. */
  51556. get: function () {
  51557. return this._framingBehavior != null;
  51558. },
  51559. set: function (value) {
  51560. if (value === this.useFramingBehavior) {
  51561. return;
  51562. }
  51563. if (value) {
  51564. this._framingBehavior = new BABYLON.FramingBehavior();
  51565. this.addBehavior(this._framingBehavior);
  51566. }
  51567. else if (this._framingBehavior) {
  51568. this.removeBehavior(this._framingBehavior);
  51569. this._framingBehavior = null;
  51570. }
  51571. },
  51572. enumerable: true,
  51573. configurable: true
  51574. });
  51575. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  51576. /**
  51577. * Gets the auto rotation behavior of the camera if it has been enabled.
  51578. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  51579. */
  51580. get: function () {
  51581. return this._autoRotationBehavior;
  51582. },
  51583. enumerable: true,
  51584. configurable: true
  51585. });
  51586. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  51587. /**
  51588. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  51589. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  51590. */
  51591. get: function () {
  51592. return this._autoRotationBehavior != null;
  51593. },
  51594. set: function (value) {
  51595. if (value === this.useAutoRotationBehavior) {
  51596. return;
  51597. }
  51598. if (value) {
  51599. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  51600. this.addBehavior(this._autoRotationBehavior);
  51601. }
  51602. else if (this._autoRotationBehavior) {
  51603. this.removeBehavior(this._autoRotationBehavior);
  51604. this._autoRotationBehavior = null;
  51605. }
  51606. },
  51607. enumerable: true,
  51608. configurable: true
  51609. });
  51610. // Cache
  51611. /** @hidden */
  51612. ArcRotateCamera.prototype._initCache = function () {
  51613. _super.prototype._initCache.call(this);
  51614. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  51615. this._cache.alpha = undefined;
  51616. this._cache.beta = undefined;
  51617. this._cache.radius = undefined;
  51618. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  51619. };
  51620. /** @hidden */
  51621. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  51622. if (!ignoreParentClass) {
  51623. _super.prototype._updateCache.call(this);
  51624. }
  51625. this._cache._target.copyFrom(this._getTargetPosition());
  51626. this._cache.alpha = this.alpha;
  51627. this._cache.beta = this.beta;
  51628. this._cache.radius = this.radius;
  51629. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  51630. };
  51631. ArcRotateCamera.prototype._getTargetPosition = function () {
  51632. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  51633. var pos = this._targetHost.absolutePosition;
  51634. if (this._targetBoundingCenter) {
  51635. pos.addToRef(this._targetBoundingCenter, this._target);
  51636. }
  51637. else {
  51638. this._target.copyFrom(pos);
  51639. }
  51640. }
  51641. var lockedTargetPosition = this._getLockedTargetPosition();
  51642. if (lockedTargetPosition) {
  51643. return lockedTargetPosition;
  51644. }
  51645. return this._target;
  51646. };
  51647. /**
  51648. * Stores the current state of the camera (alpha, beta, radius and target)
  51649. * @returns the camera itself
  51650. */
  51651. ArcRotateCamera.prototype.storeState = function () {
  51652. this._storedAlpha = this.alpha;
  51653. this._storedBeta = this.beta;
  51654. this._storedRadius = this.radius;
  51655. this._storedTarget = this._getTargetPosition().clone();
  51656. return _super.prototype.storeState.call(this);
  51657. };
  51658. /**
  51659. * @hidden
  51660. * Restored camera state. You must call storeState() first
  51661. */
  51662. ArcRotateCamera.prototype._restoreStateValues = function () {
  51663. if (!_super.prototype._restoreStateValues.call(this)) {
  51664. return false;
  51665. }
  51666. this.alpha = this._storedAlpha;
  51667. this.beta = this._storedBeta;
  51668. this.radius = this._storedRadius;
  51669. this.setTarget(this._storedTarget.clone());
  51670. this.inertialAlphaOffset = 0;
  51671. this.inertialBetaOffset = 0;
  51672. this.inertialRadiusOffset = 0;
  51673. this.inertialPanningX = 0;
  51674. this.inertialPanningY = 0;
  51675. return true;
  51676. };
  51677. // Synchronized
  51678. /** @hidden */
  51679. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  51680. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  51681. return false;
  51682. }
  51683. return this._cache._target.equals(this._getTargetPosition())
  51684. && this._cache.alpha === this.alpha
  51685. && this._cache.beta === this.beta
  51686. && this._cache.radius === this.radius
  51687. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  51688. };
  51689. /**
  51690. * Attached controls to the current camera.
  51691. * @param element Defines the element the controls should be listened from
  51692. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  51693. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  51694. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  51695. */
  51696. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  51697. var _this = this;
  51698. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  51699. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  51700. this._useCtrlForPanning = useCtrlForPanning;
  51701. this._panningMouseButton = panningMouseButton;
  51702. this.inputs.attachElement(element, noPreventDefault);
  51703. this._reset = function () {
  51704. _this.inertialAlphaOffset = 0;
  51705. _this.inertialBetaOffset = 0;
  51706. _this.inertialRadiusOffset = 0;
  51707. _this.inertialPanningX = 0;
  51708. _this.inertialPanningY = 0;
  51709. };
  51710. };
  51711. /**
  51712. * Detach the current controls from the camera.
  51713. * The camera will stop reacting to inputs.
  51714. * @param element Defines the element to stop listening the inputs from
  51715. */
  51716. ArcRotateCamera.prototype.detachControl = function (element) {
  51717. this.inputs.detachElement(element);
  51718. if (this._reset) {
  51719. this._reset();
  51720. }
  51721. };
  51722. /** @hidden */
  51723. ArcRotateCamera.prototype._checkInputs = function () {
  51724. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  51725. if (this._collisionTriggered) {
  51726. return;
  51727. }
  51728. this.inputs.checkInputs();
  51729. // Inertia
  51730. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  51731. var inertialAlphaOffset = this.inertialAlphaOffset;
  51732. if (this.beta <= 0) {
  51733. inertialAlphaOffset *= -1;
  51734. }
  51735. if (this.getScene().useRightHandedSystem) {
  51736. inertialAlphaOffset *= -1;
  51737. }
  51738. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0) {
  51739. inertialAlphaOffset *= -1;
  51740. }
  51741. this.alpha += inertialAlphaOffset;
  51742. this.beta += this.inertialBetaOffset;
  51743. this.radius -= this.inertialRadiusOffset;
  51744. this.inertialAlphaOffset *= this.inertia;
  51745. this.inertialBetaOffset *= this.inertia;
  51746. this.inertialRadiusOffset *= this.inertia;
  51747. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon) {
  51748. this.inertialAlphaOffset = 0;
  51749. }
  51750. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon) {
  51751. this.inertialBetaOffset = 0;
  51752. }
  51753. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon) {
  51754. this.inertialRadiusOffset = 0;
  51755. }
  51756. }
  51757. // Panning inertia
  51758. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  51759. if (!this._localDirection) {
  51760. this._localDirection = BABYLON.Vector3.Zero();
  51761. this._transformedDirection = BABYLON.Vector3.Zero();
  51762. }
  51763. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  51764. this._localDirection.multiplyInPlace(this.panningAxis);
  51765. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  51766. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  51767. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  51768. if (!this.panningAxis.y) {
  51769. this._transformedDirection.y = 0;
  51770. }
  51771. if (!this._targetHost) {
  51772. if (this.panningDistanceLimit) {
  51773. this._transformedDirection.addInPlace(this._target);
  51774. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  51775. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  51776. this._target.copyFrom(this._transformedDirection);
  51777. }
  51778. }
  51779. else {
  51780. this._target.addInPlace(this._transformedDirection);
  51781. }
  51782. }
  51783. this.inertialPanningX *= this.panningInertia;
  51784. this.inertialPanningY *= this.panningInertia;
  51785. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon) {
  51786. this.inertialPanningX = 0;
  51787. }
  51788. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon) {
  51789. this.inertialPanningY = 0;
  51790. }
  51791. }
  51792. // Limits
  51793. this._checkLimits();
  51794. _super.prototype._checkInputs.call(this);
  51795. };
  51796. ArcRotateCamera.prototype._checkLimits = function () {
  51797. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  51798. if (this.allowUpsideDown && this.beta > Math.PI) {
  51799. this.beta = this.beta - (2 * Math.PI);
  51800. }
  51801. }
  51802. else {
  51803. if (this.beta < this.lowerBetaLimit) {
  51804. this.beta = this.lowerBetaLimit;
  51805. }
  51806. }
  51807. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  51808. if (this.allowUpsideDown && this.beta < -Math.PI) {
  51809. this.beta = this.beta + (2 * Math.PI);
  51810. }
  51811. }
  51812. else {
  51813. if (this.beta > this.upperBetaLimit) {
  51814. this.beta = this.upperBetaLimit;
  51815. }
  51816. }
  51817. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  51818. this.alpha = this.lowerAlphaLimit;
  51819. }
  51820. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  51821. this.alpha = this.upperAlphaLimit;
  51822. }
  51823. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  51824. this.radius = this.lowerRadiusLimit;
  51825. this.inertialRadiusOffset = 0;
  51826. }
  51827. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  51828. this.radius = this.upperRadiusLimit;
  51829. this.inertialRadiusOffset = 0;
  51830. }
  51831. };
  51832. /**
  51833. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  51834. */
  51835. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  51836. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  51837. this.radius = this._computationVector.length();
  51838. if (this.radius === 0) {
  51839. this.radius = 0.0001; // Just to avoid division by zero
  51840. }
  51841. // Alpha
  51842. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  51843. if (this._computationVector.z < 0) {
  51844. this.alpha = 2 * Math.PI - this.alpha;
  51845. }
  51846. // Beta
  51847. this.beta = Math.acos(this._computationVector.y / this.radius);
  51848. this._checkLimits();
  51849. };
  51850. /**
  51851. * Use a position to define the current camera related information like aplha, beta and radius
  51852. * @param position Defines the position to set the camera at
  51853. */
  51854. ArcRotateCamera.prototype.setPosition = function (position) {
  51855. if (this.position.equals(position)) {
  51856. return;
  51857. }
  51858. this.position.copyFrom(position);
  51859. this.rebuildAnglesAndRadius();
  51860. };
  51861. /**
  51862. * Defines the target the camera should look at.
  51863. * This will automatically adapt alpha beta and radius to fit within the new target.
  51864. * @param target Defines the new target as a Vector or a mesh
  51865. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  51866. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  51867. */
  51868. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  51869. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  51870. if (allowSamePosition === void 0) { allowSamePosition = false; }
  51871. if (target.getBoundingInfo) {
  51872. if (toBoundingCenter) {
  51873. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  51874. }
  51875. else {
  51876. this._targetBoundingCenter = null;
  51877. }
  51878. this._targetHost = target;
  51879. this._target = this._getTargetPosition();
  51880. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  51881. }
  51882. else {
  51883. var newTarget = target;
  51884. var currentTarget = this._getTargetPosition();
  51885. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  51886. return;
  51887. }
  51888. this._targetHost = null;
  51889. this._target = newTarget;
  51890. this._targetBoundingCenter = null;
  51891. this.onMeshTargetChangedObservable.notifyObservers(null);
  51892. }
  51893. this.rebuildAnglesAndRadius();
  51894. };
  51895. /** @hidden */
  51896. ArcRotateCamera.prototype._getViewMatrix = function () {
  51897. // Compute
  51898. var cosa = Math.cos(this.alpha);
  51899. var sina = Math.sin(this.alpha);
  51900. var cosb = Math.cos(this.beta);
  51901. var sinb = Math.sin(this.beta);
  51902. if (sinb === 0) {
  51903. sinb = 0.0001;
  51904. }
  51905. var target = this._getTargetPosition();
  51906. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  51907. target.addToRef(this._computationVector, this._newPosition);
  51908. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  51909. if (!this._collider) {
  51910. this._collider = new BABYLON.Collider();
  51911. }
  51912. this._collider._radius = this.collisionRadius;
  51913. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  51914. this._collisionTriggered = true;
  51915. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  51916. }
  51917. else {
  51918. this.position.copyFrom(this._newPosition);
  51919. var up = this.upVector;
  51920. if (this.allowUpsideDown && sinb < 0) {
  51921. up = up.clone();
  51922. up = up.negate();
  51923. }
  51924. this._computeViewMatrix(this.position, target, up);
  51925. this._viewMatrix.addAtIndex(12, this.targetScreenOffset.x);
  51926. this._viewMatrix.addAtIndex(13, this.targetScreenOffset.y);
  51927. }
  51928. this._currentTarget = target;
  51929. return this._viewMatrix;
  51930. };
  51931. /**
  51932. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  51933. * @param meshes Defines the mesh to zoom on
  51934. * @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)
  51935. */
  51936. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  51937. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  51938. meshes = meshes || this.getScene().meshes;
  51939. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  51940. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  51941. this.radius = distance * this.zoomOnFactor;
  51942. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  51943. };
  51944. /**
  51945. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  51946. * The target will be changed but the radius
  51947. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  51948. * @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)
  51949. */
  51950. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  51951. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  51952. var meshesOrMinMaxVector;
  51953. var distance;
  51954. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  51955. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  51956. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  51957. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  51958. }
  51959. else { //minMaxVector and distance
  51960. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  51961. meshesOrMinMaxVector = minMaxVectorAndDistance;
  51962. distance = minMaxVectorAndDistance.distance;
  51963. }
  51964. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  51965. if (!doNotUpdateMaxZ) {
  51966. this.maxZ = distance * 2;
  51967. }
  51968. };
  51969. /**
  51970. * @override
  51971. * Override Camera.createRigCamera
  51972. */
  51973. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  51974. var alphaShift = 0;
  51975. switch (this.cameraRigMode) {
  51976. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  51977. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  51978. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  51979. case BABYLON.Camera.RIG_MODE_VR:
  51980. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  51981. break;
  51982. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  51983. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  51984. break;
  51985. }
  51986. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  51987. rigCam._cameraRigParams = {};
  51988. return rigCam;
  51989. };
  51990. /**
  51991. * @hidden
  51992. * @override
  51993. * Override Camera._updateRigCameras
  51994. */
  51995. ArcRotateCamera.prototype._updateRigCameras = function () {
  51996. var camLeft = this._rigCameras[0];
  51997. var camRight = this._rigCameras[1];
  51998. camLeft.beta = camRight.beta = this.beta;
  51999. camLeft.radius = camRight.radius = this.radius;
  52000. switch (this.cameraRigMode) {
  52001. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  52002. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  52003. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  52004. case BABYLON.Camera.RIG_MODE_VR:
  52005. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  52006. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  52007. break;
  52008. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  52009. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  52010. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  52011. break;
  52012. }
  52013. _super.prototype._updateRigCameras.call(this);
  52014. };
  52015. /**
  52016. * Destroy the camera and release the current resources hold by it.
  52017. */
  52018. ArcRotateCamera.prototype.dispose = function () {
  52019. this.inputs.clear();
  52020. _super.prototype.dispose.call(this);
  52021. };
  52022. /**
  52023. * Gets the current object class name.
  52024. * @return the class name
  52025. */
  52026. ArcRotateCamera.prototype.getClassName = function () {
  52027. return "ArcRotateCamera";
  52028. };
  52029. __decorate([
  52030. BABYLON.serialize()
  52031. ], ArcRotateCamera.prototype, "alpha", void 0);
  52032. __decorate([
  52033. BABYLON.serialize()
  52034. ], ArcRotateCamera.prototype, "beta", void 0);
  52035. __decorate([
  52036. BABYLON.serialize()
  52037. ], ArcRotateCamera.prototype, "radius", void 0);
  52038. __decorate([
  52039. BABYLON.serializeAsVector3("target")
  52040. ], ArcRotateCamera.prototype, "_target", void 0);
  52041. __decorate([
  52042. BABYLON.serialize()
  52043. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  52044. __decorate([
  52045. BABYLON.serialize()
  52046. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  52047. __decorate([
  52048. BABYLON.serialize()
  52049. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  52050. __decorate([
  52051. BABYLON.serialize()
  52052. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  52053. __decorate([
  52054. BABYLON.serialize()
  52055. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  52056. __decorate([
  52057. BABYLON.serialize()
  52058. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  52059. __decorate([
  52060. BABYLON.serialize()
  52061. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  52062. __decorate([
  52063. BABYLON.serialize()
  52064. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  52065. __decorate([
  52066. BABYLON.serialize()
  52067. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  52068. __decorate([
  52069. BABYLON.serialize()
  52070. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  52071. __decorate([
  52072. BABYLON.serialize()
  52073. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  52074. __decorate([
  52075. BABYLON.serialize()
  52076. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  52077. __decorate([
  52078. BABYLON.serialize()
  52079. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  52080. __decorate([
  52081. BABYLON.serializeAsVector3()
  52082. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  52083. __decorate([
  52084. BABYLON.serialize()
  52085. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  52086. __decorate([
  52087. BABYLON.serialize()
  52088. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  52089. __decorate([
  52090. BABYLON.serialize()
  52091. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  52092. __decorate([
  52093. BABYLON.serialize()
  52094. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  52095. __decorate([
  52096. BABYLON.serialize()
  52097. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  52098. return ArcRotateCamera;
  52099. }(BABYLON.TargetCamera));
  52100. BABYLON.ArcRotateCamera = ArcRotateCamera;
  52101. })(BABYLON || (BABYLON = {}));
  52102. //# sourceMappingURL=arcRotateCamera.js.map
  52103. var BABYLON;
  52104. (function (BABYLON) {
  52105. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  52106. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  52107. });
  52108. /**
  52109. * The HemisphericLight simulates the ambient environment light,
  52110. * so the passed direction is the light reflection direction, not the incoming direction.
  52111. */
  52112. var HemisphericLight = /** @class */ (function (_super) {
  52113. __extends(HemisphericLight, _super);
  52114. /**
  52115. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  52116. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  52117. * The HemisphericLight can't cast shadows.
  52118. * Documentation : http://doc.babylonjs.com/tutorials/lights
  52119. * @param name The friendly name of the light
  52120. * @param direction The direction of the light reflection
  52121. * @param scene The scene the light belongs to
  52122. */
  52123. function HemisphericLight(name, direction, scene) {
  52124. var _this = _super.call(this, name, scene) || this;
  52125. /**
  52126. * The groundColor is the light in the opposite direction to the one specified during creation.
  52127. * 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.
  52128. */
  52129. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  52130. _this.direction = direction || BABYLON.Vector3.Up();
  52131. return _this;
  52132. }
  52133. HemisphericLight.prototype._buildUniformLayout = function () {
  52134. this._uniformBuffer.addUniform("vLightData", 4);
  52135. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  52136. this._uniformBuffer.addUniform("vLightSpecular", 3);
  52137. this._uniformBuffer.addUniform("vLightGround", 3);
  52138. this._uniformBuffer.addUniform("shadowsInfo", 3);
  52139. this._uniformBuffer.addUniform("depthValues", 2);
  52140. this._uniformBuffer.create();
  52141. };
  52142. /**
  52143. * Returns the string "HemisphericLight".
  52144. * @return The class name
  52145. */
  52146. HemisphericLight.prototype.getClassName = function () {
  52147. return "HemisphericLight";
  52148. };
  52149. /**
  52150. * Sets the HemisphericLight direction towards the passed target (Vector3).
  52151. * Returns the updated direction.
  52152. * @param target The target the direction should point to
  52153. * @return The computed direction
  52154. */
  52155. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  52156. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  52157. return this.direction;
  52158. };
  52159. /**
  52160. * Returns the shadow generator associated to the light.
  52161. * @returns Always null for hemispheric lights because it does not support shadows.
  52162. */
  52163. HemisphericLight.prototype.getShadowGenerator = function () {
  52164. return null;
  52165. };
  52166. /**
  52167. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  52168. * @param effect The effect to update
  52169. * @param lightIndex The index of the light in the effect to update
  52170. * @returns The hemispheric light
  52171. */
  52172. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  52173. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  52174. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  52175. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  52176. return this;
  52177. };
  52178. /**
  52179. * Computes the world matrix of the node
  52180. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  52181. * @param useWasUpdatedFlag defines a reserved property
  52182. * @returns the world matrix
  52183. */
  52184. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  52185. if (!this._worldMatrix) {
  52186. this._worldMatrix = BABYLON.Matrix.Identity();
  52187. }
  52188. return this._worldMatrix;
  52189. };
  52190. /**
  52191. * Returns the integer 3.
  52192. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  52193. */
  52194. HemisphericLight.prototype.getTypeID = function () {
  52195. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  52196. };
  52197. /**
  52198. * Prepares the list of defines specific to the light type.
  52199. * @param defines the list of defines
  52200. * @param lightIndex defines the index of the light for the effect
  52201. */
  52202. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  52203. defines["HEMILIGHT" + lightIndex] = true;
  52204. };
  52205. __decorate([
  52206. BABYLON.serializeAsColor3()
  52207. ], HemisphericLight.prototype, "groundColor", void 0);
  52208. __decorate([
  52209. BABYLON.serializeAsVector3()
  52210. ], HemisphericLight.prototype, "direction", void 0);
  52211. return HemisphericLight;
  52212. }(BABYLON.Light));
  52213. BABYLON.HemisphericLight = HemisphericLight;
  52214. })(BABYLON || (BABYLON = {}));
  52215. //# sourceMappingURL=hemisphericLight.js.map
  52216. var BABYLON;
  52217. (function (BABYLON) {
  52218. /**
  52219. * Base implementation IShadowLight
  52220. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  52221. */
  52222. var ShadowLight = /** @class */ (function (_super) {
  52223. __extends(ShadowLight, _super);
  52224. function ShadowLight() {
  52225. var _this = _super !== null && _super.apply(this, arguments) || this;
  52226. _this._needProjectionMatrixCompute = true;
  52227. return _this;
  52228. }
  52229. ShadowLight.prototype._setPosition = function (value) {
  52230. this._position = value;
  52231. };
  52232. Object.defineProperty(ShadowLight.prototype, "position", {
  52233. /**
  52234. * Sets the position the shadow will be casted from. Also use as the light position for both
  52235. * point and spot lights.
  52236. */
  52237. get: function () {
  52238. return this._position;
  52239. },
  52240. /**
  52241. * Sets the position the shadow will be casted from. Also use as the light position for both
  52242. * point and spot lights.
  52243. */
  52244. set: function (value) {
  52245. this._setPosition(value);
  52246. },
  52247. enumerable: true,
  52248. configurable: true
  52249. });
  52250. ShadowLight.prototype._setDirection = function (value) {
  52251. this._direction = value;
  52252. };
  52253. Object.defineProperty(ShadowLight.prototype, "direction", {
  52254. /**
  52255. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  52256. * Also use as the light direction on spot and directional lights.
  52257. */
  52258. get: function () {
  52259. return this._direction;
  52260. },
  52261. /**
  52262. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  52263. * Also use as the light direction on spot and directional lights.
  52264. */
  52265. set: function (value) {
  52266. this._setDirection(value);
  52267. },
  52268. enumerable: true,
  52269. configurable: true
  52270. });
  52271. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  52272. /**
  52273. * Gets the shadow projection clipping minimum z value.
  52274. */
  52275. get: function () {
  52276. return this._shadowMinZ;
  52277. },
  52278. /**
  52279. * Sets the shadow projection clipping minimum z value.
  52280. */
  52281. set: function (value) {
  52282. this._shadowMinZ = value;
  52283. this.forceProjectionMatrixCompute();
  52284. },
  52285. enumerable: true,
  52286. configurable: true
  52287. });
  52288. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  52289. /**
  52290. * Sets the shadow projection clipping maximum z value.
  52291. */
  52292. get: function () {
  52293. return this._shadowMaxZ;
  52294. },
  52295. /**
  52296. * Gets the shadow projection clipping maximum z value.
  52297. */
  52298. set: function (value) {
  52299. this._shadowMaxZ = value;
  52300. this.forceProjectionMatrixCompute();
  52301. },
  52302. enumerable: true,
  52303. configurable: true
  52304. });
  52305. /**
  52306. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  52307. * @returns true if the information has been computed, false if it does not need to (no parenting)
  52308. */
  52309. ShadowLight.prototype.computeTransformedInformation = function () {
  52310. if (this.parent && this.parent.getWorldMatrix) {
  52311. if (!this.transformedPosition) {
  52312. this.transformedPosition = BABYLON.Vector3.Zero();
  52313. }
  52314. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  52315. // In case the direction is present.
  52316. if (this.direction) {
  52317. if (!this.transformedDirection) {
  52318. this.transformedDirection = BABYLON.Vector3.Zero();
  52319. }
  52320. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  52321. }
  52322. return true;
  52323. }
  52324. return false;
  52325. };
  52326. /**
  52327. * Return the depth scale used for the shadow map.
  52328. * @returns the depth scale.
  52329. */
  52330. ShadowLight.prototype.getDepthScale = function () {
  52331. return 50.0;
  52332. };
  52333. /**
  52334. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  52335. * @param faceIndex The index of the face we are computed the direction to generate shadow
  52336. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  52337. */
  52338. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  52339. return this.transformedDirection ? this.transformedDirection : this.direction;
  52340. };
  52341. /**
  52342. * Returns the ShadowLight absolute position in the World.
  52343. * @returns the position vector in world space
  52344. */
  52345. ShadowLight.prototype.getAbsolutePosition = function () {
  52346. return this.transformedPosition ? this.transformedPosition : this.position;
  52347. };
  52348. /**
  52349. * Sets the ShadowLight direction toward the passed target.
  52350. * @param target The point tot target in local space
  52351. * @returns the updated ShadowLight direction
  52352. */
  52353. ShadowLight.prototype.setDirectionToTarget = function (target) {
  52354. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  52355. return this.direction;
  52356. };
  52357. /**
  52358. * Returns the light rotation in euler definition.
  52359. * @returns the x y z rotation in local space.
  52360. */
  52361. ShadowLight.prototype.getRotation = function () {
  52362. this.direction.normalize();
  52363. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  52364. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  52365. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  52366. };
  52367. /**
  52368. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  52369. * @returns true if a cube texture needs to be use
  52370. */
  52371. ShadowLight.prototype.needCube = function () {
  52372. return false;
  52373. };
  52374. /**
  52375. * Detects if the projection matrix requires to be recomputed this frame.
  52376. * @returns true if it requires to be recomputed otherwise, false.
  52377. */
  52378. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  52379. return this._needProjectionMatrixCompute;
  52380. };
  52381. /**
  52382. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  52383. */
  52384. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  52385. this._needProjectionMatrixCompute = true;
  52386. };
  52387. /** @hidden */
  52388. ShadowLight.prototype._initCache = function () {
  52389. _super.prototype._initCache.call(this);
  52390. this._cache.position = BABYLON.Vector3.Zero();
  52391. };
  52392. /** @hidden */
  52393. ShadowLight.prototype._isSynchronized = function () {
  52394. if (!this._cache.position.equals(this.position)) {
  52395. return false;
  52396. }
  52397. return true;
  52398. };
  52399. /**
  52400. * Computes the world matrix of the node
  52401. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  52402. * @returns the world matrix
  52403. */
  52404. ShadowLight.prototype.computeWorldMatrix = function (force) {
  52405. if (!force && this.isSynchronized()) {
  52406. this._currentRenderId = this.getScene().getRenderId();
  52407. return this._worldMatrix;
  52408. }
  52409. this._updateCache();
  52410. this._cache.position.copyFrom(this.position);
  52411. if (!this._worldMatrix) {
  52412. this._worldMatrix = BABYLON.Matrix.Identity();
  52413. }
  52414. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  52415. if (this.parent && this.parent.getWorldMatrix) {
  52416. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  52417. this._markSyncedWithParent();
  52418. }
  52419. // Cache the determinant
  52420. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  52421. return this._worldMatrix;
  52422. };
  52423. /**
  52424. * Gets the minZ used for shadow according to both the scene and the light.
  52425. * @param activeCamera The camera we are returning the min for
  52426. * @returns the depth min z
  52427. */
  52428. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  52429. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  52430. };
  52431. /**
  52432. * Gets the maxZ used for shadow according to both the scene and the light.
  52433. * @param activeCamera The camera we are returning the max for
  52434. * @returns the depth max z
  52435. */
  52436. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  52437. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  52438. };
  52439. /**
  52440. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  52441. * @param matrix The materix to updated with the projection information
  52442. * @param viewMatrix The transform matrix of the light
  52443. * @param renderList The list of mesh to render in the map
  52444. * @returns The current light
  52445. */
  52446. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  52447. if (this.customProjectionMatrixBuilder) {
  52448. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  52449. }
  52450. else {
  52451. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  52452. }
  52453. return this;
  52454. };
  52455. __decorate([
  52456. BABYLON.serializeAsVector3()
  52457. ], ShadowLight.prototype, "position", null);
  52458. __decorate([
  52459. BABYLON.serializeAsVector3()
  52460. ], ShadowLight.prototype, "direction", null);
  52461. __decorate([
  52462. BABYLON.serialize()
  52463. ], ShadowLight.prototype, "shadowMinZ", null);
  52464. __decorate([
  52465. BABYLON.serialize()
  52466. ], ShadowLight.prototype, "shadowMaxZ", null);
  52467. return ShadowLight;
  52468. }(BABYLON.Light));
  52469. BABYLON.ShadowLight = ShadowLight;
  52470. })(BABYLON || (BABYLON = {}));
  52471. //# sourceMappingURL=shadowLight.js.map
  52472. var BABYLON;
  52473. (function (BABYLON) {
  52474. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  52475. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  52476. });
  52477. /**
  52478. * A point light is a light defined by an unique point in world space.
  52479. * The light is emitted in every direction from this point.
  52480. * A good example of a point light is a standard light bulb.
  52481. * Documentation: https://doc.babylonjs.com/babylon101/lights
  52482. */
  52483. var PointLight = /** @class */ (function (_super) {
  52484. __extends(PointLight, _super);
  52485. /**
  52486. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  52487. * A PointLight emits the light in every direction.
  52488. * It can cast shadows.
  52489. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  52490. * ```javascript
  52491. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  52492. * ```
  52493. * Documentation : http://doc.babylonjs.com/tutorials/lights
  52494. * @param name The light friendly name
  52495. * @param position The position of the point light in the scene
  52496. * @param scene The scene the lights belongs to
  52497. */
  52498. function PointLight(name, position, scene) {
  52499. var _this = _super.call(this, name, scene) || this;
  52500. _this._shadowAngle = Math.PI / 2;
  52501. _this.position = position;
  52502. return _this;
  52503. }
  52504. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  52505. /**
  52506. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  52507. * This specifies what angle the shadow will use to be created.
  52508. *
  52509. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  52510. */
  52511. get: function () {
  52512. return this._shadowAngle;
  52513. },
  52514. /**
  52515. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  52516. * This specifies what angle the shadow will use to be created.
  52517. *
  52518. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  52519. */
  52520. set: function (value) {
  52521. this._shadowAngle = value;
  52522. this.forceProjectionMatrixCompute();
  52523. },
  52524. enumerable: true,
  52525. configurable: true
  52526. });
  52527. Object.defineProperty(PointLight.prototype, "direction", {
  52528. /**
  52529. * Gets the direction if it has been set.
  52530. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  52531. */
  52532. get: function () {
  52533. return this._direction;
  52534. },
  52535. /**
  52536. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  52537. */
  52538. set: function (value) {
  52539. var previousNeedCube = this.needCube();
  52540. this._direction = value;
  52541. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  52542. this._shadowGenerator.recreateShadowMap();
  52543. }
  52544. },
  52545. enumerable: true,
  52546. configurable: true
  52547. });
  52548. /**
  52549. * Returns the string "PointLight"
  52550. * @returns the class name
  52551. */
  52552. PointLight.prototype.getClassName = function () {
  52553. return "PointLight";
  52554. };
  52555. /**
  52556. * Returns the integer 0.
  52557. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  52558. */
  52559. PointLight.prototype.getTypeID = function () {
  52560. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  52561. };
  52562. /**
  52563. * Specifies wether or not the shadowmap should be a cube texture.
  52564. * @returns true if the shadowmap needs to be a cube texture.
  52565. */
  52566. PointLight.prototype.needCube = function () {
  52567. return !this.direction;
  52568. };
  52569. /**
  52570. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  52571. * @param faceIndex The index of the face we are computed the direction to generate shadow
  52572. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  52573. */
  52574. PointLight.prototype.getShadowDirection = function (faceIndex) {
  52575. if (this.direction) {
  52576. return _super.prototype.getShadowDirection.call(this, faceIndex);
  52577. }
  52578. else {
  52579. switch (faceIndex) {
  52580. case 0:
  52581. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  52582. case 1:
  52583. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  52584. case 2:
  52585. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  52586. case 3:
  52587. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  52588. case 4:
  52589. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  52590. case 5:
  52591. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  52592. }
  52593. }
  52594. return BABYLON.Vector3.Zero();
  52595. };
  52596. /**
  52597. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  52598. * - fov = PI / 2
  52599. * - aspect ratio : 1.0
  52600. * - z-near and far equal to the active camera minZ and maxZ.
  52601. * Returns the PointLight.
  52602. */
  52603. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  52604. var activeCamera = this.getScene().activeCamera;
  52605. if (!activeCamera) {
  52606. return;
  52607. }
  52608. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  52609. };
  52610. PointLight.prototype._buildUniformLayout = function () {
  52611. this._uniformBuffer.addUniform("vLightData", 4);
  52612. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  52613. this._uniformBuffer.addUniform("vLightSpecular", 3);
  52614. this._uniformBuffer.addUniform("vLightFalloff", 4);
  52615. this._uniformBuffer.addUniform("shadowsInfo", 3);
  52616. this._uniformBuffer.addUniform("depthValues", 2);
  52617. this._uniformBuffer.create();
  52618. };
  52619. /**
  52620. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  52621. * @param effect The effect to update
  52622. * @param lightIndex The index of the light in the effect to update
  52623. * @returns The point light
  52624. */
  52625. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  52626. if (this.computeTransformedInformation()) {
  52627. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  52628. }
  52629. else {
  52630. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  52631. }
  52632. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  52633. return this;
  52634. };
  52635. /**
  52636. * Prepares the list of defines specific to the light type.
  52637. * @param defines the list of defines
  52638. * @param lightIndex defines the index of the light for the effect
  52639. */
  52640. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  52641. defines["POINTLIGHT" + lightIndex] = true;
  52642. };
  52643. __decorate([
  52644. BABYLON.serialize()
  52645. ], PointLight.prototype, "shadowAngle", null);
  52646. return PointLight;
  52647. }(BABYLON.ShadowLight));
  52648. BABYLON.PointLight = PointLight;
  52649. })(BABYLON || (BABYLON = {}));
  52650. //# sourceMappingURL=pointLight.js.map
  52651. var BABYLON;
  52652. (function (BABYLON) {
  52653. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  52654. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  52655. });
  52656. /**
  52657. * A directional light is defined by a direction (what a surprise!).
  52658. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  52659. * 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.
  52660. * Documentation: https://doc.babylonjs.com/babylon101/lights
  52661. */
  52662. var DirectionalLight = /** @class */ (function (_super) {
  52663. __extends(DirectionalLight, _super);
  52664. /**
  52665. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  52666. * The directional light is emitted from everywhere in the given direction.
  52667. * It can cast shadows.
  52668. * Documentation : http://doc.babylonjs.com/tutorials/lights
  52669. * @param name The friendly name of the light
  52670. * @param direction The direction of the light
  52671. * @param scene The scene the light belongs to
  52672. */
  52673. function DirectionalLight(name, direction, scene) {
  52674. var _this = _super.call(this, name, scene) || this;
  52675. _this._shadowFrustumSize = 0;
  52676. _this._shadowOrthoScale = 0.1;
  52677. /**
  52678. * Automatically compute the projection matrix to best fit (including all the casters)
  52679. * on each frame.
  52680. */
  52681. _this.autoUpdateExtends = true;
  52682. // Cache
  52683. _this._orthoLeft = Number.MAX_VALUE;
  52684. _this._orthoRight = Number.MIN_VALUE;
  52685. _this._orthoTop = Number.MIN_VALUE;
  52686. _this._orthoBottom = Number.MAX_VALUE;
  52687. _this.position = direction.scale(-1.0);
  52688. _this.direction = direction;
  52689. return _this;
  52690. }
  52691. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  52692. /**
  52693. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  52694. */
  52695. get: function () {
  52696. return this._shadowFrustumSize;
  52697. },
  52698. /**
  52699. * Specifies a fix frustum size for the shadow generation.
  52700. */
  52701. set: function (value) {
  52702. this._shadowFrustumSize = value;
  52703. this.forceProjectionMatrixCompute();
  52704. },
  52705. enumerable: true,
  52706. configurable: true
  52707. });
  52708. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  52709. /**
  52710. * Gets the shadow projection scale against the optimal computed one.
  52711. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  52712. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  52713. */
  52714. get: function () {
  52715. return this._shadowOrthoScale;
  52716. },
  52717. /**
  52718. * Sets the shadow projection scale against the optimal computed one.
  52719. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  52720. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  52721. */
  52722. set: function (value) {
  52723. this._shadowOrthoScale = value;
  52724. this.forceProjectionMatrixCompute();
  52725. },
  52726. enumerable: true,
  52727. configurable: true
  52728. });
  52729. /**
  52730. * Returns the string "DirectionalLight".
  52731. * @return The class name
  52732. */
  52733. DirectionalLight.prototype.getClassName = function () {
  52734. return "DirectionalLight";
  52735. };
  52736. /**
  52737. * Returns the integer 1.
  52738. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  52739. */
  52740. DirectionalLight.prototype.getTypeID = function () {
  52741. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  52742. };
  52743. /**
  52744. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  52745. * Returns the DirectionalLight Shadow projection matrix.
  52746. */
  52747. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  52748. if (this.shadowFrustumSize > 0) {
  52749. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  52750. }
  52751. else {
  52752. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  52753. }
  52754. };
  52755. /**
  52756. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  52757. * Returns the DirectionalLight Shadow projection matrix.
  52758. */
  52759. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  52760. var activeCamera = this.getScene().activeCamera;
  52761. if (!activeCamera) {
  52762. return;
  52763. }
  52764. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  52765. };
  52766. /**
  52767. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  52768. * Returns the DirectionalLight Shadow projection matrix.
  52769. */
  52770. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  52771. var activeCamera = this.getScene().activeCamera;
  52772. if (!activeCamera) {
  52773. return;
  52774. }
  52775. // Check extends
  52776. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  52777. var tempVector3 = BABYLON.Vector3.Zero();
  52778. this._orthoLeft = Number.MAX_VALUE;
  52779. this._orthoRight = Number.MIN_VALUE;
  52780. this._orthoTop = Number.MIN_VALUE;
  52781. this._orthoBottom = Number.MAX_VALUE;
  52782. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  52783. var mesh = renderList[meshIndex];
  52784. if (!mesh) {
  52785. continue;
  52786. }
  52787. var boundingInfo = mesh.getBoundingInfo();
  52788. var boundingBox = boundingInfo.boundingBox;
  52789. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  52790. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  52791. if (tempVector3.x < this._orthoLeft) {
  52792. this._orthoLeft = tempVector3.x;
  52793. }
  52794. if (tempVector3.y < this._orthoBottom) {
  52795. this._orthoBottom = tempVector3.y;
  52796. }
  52797. if (tempVector3.x > this._orthoRight) {
  52798. this._orthoRight = tempVector3.x;
  52799. }
  52800. if (tempVector3.y > this._orthoTop) {
  52801. this._orthoTop = tempVector3.y;
  52802. }
  52803. }
  52804. }
  52805. }
  52806. var xOffset = this._orthoRight - this._orthoLeft;
  52807. var yOffset = this._orthoTop - this._orthoBottom;
  52808. 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);
  52809. };
  52810. DirectionalLight.prototype._buildUniformLayout = function () {
  52811. this._uniformBuffer.addUniform("vLightData", 4);
  52812. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  52813. this._uniformBuffer.addUniform("vLightSpecular", 3);
  52814. this._uniformBuffer.addUniform("shadowsInfo", 3);
  52815. this._uniformBuffer.addUniform("depthValues", 2);
  52816. this._uniformBuffer.create();
  52817. };
  52818. /**
  52819. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  52820. * @param effect The effect to update
  52821. * @param lightIndex The index of the light in the effect to update
  52822. * @returns The directional light
  52823. */
  52824. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  52825. if (this.computeTransformedInformation()) {
  52826. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  52827. return this;
  52828. }
  52829. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  52830. return this;
  52831. };
  52832. /**
  52833. * Gets the minZ used for shadow according to both the scene and the light.
  52834. *
  52835. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  52836. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  52837. * @param activeCamera The camera we are returning the min for
  52838. * @returns the depth min z
  52839. */
  52840. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  52841. return 1;
  52842. };
  52843. /**
  52844. * Gets the maxZ used for shadow according to both the scene and the light.
  52845. *
  52846. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  52847. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  52848. * @param activeCamera The camera we are returning the max for
  52849. * @returns the depth max z
  52850. */
  52851. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  52852. return 1;
  52853. };
  52854. /**
  52855. * Prepares the list of defines specific to the light type.
  52856. * @param defines the list of defines
  52857. * @param lightIndex defines the index of the light for the effect
  52858. */
  52859. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  52860. defines["DIRLIGHT" + lightIndex] = true;
  52861. };
  52862. __decorate([
  52863. BABYLON.serialize()
  52864. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  52865. __decorate([
  52866. BABYLON.serialize()
  52867. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  52868. __decorate([
  52869. BABYLON.serialize()
  52870. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  52871. return DirectionalLight;
  52872. }(BABYLON.ShadowLight));
  52873. BABYLON.DirectionalLight = DirectionalLight;
  52874. })(BABYLON || (BABYLON = {}));
  52875. //# sourceMappingURL=directionalLight.js.map
  52876. var BABYLON;
  52877. (function (BABYLON) {
  52878. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  52879. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  52880. });
  52881. /**
  52882. * A spot light is defined by a position, a direction, an angle, and an exponent.
  52883. * These values define a cone of light starting from the position, emitting toward the direction.
  52884. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  52885. * and the exponent defines the speed of the decay of the light with distance (reach).
  52886. * Documentation: https://doc.babylonjs.com/babylon101/lights
  52887. */
  52888. var SpotLight = /** @class */ (function (_super) {
  52889. __extends(SpotLight, _super);
  52890. /**
  52891. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  52892. * It can cast shadows.
  52893. * Documentation : http://doc.babylonjs.com/tutorials/lights
  52894. * @param name The light friendly name
  52895. * @param position The position of the spot light in the scene
  52896. * @param direction The direction of the light in the scene
  52897. * @param angle The cone angle of the light in Radians
  52898. * @param exponent The light decay speed with the distance from the emission spot
  52899. * @param scene The scene the lights belongs to
  52900. */
  52901. function SpotLight(name, position, direction, angle, exponent, scene) {
  52902. var _this = _super.call(this, name, scene) || this;
  52903. _this._innerAngle = 0;
  52904. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  52905. _this._projectionTextureLightNear = 1e-6;
  52906. _this._projectionTextureLightFar = 1000.0;
  52907. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  52908. _this._projectionTextureViewLightDirty = true;
  52909. _this._projectionTextureProjectionLightDirty = true;
  52910. _this._projectionTextureDirty = true;
  52911. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  52912. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  52913. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  52914. _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);
  52915. _this.position = position;
  52916. _this.direction = direction;
  52917. _this.angle = angle;
  52918. _this.exponent = exponent;
  52919. return _this;
  52920. }
  52921. Object.defineProperty(SpotLight.prototype, "angle", {
  52922. /**
  52923. * Gets the cone angle of the spot light in Radians.
  52924. */
  52925. get: function () {
  52926. return this._angle;
  52927. },
  52928. /**
  52929. * Sets the cone angle of the spot light in Radians.
  52930. */
  52931. set: function (value) {
  52932. this._angle = value;
  52933. this._cosHalfAngle = Math.cos(value * 0.5);
  52934. this._projectionTextureProjectionLightDirty = true;
  52935. this.forceProjectionMatrixCompute();
  52936. this._computeAngleValues();
  52937. },
  52938. enumerable: true,
  52939. configurable: true
  52940. });
  52941. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  52942. /**
  52943. * Only used in gltf falloff mode, this defines the angle where
  52944. * the directional falloff will start before cutting at angle which could be seen
  52945. * as outer angle.
  52946. */
  52947. get: function () {
  52948. return this._innerAngle;
  52949. },
  52950. /**
  52951. * Only used in gltf falloff mode, this defines the angle where
  52952. * the directional falloff will start before cutting at angle which could be seen
  52953. * as outer angle.
  52954. */
  52955. set: function (value) {
  52956. this._innerAngle = value;
  52957. this._computeAngleValues();
  52958. },
  52959. enumerable: true,
  52960. configurable: true
  52961. });
  52962. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  52963. /**
  52964. * Allows scaling the angle of the light for shadow generation only.
  52965. */
  52966. get: function () {
  52967. return this._shadowAngleScale;
  52968. },
  52969. /**
  52970. * Allows scaling the angle of the light for shadow generation only.
  52971. */
  52972. set: function (value) {
  52973. this._shadowAngleScale = value;
  52974. this.forceProjectionMatrixCompute();
  52975. },
  52976. enumerable: true,
  52977. configurable: true
  52978. });
  52979. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  52980. /**
  52981. * Allows reading the projecton texture
  52982. */
  52983. get: function () {
  52984. return this._projectionTextureMatrix;
  52985. },
  52986. enumerable: true,
  52987. configurable: true
  52988. });
  52989. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  52990. /**
  52991. * Gets the near clip of the Spotlight for texture projection.
  52992. */
  52993. get: function () {
  52994. return this._projectionTextureLightNear;
  52995. },
  52996. /**
  52997. * Sets the near clip of the Spotlight for texture projection.
  52998. */
  52999. set: function (value) {
  53000. this._projectionTextureLightNear = value;
  53001. this._projectionTextureProjectionLightDirty = true;
  53002. },
  53003. enumerable: true,
  53004. configurable: true
  53005. });
  53006. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  53007. /**
  53008. * Gets the far clip of the Spotlight for texture projection.
  53009. */
  53010. get: function () {
  53011. return this._projectionTextureLightFar;
  53012. },
  53013. /**
  53014. * Sets the far clip of the Spotlight for texture projection.
  53015. */
  53016. set: function (value) {
  53017. this._projectionTextureLightFar = value;
  53018. this._projectionTextureProjectionLightDirty = true;
  53019. },
  53020. enumerable: true,
  53021. configurable: true
  53022. });
  53023. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  53024. /**
  53025. * Gets the Up vector of the Spotlight for texture projection.
  53026. */
  53027. get: function () {
  53028. return this._projectionTextureUpDirection;
  53029. },
  53030. /**
  53031. * Sets the Up vector of the Spotlight for texture projection.
  53032. */
  53033. set: function (value) {
  53034. this._projectionTextureUpDirection = value;
  53035. this._projectionTextureProjectionLightDirty = true;
  53036. },
  53037. enumerable: true,
  53038. configurable: true
  53039. });
  53040. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  53041. /**
  53042. * Gets the projection texture of the light.
  53043. */
  53044. get: function () {
  53045. return this._projectionTexture;
  53046. },
  53047. /**
  53048. * Sets the projection texture of the light.
  53049. */
  53050. set: function (value) {
  53051. this._projectionTexture = value;
  53052. this._projectionTextureDirty = true;
  53053. },
  53054. enumerable: true,
  53055. configurable: true
  53056. });
  53057. /**
  53058. * Returns the string "SpotLight".
  53059. * @returns the class name
  53060. */
  53061. SpotLight.prototype.getClassName = function () {
  53062. return "SpotLight";
  53063. };
  53064. /**
  53065. * Returns the integer 2.
  53066. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  53067. */
  53068. SpotLight.prototype.getTypeID = function () {
  53069. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  53070. };
  53071. /**
  53072. * Overrides the direction setter to recompute the projection texture view light Matrix.
  53073. */
  53074. SpotLight.prototype._setDirection = function (value) {
  53075. _super.prototype._setDirection.call(this, value);
  53076. this._projectionTextureViewLightDirty = true;
  53077. };
  53078. /**
  53079. * Overrides the position setter to recompute the projection texture view light Matrix.
  53080. */
  53081. SpotLight.prototype._setPosition = function (value) {
  53082. _super.prototype._setPosition.call(this, value);
  53083. this._projectionTextureViewLightDirty = true;
  53084. };
  53085. /**
  53086. * 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.
  53087. * Returns the SpotLight.
  53088. */
  53089. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  53090. var activeCamera = this.getScene().activeCamera;
  53091. if (!activeCamera) {
  53092. return;
  53093. }
  53094. this._shadowAngleScale = this._shadowAngleScale || 1;
  53095. var angle = this._shadowAngleScale * this._angle;
  53096. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  53097. };
  53098. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  53099. this._projectionTextureViewLightDirty = false;
  53100. this._projectionTextureDirty = true;
  53101. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  53102. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  53103. };
  53104. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  53105. this._projectionTextureProjectionLightDirty = false;
  53106. this._projectionTextureDirty = true;
  53107. var light_far = this.projectionTextureLightFar;
  53108. var light_near = this.projectionTextureLightNear;
  53109. var P = light_far / (light_far - light_near);
  53110. var Q = -P * light_near;
  53111. var S = 1.0 / Math.tan(this._angle / 2.0);
  53112. var A = 1.0;
  53113. 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);
  53114. };
  53115. /**
  53116. * Main function for light texture projection matrix computing.
  53117. */
  53118. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  53119. this._projectionTextureDirty = false;
  53120. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  53121. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  53122. };
  53123. SpotLight.prototype._buildUniformLayout = function () {
  53124. this._uniformBuffer.addUniform("vLightData", 4);
  53125. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  53126. this._uniformBuffer.addUniform("vLightSpecular", 3);
  53127. this._uniformBuffer.addUniform("vLightDirection", 3);
  53128. this._uniformBuffer.addUniform("vLightFalloff", 4);
  53129. this._uniformBuffer.addUniform("shadowsInfo", 3);
  53130. this._uniformBuffer.addUniform("depthValues", 2);
  53131. this._uniformBuffer.create();
  53132. };
  53133. SpotLight.prototype._computeAngleValues = function () {
  53134. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  53135. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  53136. };
  53137. /**
  53138. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  53139. * @param effect The effect to update
  53140. * @param lightIndex The index of the light in the effect to update
  53141. * @returns The spot light
  53142. */
  53143. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  53144. var normalizeDirection;
  53145. if (this.computeTransformedInformation()) {
  53146. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  53147. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  53148. }
  53149. else {
  53150. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  53151. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  53152. }
  53153. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  53154. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  53155. if (this.projectionTexture && this.projectionTexture.isReady()) {
  53156. if (this._projectionTextureViewLightDirty) {
  53157. this._computeProjectionTextureViewLightMatrix();
  53158. }
  53159. if (this._projectionTextureProjectionLightDirty) {
  53160. this._computeProjectionTextureProjectionLightMatrix();
  53161. }
  53162. if (this._projectionTextureDirty) {
  53163. this._computeProjectionTextureMatrix();
  53164. }
  53165. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  53166. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  53167. }
  53168. return this;
  53169. };
  53170. /**
  53171. * Disposes the light and the associated resources.
  53172. */
  53173. SpotLight.prototype.dispose = function () {
  53174. _super.prototype.dispose.call(this);
  53175. if (this._projectionTexture) {
  53176. this._projectionTexture.dispose();
  53177. }
  53178. };
  53179. /**
  53180. * Prepares the list of defines specific to the light type.
  53181. * @param defines the list of defines
  53182. * @param lightIndex defines the index of the light for the effect
  53183. */
  53184. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  53185. defines["SPOTLIGHT" + lightIndex] = true;
  53186. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  53187. };
  53188. __decorate([
  53189. BABYLON.serialize()
  53190. ], SpotLight.prototype, "angle", null);
  53191. __decorate([
  53192. BABYLON.serialize()
  53193. ], SpotLight.prototype, "innerAngle", null);
  53194. __decorate([
  53195. BABYLON.serialize()
  53196. ], SpotLight.prototype, "shadowAngleScale", null);
  53197. __decorate([
  53198. BABYLON.serialize()
  53199. ], SpotLight.prototype, "exponent", void 0);
  53200. __decorate([
  53201. BABYLON.serialize()
  53202. ], SpotLight.prototype, "projectionTextureLightNear", null);
  53203. __decorate([
  53204. BABYLON.serialize()
  53205. ], SpotLight.prototype, "projectionTextureLightFar", null);
  53206. __decorate([
  53207. BABYLON.serialize()
  53208. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  53209. __decorate([
  53210. BABYLON.serializeAsTexture("projectedLightTexture")
  53211. ], SpotLight.prototype, "_projectionTexture", void 0);
  53212. return SpotLight;
  53213. }(BABYLON.ShadowLight));
  53214. BABYLON.SpotLight = SpotLight;
  53215. })(BABYLON || (BABYLON = {}));
  53216. //# sourceMappingURL=spotLight.js.map
  53217. var BABYLON;
  53218. (function (BABYLON) {
  53219. /**
  53220. * Class used to override all child animations of a given target
  53221. */
  53222. var AnimationPropertiesOverride = /** @class */ (function () {
  53223. function AnimationPropertiesOverride() {
  53224. /**
  53225. * Gets or sets a value indicating if animation blending must be used
  53226. */
  53227. this.enableBlending = false;
  53228. /**
  53229. * Gets or sets the blending speed to use when enableBlending is true
  53230. */
  53231. this.blendingSpeed = 0.01;
  53232. /**
  53233. * Gets or sets the default loop mode to use
  53234. */
  53235. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  53236. }
  53237. return AnimationPropertiesOverride;
  53238. }());
  53239. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  53240. })(BABYLON || (BABYLON = {}));
  53241. //# sourceMappingURL=animationPropertiesOverride.js.map
  53242. var BABYLON;
  53243. (function (BABYLON) {
  53244. /**
  53245. * Represents the range of an animation
  53246. */
  53247. var AnimationRange = /** @class */ (function () {
  53248. /**
  53249. * Initializes the range of an animation
  53250. * @param name The name of the animation range
  53251. * @param from The starting frame of the animation
  53252. * @param to The ending frame of the animation
  53253. */
  53254. function AnimationRange(
  53255. /**The name of the animation range**/
  53256. name,
  53257. /**The starting frame of the animation */
  53258. from,
  53259. /**The ending frame of the animation*/
  53260. to) {
  53261. this.name = name;
  53262. this.from = from;
  53263. this.to = to;
  53264. }
  53265. /**
  53266. * Makes a copy of the animation range
  53267. * @returns A copy of the animation range
  53268. */
  53269. AnimationRange.prototype.clone = function () {
  53270. return new AnimationRange(this.name, this.from, this.to);
  53271. };
  53272. return AnimationRange;
  53273. }());
  53274. BABYLON.AnimationRange = AnimationRange;
  53275. /**
  53276. * Composed of a frame, and an action function
  53277. */
  53278. var AnimationEvent = /** @class */ (function () {
  53279. /**
  53280. * Initializes the animation event
  53281. * @param frame The frame for which the event is triggered
  53282. * @param action The event to perform when triggered
  53283. * @param onlyOnce Specifies if the event should be triggered only once
  53284. */
  53285. function AnimationEvent(
  53286. /** The frame for which the event is triggered **/
  53287. frame,
  53288. /** The event to perform when triggered **/
  53289. action,
  53290. /** Specifies if the event should be triggered only once**/
  53291. onlyOnce) {
  53292. this.frame = frame;
  53293. this.action = action;
  53294. this.onlyOnce = onlyOnce;
  53295. /**
  53296. * Specifies if the animation event is done
  53297. */
  53298. this.isDone = false;
  53299. }
  53300. /** @hidden */
  53301. AnimationEvent.prototype._clone = function () {
  53302. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  53303. };
  53304. return AnimationEvent;
  53305. }());
  53306. BABYLON.AnimationEvent = AnimationEvent;
  53307. /**
  53308. * A cursor which tracks a point on a path
  53309. */
  53310. var PathCursor = /** @class */ (function () {
  53311. /**
  53312. * Initializes the path cursor
  53313. * @param path The path to track
  53314. */
  53315. function PathCursor(path) {
  53316. this.path = path;
  53317. /**
  53318. * Stores path cursor callbacks for when an onchange event is triggered
  53319. */
  53320. this._onchange = new Array();
  53321. /**
  53322. * The value of the path cursor
  53323. */
  53324. this.value = 0;
  53325. /**
  53326. * The animation array of the path cursor
  53327. */
  53328. this.animations = new Array();
  53329. }
  53330. /**
  53331. * Gets the cursor point on the path
  53332. * @returns A point on the path cursor at the cursor location
  53333. */
  53334. PathCursor.prototype.getPoint = function () {
  53335. var point = this.path.getPointAtLengthPosition(this.value);
  53336. return new BABYLON.Vector3(point.x, 0, point.y);
  53337. };
  53338. /**
  53339. * Moves the cursor ahead by the step amount
  53340. * @param step The amount to move the cursor forward
  53341. * @returns This path cursor
  53342. */
  53343. PathCursor.prototype.moveAhead = function (step) {
  53344. if (step === void 0) { step = 0.002; }
  53345. this.move(step);
  53346. return this;
  53347. };
  53348. /**
  53349. * Moves the cursor behind by the step amount
  53350. * @param step The amount to move the cursor back
  53351. * @returns This path cursor
  53352. */
  53353. PathCursor.prototype.moveBack = function (step) {
  53354. if (step === void 0) { step = 0.002; }
  53355. this.move(-step);
  53356. return this;
  53357. };
  53358. /**
  53359. * Moves the cursor by the step amount
  53360. * If the step amount is greater than one, an exception is thrown
  53361. * @param step The amount to move the cursor
  53362. * @returns This path cursor
  53363. */
  53364. PathCursor.prototype.move = function (step) {
  53365. if (Math.abs(step) > 1) {
  53366. throw "step size should be less than 1.";
  53367. }
  53368. this.value += step;
  53369. this.ensureLimits();
  53370. this.raiseOnChange();
  53371. return this;
  53372. };
  53373. /**
  53374. * Ensures that the value is limited between zero and one
  53375. * @returns This path cursor
  53376. */
  53377. PathCursor.prototype.ensureLimits = function () {
  53378. while (this.value > 1) {
  53379. this.value -= 1;
  53380. }
  53381. while (this.value < 0) {
  53382. this.value += 1;
  53383. }
  53384. return this;
  53385. };
  53386. /**
  53387. * Runs onchange callbacks on change (used by the animation engine)
  53388. * @returns This path cursor
  53389. */
  53390. PathCursor.prototype.raiseOnChange = function () {
  53391. var _this = this;
  53392. this._onchange.forEach(function (f) { return f(_this); });
  53393. return this;
  53394. };
  53395. /**
  53396. * Executes a function on change
  53397. * @param f A path cursor onchange callback
  53398. * @returns This path cursor
  53399. */
  53400. PathCursor.prototype.onchange = function (f) {
  53401. this._onchange.push(f);
  53402. return this;
  53403. };
  53404. return PathCursor;
  53405. }());
  53406. BABYLON.PathCursor = PathCursor;
  53407. /**
  53408. * Enum for the animation key frame interpolation type
  53409. */
  53410. var AnimationKeyInterpolation;
  53411. (function (AnimationKeyInterpolation) {
  53412. /**
  53413. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  53414. */
  53415. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  53416. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  53417. /**
  53418. * Class used to store any kind of animation
  53419. */
  53420. var Animation = /** @class */ (function () {
  53421. /**
  53422. * Initializes the animation
  53423. * @param name Name of the animation
  53424. * @param targetProperty Property to animate
  53425. * @param framePerSecond The frames per second of the animation
  53426. * @param dataType The data type of the animation
  53427. * @param loopMode The loop mode of the animation
  53428. * @param enableBlendings Specifies if blending should be enabled
  53429. */
  53430. function Animation(
  53431. /**Name of the animation */
  53432. name,
  53433. /**Property to animate */
  53434. targetProperty,
  53435. /**The frames per second of the animation */
  53436. framePerSecond,
  53437. /**The data type of the animation */
  53438. dataType,
  53439. /**The loop mode of the animation */
  53440. loopMode,
  53441. /**Specifies if blending should be enabled */
  53442. enableBlending) {
  53443. this.name = name;
  53444. this.targetProperty = targetProperty;
  53445. this.framePerSecond = framePerSecond;
  53446. this.dataType = dataType;
  53447. this.loopMode = loopMode;
  53448. this.enableBlending = enableBlending;
  53449. /**
  53450. * @hidden Internal use only
  53451. */
  53452. this._runtimeAnimations = new Array();
  53453. /**
  53454. * The set of event that will be linked to this animation
  53455. */
  53456. this._events = new Array();
  53457. /**
  53458. * Stores the blending speed of the animation
  53459. */
  53460. this.blendingSpeed = 0.01;
  53461. /**
  53462. * Stores the animation ranges for the animation
  53463. */
  53464. this._ranges = {};
  53465. this.targetPropertyPath = targetProperty.split(".");
  53466. this.dataType = dataType;
  53467. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  53468. }
  53469. /**
  53470. * @hidden Internal use
  53471. */
  53472. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  53473. var dataType = undefined;
  53474. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  53475. dataType = Animation.ANIMATIONTYPE_FLOAT;
  53476. }
  53477. else if (from instanceof BABYLON.Quaternion) {
  53478. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  53479. }
  53480. else if (from instanceof BABYLON.Vector3) {
  53481. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  53482. }
  53483. else if (from instanceof BABYLON.Vector2) {
  53484. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  53485. }
  53486. else if (from instanceof BABYLON.Color3) {
  53487. dataType = Animation.ANIMATIONTYPE_COLOR3;
  53488. }
  53489. else if (from instanceof BABYLON.Size) {
  53490. dataType = Animation.ANIMATIONTYPE_SIZE;
  53491. }
  53492. if (dataType == undefined) {
  53493. return null;
  53494. }
  53495. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  53496. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  53497. animation.setKeys(keys);
  53498. if (easingFunction !== undefined) {
  53499. animation.setEasingFunction(easingFunction);
  53500. }
  53501. return animation;
  53502. };
  53503. /**
  53504. * Sets up an animation
  53505. * @param property The property to animate
  53506. * @param animationType The animation type to apply
  53507. * @param framePerSecond The frames per second of the animation
  53508. * @param easingFunction The easing function used in the animation
  53509. * @returns The created animation
  53510. */
  53511. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  53512. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  53513. animation.setEasingFunction(easingFunction);
  53514. return animation;
  53515. };
  53516. /**
  53517. * Create and start an animation on a node
  53518. * @param name defines the name of the global animation that will be run on all nodes
  53519. * @param node defines the root node where the animation will take place
  53520. * @param targetProperty defines property to animate
  53521. * @param framePerSecond defines the number of frame per second yo use
  53522. * @param totalFrame defines the number of frames in total
  53523. * @param from defines the initial value
  53524. * @param to defines the final value
  53525. * @param loopMode defines which loop mode you want to use (off by default)
  53526. * @param easingFunction defines the easing function to use (linear by default)
  53527. * @param onAnimationEnd defines the callback to call when animation end
  53528. * @returns the animatable created for this animation
  53529. */
  53530. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  53531. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  53532. if (!animation) {
  53533. return null;
  53534. }
  53535. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  53536. };
  53537. /**
  53538. * Create and start an animation on a node and its descendants
  53539. * @param name defines the name of the global animation that will be run on all nodes
  53540. * @param node defines the root node where the animation will take place
  53541. * @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
  53542. * @param targetProperty defines property to animate
  53543. * @param framePerSecond defines the number of frame per second to use
  53544. * @param totalFrame defines the number of frames in total
  53545. * @param from defines the initial value
  53546. * @param to defines the final value
  53547. * @param loopMode defines which loop mode you want to use (off by default)
  53548. * @param easingFunction defines the easing function to use (linear by default)
  53549. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  53550. * @returns the list of animatables created for all nodes
  53551. * @example https://www.babylonjs-playground.com/#MH0VLI
  53552. */
  53553. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  53554. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  53555. if (!animation) {
  53556. return null;
  53557. }
  53558. var scene = node.getScene();
  53559. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  53560. };
  53561. /**
  53562. * Creates a new animation, merges it with the existing animations and starts it
  53563. * @param name Name of the animation
  53564. * @param node Node which contains the scene that begins the animations
  53565. * @param targetProperty Specifies which property to animate
  53566. * @param framePerSecond The frames per second of the animation
  53567. * @param totalFrame The total number of frames
  53568. * @param from The frame at the beginning of the animation
  53569. * @param to The frame at the end of the animation
  53570. * @param loopMode Specifies the loop mode of the animation
  53571. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  53572. * @param onAnimationEnd Callback to run once the animation is complete
  53573. * @returns Nullable animation
  53574. */
  53575. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  53576. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  53577. if (!animation) {
  53578. return null;
  53579. }
  53580. node.animations.push(animation);
  53581. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  53582. };
  53583. /**
  53584. * Transition property of an host to the target Value
  53585. * @param property The property to transition
  53586. * @param targetValue The target Value of the property
  53587. * @param host The object where the property to animate belongs
  53588. * @param scene Scene used to run the animation
  53589. * @param frameRate Framerate (in frame/s) to use
  53590. * @param transition The transition type we want to use
  53591. * @param duration The duration of the animation, in milliseconds
  53592. * @param onAnimationEnd Callback trigger at the end of the animation
  53593. * @returns Nullable animation
  53594. */
  53595. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  53596. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  53597. if (duration <= 0) {
  53598. host[property] = targetValue;
  53599. if (onAnimationEnd) {
  53600. onAnimationEnd();
  53601. }
  53602. return null;
  53603. }
  53604. var endFrame = frameRate * (duration / 1000);
  53605. transition.setKeys([{
  53606. frame: 0,
  53607. value: host[property].clone ? host[property].clone() : host[property]
  53608. },
  53609. {
  53610. frame: endFrame,
  53611. value: targetValue
  53612. }]);
  53613. if (!host.animations) {
  53614. host.animations = [];
  53615. }
  53616. host.animations.push(transition);
  53617. var animation = scene.beginAnimation(host, 0, endFrame, false);
  53618. animation.onAnimationEnd = onAnimationEnd;
  53619. return animation;
  53620. };
  53621. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  53622. /**
  53623. * Return the array of runtime animations currently using this animation
  53624. */
  53625. get: function () {
  53626. return this._runtimeAnimations;
  53627. },
  53628. enumerable: true,
  53629. configurable: true
  53630. });
  53631. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  53632. /**
  53633. * Specifies if any of the runtime animations are currently running
  53634. */
  53635. get: function () {
  53636. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  53637. var runtimeAnimation = _a[_i];
  53638. if (!runtimeAnimation.isStopped) {
  53639. return true;
  53640. }
  53641. }
  53642. return false;
  53643. },
  53644. enumerable: true,
  53645. configurable: true
  53646. });
  53647. // Methods
  53648. /**
  53649. * Converts the animation to a string
  53650. * @param fullDetails support for multiple levels of logging within scene loading
  53651. * @returns String form of the animation
  53652. */
  53653. Animation.prototype.toString = function (fullDetails) {
  53654. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  53655. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  53656. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  53657. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  53658. if (fullDetails) {
  53659. ret += ", Ranges: {";
  53660. var first = true;
  53661. for (var name in this._ranges) {
  53662. if (first) {
  53663. ret += ", ";
  53664. first = false;
  53665. }
  53666. ret += name;
  53667. }
  53668. ret += "}";
  53669. }
  53670. return ret;
  53671. };
  53672. /**
  53673. * Add an event to this animation
  53674. * @param event Event to add
  53675. */
  53676. Animation.prototype.addEvent = function (event) {
  53677. this._events.push(event);
  53678. };
  53679. /**
  53680. * Remove all events found at the given frame
  53681. * @param frame The frame to remove events from
  53682. */
  53683. Animation.prototype.removeEvents = function (frame) {
  53684. for (var index = 0; index < this._events.length; index++) {
  53685. if (this._events[index].frame === frame) {
  53686. this._events.splice(index, 1);
  53687. index--;
  53688. }
  53689. }
  53690. };
  53691. /**
  53692. * Retrieves all the events from the animation
  53693. * @returns Events from the animation
  53694. */
  53695. Animation.prototype.getEvents = function () {
  53696. return this._events;
  53697. };
  53698. /**
  53699. * Creates an animation range
  53700. * @param name Name of the animation range
  53701. * @param from Starting frame of the animation range
  53702. * @param to Ending frame of the animation
  53703. */
  53704. Animation.prototype.createRange = function (name, from, to) {
  53705. // check name not already in use; could happen for bones after serialized
  53706. if (!this._ranges[name]) {
  53707. this._ranges[name] = new AnimationRange(name, from, to);
  53708. }
  53709. };
  53710. /**
  53711. * Deletes an animation range by name
  53712. * @param name Name of the animation range to delete
  53713. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  53714. */
  53715. Animation.prototype.deleteRange = function (name, deleteFrames) {
  53716. if (deleteFrames === void 0) { deleteFrames = true; }
  53717. var range = this._ranges[name];
  53718. if (!range) {
  53719. return;
  53720. }
  53721. if (deleteFrames) {
  53722. var from = range.from;
  53723. var to = range.to;
  53724. // this loop MUST go high to low for multiple splices to work
  53725. for (var key = this._keys.length - 1; key >= 0; key--) {
  53726. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  53727. this._keys.splice(key, 1);
  53728. }
  53729. }
  53730. }
  53731. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  53732. };
  53733. /**
  53734. * Gets the animation range by name, or null if not defined
  53735. * @param name Name of the animation range
  53736. * @returns Nullable animation range
  53737. */
  53738. Animation.prototype.getRange = function (name) {
  53739. return this._ranges[name];
  53740. };
  53741. /**
  53742. * Gets the key frames from the animation
  53743. * @returns The key frames of the animation
  53744. */
  53745. Animation.prototype.getKeys = function () {
  53746. return this._keys;
  53747. };
  53748. /**
  53749. * Gets the highest frame rate of the animation
  53750. * @returns Highest frame rate of the animation
  53751. */
  53752. Animation.prototype.getHighestFrame = function () {
  53753. var ret = 0;
  53754. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  53755. if (ret < this._keys[key].frame) {
  53756. ret = this._keys[key].frame;
  53757. }
  53758. }
  53759. return ret;
  53760. };
  53761. /**
  53762. * Gets the easing function of the animation
  53763. * @returns Easing function of the animation
  53764. */
  53765. Animation.prototype.getEasingFunction = function () {
  53766. return this._easingFunction;
  53767. };
  53768. /**
  53769. * Sets the easing function of the animation
  53770. * @param easingFunction A custom mathematical formula for animation
  53771. */
  53772. Animation.prototype.setEasingFunction = function (easingFunction) {
  53773. this._easingFunction = easingFunction;
  53774. };
  53775. /**
  53776. * Interpolates a scalar linearly
  53777. * @param startValue Start value of the animation curve
  53778. * @param endValue End value of the animation curve
  53779. * @param gradient Scalar amount to interpolate
  53780. * @returns Interpolated scalar value
  53781. */
  53782. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  53783. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  53784. };
  53785. /**
  53786. * Interpolates a scalar cubically
  53787. * @param startValue Start value of the animation curve
  53788. * @param outTangent End tangent of the animation
  53789. * @param endValue End value of the animation curve
  53790. * @param inTangent Start tangent of the animation curve
  53791. * @param gradient Scalar amount to interpolate
  53792. * @returns Interpolated scalar value
  53793. */
  53794. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  53795. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  53796. };
  53797. /**
  53798. * Interpolates a quaternion using a spherical linear interpolation
  53799. * @param startValue Start value of the animation curve
  53800. * @param endValue End value of the animation curve
  53801. * @param gradient Scalar amount to interpolate
  53802. * @returns Interpolated quaternion value
  53803. */
  53804. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  53805. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  53806. };
  53807. /**
  53808. * Interpolates a quaternion cubically
  53809. * @param startValue Start value of the animation curve
  53810. * @param outTangent End tangent of the animation curve
  53811. * @param endValue End value of the animation curve
  53812. * @param inTangent Start tangent of the animation curve
  53813. * @param gradient Scalar amount to interpolate
  53814. * @returns Interpolated quaternion value
  53815. */
  53816. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  53817. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  53818. };
  53819. /**
  53820. * Interpolates a Vector3 linearl
  53821. * @param startValue Start value of the animation curve
  53822. * @param endValue End value of the animation curve
  53823. * @param gradient Scalar amount to interpolate
  53824. * @returns Interpolated scalar value
  53825. */
  53826. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  53827. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  53828. };
  53829. /**
  53830. * Interpolates a Vector3 cubically
  53831. * @param startValue Start value of the animation curve
  53832. * @param outTangent End tangent of the animation
  53833. * @param endValue End value of the animation curve
  53834. * @param inTangent Start tangent of the animation curve
  53835. * @param gradient Scalar amount to interpolate
  53836. * @returns InterpolatedVector3 value
  53837. */
  53838. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  53839. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  53840. };
  53841. /**
  53842. * Interpolates a Vector2 linearly
  53843. * @param startValue Start value of the animation curve
  53844. * @param endValue End value of the animation curve
  53845. * @param gradient Scalar amount to interpolate
  53846. * @returns Interpolated Vector2 value
  53847. */
  53848. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  53849. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  53850. };
  53851. /**
  53852. * Interpolates a Vector2 cubically
  53853. * @param startValue Start value of the animation curve
  53854. * @param outTangent End tangent of the animation
  53855. * @param endValue End value of the animation curve
  53856. * @param inTangent Start tangent of the animation curve
  53857. * @param gradient Scalar amount to interpolate
  53858. * @returns Interpolated Vector2 value
  53859. */
  53860. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  53861. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  53862. };
  53863. /**
  53864. * Interpolates a size linearly
  53865. * @param startValue Start value of the animation curve
  53866. * @param endValue End value of the animation curve
  53867. * @param gradient Scalar amount to interpolate
  53868. * @returns Interpolated Size value
  53869. */
  53870. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  53871. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  53872. };
  53873. /**
  53874. * Interpolates a Color3 linearly
  53875. * @param startValue Start value of the animation curve
  53876. * @param endValue End value of the animation curve
  53877. * @param gradient Scalar amount to interpolate
  53878. * @returns Interpolated Color3 value
  53879. */
  53880. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  53881. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  53882. };
  53883. /**
  53884. * @hidden Internal use only
  53885. */
  53886. Animation.prototype._getKeyValue = function (value) {
  53887. if (typeof value === "function") {
  53888. return value();
  53889. }
  53890. return value;
  53891. };
  53892. /**
  53893. * @hidden Internal use only
  53894. */
  53895. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  53896. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  53897. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  53898. }
  53899. var keys = this.getKeys();
  53900. // Try to get a hash to find the right key
  53901. 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));
  53902. if (keys[startKeyIndex].frame >= currentFrame) {
  53903. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  53904. startKeyIndex--;
  53905. }
  53906. }
  53907. for (var key = startKeyIndex; key < keys.length; key++) {
  53908. var endKey = keys[key + 1];
  53909. if (endKey.frame >= currentFrame) {
  53910. var startKey = keys[key];
  53911. var startValue = this._getKeyValue(startKey.value);
  53912. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  53913. return startValue;
  53914. }
  53915. var endValue = this._getKeyValue(endKey.value);
  53916. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  53917. var frameDelta = endKey.frame - startKey.frame;
  53918. // gradient : percent of currentFrame between the frame inf and the frame sup
  53919. var gradient = (currentFrame - startKey.frame) / frameDelta;
  53920. // check for easingFunction and correction of gradient
  53921. var easingFunction = this.getEasingFunction();
  53922. if (easingFunction != null) {
  53923. gradient = easingFunction.ease(gradient);
  53924. }
  53925. switch (this.dataType) {
  53926. // Float
  53927. case Animation.ANIMATIONTYPE_FLOAT:
  53928. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  53929. switch (loopMode) {
  53930. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53931. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53932. return floatValue;
  53933. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53934. return offsetValue * repeatCount + floatValue;
  53935. }
  53936. break;
  53937. // Quaternion
  53938. case Animation.ANIMATIONTYPE_QUATERNION:
  53939. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  53940. switch (loopMode) {
  53941. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53942. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53943. return quatValue;
  53944. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53945. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  53946. }
  53947. return quatValue;
  53948. // Vector3
  53949. case Animation.ANIMATIONTYPE_VECTOR3:
  53950. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  53951. switch (loopMode) {
  53952. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53953. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53954. return vec3Value;
  53955. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53956. return vec3Value.add(offsetValue.scale(repeatCount));
  53957. }
  53958. // Vector2
  53959. case Animation.ANIMATIONTYPE_VECTOR2:
  53960. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  53961. switch (loopMode) {
  53962. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53963. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53964. return vec2Value;
  53965. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53966. return vec2Value.add(offsetValue.scale(repeatCount));
  53967. }
  53968. // Size
  53969. case Animation.ANIMATIONTYPE_SIZE:
  53970. switch (loopMode) {
  53971. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53972. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53973. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  53974. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53975. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  53976. }
  53977. // Color3
  53978. case Animation.ANIMATIONTYPE_COLOR3:
  53979. switch (loopMode) {
  53980. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53981. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53982. return this.color3InterpolateFunction(startValue, endValue, gradient);
  53983. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53984. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  53985. }
  53986. // Matrix
  53987. case Animation.ANIMATIONTYPE_MATRIX:
  53988. switch (loopMode) {
  53989. case Animation.ANIMATIONLOOPMODE_CYCLE:
  53990. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  53991. if (Animation.AllowMatricesInterpolation) {
  53992. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  53993. }
  53994. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  53995. return startValue;
  53996. }
  53997. default:
  53998. break;
  53999. }
  54000. break;
  54001. }
  54002. }
  54003. return this._getKeyValue(keys[keys.length - 1].value);
  54004. };
  54005. /**
  54006. * Defines the function to use to interpolate matrices
  54007. * @param startValue defines the start matrix
  54008. * @param endValue defines the end matrix
  54009. * @param gradient defines the gradient between both matrices
  54010. * @param result defines an optional target matrix where to store the interpolation
  54011. * @returns the interpolated matrix
  54012. */
  54013. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  54014. if (Animation.AllowMatrixDecomposeForInterpolation) {
  54015. if (result) {
  54016. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  54017. return result;
  54018. }
  54019. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  54020. }
  54021. if (result) {
  54022. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  54023. return result;
  54024. }
  54025. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  54026. };
  54027. /**
  54028. * Makes a copy of the animation
  54029. * @returns Cloned animation
  54030. */
  54031. Animation.prototype.clone = function () {
  54032. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  54033. clone.enableBlending = this.enableBlending;
  54034. clone.blendingSpeed = this.blendingSpeed;
  54035. if (this._keys) {
  54036. clone.setKeys(this._keys);
  54037. }
  54038. if (this._ranges) {
  54039. clone._ranges = {};
  54040. for (var name in this._ranges) {
  54041. var range = this._ranges[name];
  54042. if (!range) {
  54043. continue;
  54044. }
  54045. clone._ranges[name] = range.clone();
  54046. }
  54047. }
  54048. return clone;
  54049. };
  54050. /**
  54051. * Sets the key frames of the animation
  54052. * @param values The animation key frames to set
  54053. */
  54054. Animation.prototype.setKeys = function (values) {
  54055. this._keys = values.slice(0);
  54056. };
  54057. /**
  54058. * Serializes the animation to an object
  54059. * @returns Serialized object
  54060. */
  54061. Animation.prototype.serialize = function () {
  54062. var serializationObject = {};
  54063. serializationObject.name = this.name;
  54064. serializationObject.property = this.targetProperty;
  54065. serializationObject.framePerSecond = this.framePerSecond;
  54066. serializationObject.dataType = this.dataType;
  54067. serializationObject.loopBehavior = this.loopMode;
  54068. serializationObject.enableBlending = this.enableBlending;
  54069. serializationObject.blendingSpeed = this.blendingSpeed;
  54070. var dataType = this.dataType;
  54071. serializationObject.keys = [];
  54072. var keys = this.getKeys();
  54073. for (var index = 0; index < keys.length; index++) {
  54074. var animationKey = keys[index];
  54075. var key = {};
  54076. key.frame = animationKey.frame;
  54077. switch (dataType) {
  54078. case Animation.ANIMATIONTYPE_FLOAT:
  54079. key.values = [animationKey.value];
  54080. break;
  54081. case Animation.ANIMATIONTYPE_QUATERNION:
  54082. case Animation.ANIMATIONTYPE_MATRIX:
  54083. case Animation.ANIMATIONTYPE_VECTOR3:
  54084. case Animation.ANIMATIONTYPE_COLOR3:
  54085. key.values = animationKey.value.asArray();
  54086. break;
  54087. }
  54088. serializationObject.keys.push(key);
  54089. }
  54090. serializationObject.ranges = [];
  54091. for (var name in this._ranges) {
  54092. var source = this._ranges[name];
  54093. if (!source) {
  54094. continue;
  54095. }
  54096. var range = {};
  54097. range.name = name;
  54098. range.from = source.from;
  54099. range.to = source.to;
  54100. serializationObject.ranges.push(range);
  54101. }
  54102. return serializationObject;
  54103. };
  54104. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  54105. /**
  54106. * Get the float animation type
  54107. */
  54108. get: function () {
  54109. return Animation._ANIMATIONTYPE_FLOAT;
  54110. },
  54111. enumerable: true,
  54112. configurable: true
  54113. });
  54114. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  54115. /**
  54116. * Get the Vector3 animation type
  54117. */
  54118. get: function () {
  54119. return Animation._ANIMATIONTYPE_VECTOR3;
  54120. },
  54121. enumerable: true,
  54122. configurable: true
  54123. });
  54124. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  54125. /**
  54126. * Get the Vector2 animation type
  54127. */
  54128. get: function () {
  54129. return Animation._ANIMATIONTYPE_VECTOR2;
  54130. },
  54131. enumerable: true,
  54132. configurable: true
  54133. });
  54134. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  54135. /**
  54136. * Get the Size animation type
  54137. */
  54138. get: function () {
  54139. return Animation._ANIMATIONTYPE_SIZE;
  54140. },
  54141. enumerable: true,
  54142. configurable: true
  54143. });
  54144. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  54145. /**
  54146. * Get the Quaternion animation type
  54147. */
  54148. get: function () {
  54149. return Animation._ANIMATIONTYPE_QUATERNION;
  54150. },
  54151. enumerable: true,
  54152. configurable: true
  54153. });
  54154. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  54155. /**
  54156. * Get the Matrix animation type
  54157. */
  54158. get: function () {
  54159. return Animation._ANIMATIONTYPE_MATRIX;
  54160. },
  54161. enumerable: true,
  54162. configurable: true
  54163. });
  54164. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  54165. /**
  54166. * Get the Color3 animation type
  54167. */
  54168. get: function () {
  54169. return Animation._ANIMATIONTYPE_COLOR3;
  54170. },
  54171. enumerable: true,
  54172. configurable: true
  54173. });
  54174. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  54175. /**
  54176. * Get the Relative Loop Mode
  54177. */
  54178. get: function () {
  54179. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  54180. },
  54181. enumerable: true,
  54182. configurable: true
  54183. });
  54184. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  54185. /**
  54186. * Get the Cycle Loop Mode
  54187. */
  54188. get: function () {
  54189. return Animation._ANIMATIONLOOPMODE_CYCLE;
  54190. },
  54191. enumerable: true,
  54192. configurable: true
  54193. });
  54194. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  54195. /**
  54196. * Get the Constant Loop Mode
  54197. */
  54198. get: function () {
  54199. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  54200. },
  54201. enumerable: true,
  54202. configurable: true
  54203. });
  54204. /** @hidden */
  54205. Animation._UniversalLerp = function (left, right, amount) {
  54206. var constructor = left.constructor;
  54207. if (constructor.Lerp) { // Lerp supported
  54208. return constructor.Lerp(left, right, amount);
  54209. }
  54210. else if (constructor.Slerp) { // Slerp supported
  54211. return constructor.Slerp(left, right, amount);
  54212. }
  54213. else if (left.toFixed) { // Number
  54214. return left * (1.0 - amount) + amount * right;
  54215. }
  54216. else { // Blending not supported
  54217. return right;
  54218. }
  54219. };
  54220. /**
  54221. * Parses an animation object and creates an animation
  54222. * @param parsedAnimation Parsed animation object
  54223. * @returns Animation object
  54224. */
  54225. Animation.Parse = function (parsedAnimation) {
  54226. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  54227. var dataType = parsedAnimation.dataType;
  54228. var keys = [];
  54229. var data;
  54230. var index;
  54231. if (parsedAnimation.enableBlending) {
  54232. animation.enableBlending = parsedAnimation.enableBlending;
  54233. }
  54234. if (parsedAnimation.blendingSpeed) {
  54235. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  54236. }
  54237. for (index = 0; index < parsedAnimation.keys.length; index++) {
  54238. var key = parsedAnimation.keys[index];
  54239. var inTangent;
  54240. var outTangent;
  54241. switch (dataType) {
  54242. case Animation.ANIMATIONTYPE_FLOAT:
  54243. data = key.values[0];
  54244. if (key.values.length >= 1) {
  54245. inTangent = key.values[1];
  54246. }
  54247. if (key.values.length >= 2) {
  54248. outTangent = key.values[2];
  54249. }
  54250. break;
  54251. case Animation.ANIMATIONTYPE_QUATERNION:
  54252. data = BABYLON.Quaternion.FromArray(key.values);
  54253. if (key.values.length >= 8) {
  54254. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  54255. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  54256. inTangent = _inTangent;
  54257. }
  54258. }
  54259. if (key.values.length >= 12) {
  54260. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  54261. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  54262. outTangent = _outTangent;
  54263. }
  54264. }
  54265. break;
  54266. case Animation.ANIMATIONTYPE_MATRIX:
  54267. data = BABYLON.Matrix.FromArray(key.values);
  54268. break;
  54269. case Animation.ANIMATIONTYPE_COLOR3:
  54270. data = BABYLON.Color3.FromArray(key.values);
  54271. break;
  54272. case Animation.ANIMATIONTYPE_VECTOR3:
  54273. default:
  54274. data = BABYLON.Vector3.FromArray(key.values);
  54275. break;
  54276. }
  54277. var keyData = {};
  54278. keyData.frame = key.frame;
  54279. keyData.value = data;
  54280. if (inTangent != undefined) {
  54281. keyData.inTangent = inTangent;
  54282. }
  54283. if (outTangent != undefined) {
  54284. keyData.outTangent = outTangent;
  54285. }
  54286. keys.push(keyData);
  54287. }
  54288. animation.setKeys(keys);
  54289. if (parsedAnimation.ranges) {
  54290. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  54291. data = parsedAnimation.ranges[index];
  54292. animation.createRange(data.name, data.from, data.to);
  54293. }
  54294. }
  54295. return animation;
  54296. };
  54297. /**
  54298. * Appends the serialized animations from the source animations
  54299. * @param source Source containing the animations
  54300. * @param destination Target to store the animations
  54301. */
  54302. Animation.AppendSerializedAnimations = function (source, destination) {
  54303. if (source.animations) {
  54304. destination.animations = [];
  54305. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  54306. var animation = source.animations[animationIndex];
  54307. destination.animations.push(animation.serialize());
  54308. }
  54309. }
  54310. };
  54311. /**
  54312. * Use matrix interpolation instead of using direct key value when animating matrices
  54313. */
  54314. Animation.AllowMatricesInterpolation = false;
  54315. /**
  54316. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  54317. */
  54318. Animation.AllowMatrixDecomposeForInterpolation = true;
  54319. // Statics
  54320. /**
  54321. * Float animation type
  54322. */
  54323. Animation._ANIMATIONTYPE_FLOAT = 0;
  54324. /**
  54325. * Vector3 animation type
  54326. */
  54327. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  54328. /**
  54329. * Quaternion animation type
  54330. */
  54331. Animation._ANIMATIONTYPE_QUATERNION = 2;
  54332. /**
  54333. * Matrix animation type
  54334. */
  54335. Animation._ANIMATIONTYPE_MATRIX = 3;
  54336. /**
  54337. * Color3 animation type
  54338. */
  54339. Animation._ANIMATIONTYPE_COLOR3 = 4;
  54340. /**
  54341. * Vector2 animation type
  54342. */
  54343. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  54344. /**
  54345. * Size animation type
  54346. */
  54347. Animation._ANIMATIONTYPE_SIZE = 6;
  54348. /**
  54349. * Relative Loop Mode
  54350. */
  54351. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  54352. /**
  54353. * Cycle Loop Mode
  54354. */
  54355. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  54356. /**
  54357. * Constant Loop Mode
  54358. */
  54359. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  54360. return Animation;
  54361. }());
  54362. BABYLON.Animation = Animation;
  54363. })(BABYLON || (BABYLON = {}));
  54364. //# sourceMappingURL=animation.js.map
  54365. var BABYLON;
  54366. (function (BABYLON) {
  54367. /**
  54368. * This class defines the direct association between an animation and a target
  54369. */
  54370. var TargetedAnimation = /** @class */ (function () {
  54371. function TargetedAnimation() {
  54372. }
  54373. return TargetedAnimation;
  54374. }());
  54375. BABYLON.TargetedAnimation = TargetedAnimation;
  54376. /**
  54377. * Use this class to create coordinated animations on multiple targets
  54378. */
  54379. var AnimationGroup = /** @class */ (function () {
  54380. /**
  54381. * Instantiates a new Animation Group.
  54382. * This helps managing several animations at once.
  54383. * @see http://doc.babylonjs.com/how_to/group
  54384. * @param name Defines the name of the group
  54385. * @param scene Defines the scene the group belongs to
  54386. */
  54387. function AnimationGroup(
  54388. /** The name of the animation group */
  54389. name, scene) {
  54390. if (scene === void 0) { scene = null; }
  54391. this.name = name;
  54392. this._targetedAnimations = new Array();
  54393. this._animatables = new Array();
  54394. this._from = Number.MAX_VALUE;
  54395. this._to = -Number.MAX_VALUE;
  54396. this._speedRatio = 1;
  54397. /**
  54398. * This observable will notify when one animation have ended.
  54399. */
  54400. this.onAnimationEndObservable = new BABYLON.Observable();
  54401. /**
  54402. * This observable will notify when all animations have ended.
  54403. */
  54404. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  54405. /**
  54406. * This observable will notify when all animations have paused.
  54407. */
  54408. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  54409. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54410. this._scene.animationGroups.push(this);
  54411. }
  54412. Object.defineProperty(AnimationGroup.prototype, "from", {
  54413. /**
  54414. * Gets the first frame
  54415. */
  54416. get: function () {
  54417. return this._from;
  54418. },
  54419. enumerable: true,
  54420. configurable: true
  54421. });
  54422. Object.defineProperty(AnimationGroup.prototype, "to", {
  54423. /**
  54424. * Gets the last frame
  54425. */
  54426. get: function () {
  54427. return this._to;
  54428. },
  54429. enumerable: true,
  54430. configurable: true
  54431. });
  54432. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  54433. /**
  54434. * Define if the animations are started
  54435. */
  54436. get: function () {
  54437. return this._isStarted;
  54438. },
  54439. enumerable: true,
  54440. configurable: true
  54441. });
  54442. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  54443. /**
  54444. * Gets or sets the speed ratio to use for all animations
  54445. */
  54446. get: function () {
  54447. return this._speedRatio;
  54448. },
  54449. /**
  54450. * Gets or sets the speed ratio to use for all animations
  54451. */
  54452. set: function (value) {
  54453. if (this._speedRatio === value) {
  54454. return;
  54455. }
  54456. this._speedRatio = value;
  54457. for (var index = 0; index < this._animatables.length; index++) {
  54458. var animatable = this._animatables[index];
  54459. animatable.speedRatio = this._speedRatio;
  54460. }
  54461. },
  54462. enumerable: true,
  54463. configurable: true
  54464. });
  54465. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  54466. /**
  54467. * Gets the targeted animations for this animation group
  54468. */
  54469. get: function () {
  54470. return this._targetedAnimations;
  54471. },
  54472. enumerable: true,
  54473. configurable: true
  54474. });
  54475. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  54476. /**
  54477. * returning the list of animatables controlled by this animation group.
  54478. */
  54479. get: function () {
  54480. return this._animatables;
  54481. },
  54482. enumerable: true,
  54483. configurable: true
  54484. });
  54485. /**
  54486. * Add an animation (with its target) in the group
  54487. * @param animation defines the animation we want to add
  54488. * @param target defines the target of the animation
  54489. * @returns the TargetedAnimation object
  54490. */
  54491. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  54492. var targetedAnimation = {
  54493. animation: animation,
  54494. target: target
  54495. };
  54496. var keys = animation.getKeys();
  54497. if (this._from > keys[0].frame) {
  54498. this._from = keys[0].frame;
  54499. }
  54500. if (this._to < keys[keys.length - 1].frame) {
  54501. this._to = keys[keys.length - 1].frame;
  54502. }
  54503. this._targetedAnimations.push(targetedAnimation);
  54504. return targetedAnimation;
  54505. };
  54506. /**
  54507. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  54508. * It can add constant keys at begin or end
  54509. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  54510. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  54511. * @returns the animation group
  54512. */
  54513. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  54514. if (beginFrame === void 0) { beginFrame = null; }
  54515. if (endFrame === void 0) { endFrame = null; }
  54516. if (beginFrame == null) {
  54517. beginFrame = this._from;
  54518. }
  54519. if (endFrame == null) {
  54520. endFrame = this._to;
  54521. }
  54522. for (var index = 0; index < this._targetedAnimations.length; index++) {
  54523. var targetedAnimation = this._targetedAnimations[index];
  54524. var keys = targetedAnimation.animation.getKeys();
  54525. var startKey = keys[0];
  54526. var endKey = keys[keys.length - 1];
  54527. if (startKey.frame > beginFrame) {
  54528. var newKey = {
  54529. frame: beginFrame,
  54530. value: startKey.value,
  54531. inTangent: startKey.inTangent,
  54532. outTangent: startKey.outTangent,
  54533. interpolation: startKey.interpolation
  54534. };
  54535. keys.splice(0, 0, newKey);
  54536. }
  54537. if (endKey.frame < endFrame) {
  54538. var newKey = {
  54539. frame: endFrame,
  54540. value: endKey.value,
  54541. inTangent: endKey.outTangent,
  54542. outTangent: endKey.outTangent,
  54543. interpolation: endKey.interpolation
  54544. };
  54545. keys.push(newKey);
  54546. }
  54547. }
  54548. this._from = beginFrame;
  54549. this._to = endFrame;
  54550. return this;
  54551. };
  54552. /**
  54553. * Start all animations on given targets
  54554. * @param loop defines if animations must loop
  54555. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  54556. * @param from defines the from key (optional)
  54557. * @param to defines the to key (optional)
  54558. * @returns the current animation group
  54559. */
  54560. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  54561. var _this = this;
  54562. if (loop === void 0) { loop = false; }
  54563. if (speedRatio === void 0) { speedRatio = 1; }
  54564. if (this._isStarted || this._targetedAnimations.length === 0) {
  54565. return this;
  54566. }
  54567. var _loop_1 = function (targetedAnimation) {
  54568. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  54569. animatable.onAnimationEnd = function () {
  54570. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  54571. _this._checkAnimationGroupEnded(animatable);
  54572. };
  54573. this_1._animatables.push(animatable);
  54574. };
  54575. var this_1 = this;
  54576. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  54577. var targetedAnimation = _a[_i];
  54578. _loop_1(targetedAnimation);
  54579. }
  54580. this._speedRatio = speedRatio;
  54581. this._isStarted = true;
  54582. return this;
  54583. };
  54584. /**
  54585. * Pause all animations
  54586. * @returns the animation group
  54587. */
  54588. AnimationGroup.prototype.pause = function () {
  54589. if (!this._isStarted) {
  54590. return this;
  54591. }
  54592. for (var index = 0; index < this._animatables.length; index++) {
  54593. var animatable = this._animatables[index];
  54594. animatable.pause();
  54595. }
  54596. this.onAnimationGroupPauseObservable.notifyObservers(this);
  54597. return this;
  54598. };
  54599. /**
  54600. * Play all animations to initial state
  54601. * This function will start() the animations if they were not started or will restart() them if they were paused
  54602. * @param loop defines if animations must loop
  54603. * @returns the animation group
  54604. */
  54605. AnimationGroup.prototype.play = function (loop) {
  54606. // only if all animatables are ready and exist
  54607. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  54608. if (loop !== undefined) {
  54609. for (var index = 0; index < this._animatables.length; index++) {
  54610. var animatable = this._animatables[index];
  54611. animatable.loopAnimation = loop;
  54612. }
  54613. }
  54614. this.restart();
  54615. }
  54616. else {
  54617. this.stop();
  54618. this.start(loop, this._speedRatio);
  54619. }
  54620. return this;
  54621. };
  54622. /**
  54623. * Reset all animations to initial state
  54624. * @returns the animation group
  54625. */
  54626. AnimationGroup.prototype.reset = function () {
  54627. if (!this._isStarted) {
  54628. return this;
  54629. }
  54630. for (var index = 0; index < this._animatables.length; index++) {
  54631. var animatable = this._animatables[index];
  54632. animatable.reset();
  54633. }
  54634. return this;
  54635. };
  54636. /**
  54637. * Restart animations from key 0
  54638. * @returns the animation group
  54639. */
  54640. AnimationGroup.prototype.restart = function () {
  54641. if (!this._isStarted) {
  54642. return this;
  54643. }
  54644. for (var index = 0; index < this._animatables.length; index++) {
  54645. var animatable = this._animatables[index];
  54646. animatable.restart();
  54647. }
  54648. return this;
  54649. };
  54650. /**
  54651. * Stop all animations
  54652. * @returns the animation group
  54653. */
  54654. AnimationGroup.prototype.stop = function () {
  54655. if (!this._isStarted) {
  54656. return this;
  54657. }
  54658. var list = this._animatables.slice();
  54659. for (var index = 0; index < list.length; index++) {
  54660. list[index].stop();
  54661. }
  54662. this._isStarted = false;
  54663. return this;
  54664. };
  54665. /**
  54666. * Set animation weight for all animatables
  54667. * @param weight defines the weight to use
  54668. * @return the animationGroup
  54669. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  54670. */
  54671. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  54672. for (var index = 0; index < this._animatables.length; index++) {
  54673. var animatable = this._animatables[index];
  54674. animatable.weight = weight;
  54675. }
  54676. return this;
  54677. };
  54678. /**
  54679. * Synchronize and normalize all animatables with a source animatable
  54680. * @param root defines the root animatable to synchronize with
  54681. * @return the animationGroup
  54682. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  54683. */
  54684. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  54685. for (var index = 0; index < this._animatables.length; index++) {
  54686. var animatable = this._animatables[index];
  54687. animatable.syncWith(root);
  54688. }
  54689. return this;
  54690. };
  54691. /**
  54692. * Goes to a specific frame in this animation group
  54693. * @param frame the frame number to go to
  54694. * @return the animationGroup
  54695. */
  54696. AnimationGroup.prototype.goToFrame = function (frame) {
  54697. if (!this._isStarted) {
  54698. return this;
  54699. }
  54700. for (var index = 0; index < this._animatables.length; index++) {
  54701. var animatable = this._animatables[index];
  54702. animatable.goToFrame(frame);
  54703. }
  54704. return this;
  54705. };
  54706. /**
  54707. * Dispose all associated resources
  54708. */
  54709. AnimationGroup.prototype.dispose = function () {
  54710. this._targetedAnimations = [];
  54711. this._animatables = [];
  54712. var index = this._scene.animationGroups.indexOf(this);
  54713. if (index > -1) {
  54714. this._scene.animationGroups.splice(index, 1);
  54715. }
  54716. };
  54717. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  54718. // animatable should be taken out of the array
  54719. var idx = this._animatables.indexOf(animatable);
  54720. if (idx > -1) {
  54721. this._animatables.splice(idx, 1);
  54722. }
  54723. // all animatables were removed? animation group ended!
  54724. if (this._animatables.length === 0) {
  54725. this._isStarted = false;
  54726. this.onAnimationGroupEndObservable.notifyObservers(this);
  54727. }
  54728. };
  54729. // Statics
  54730. /**
  54731. * Returns a new AnimationGroup object parsed from the source provided.
  54732. * @param parsedAnimationGroup defines the source
  54733. * @param scene defines the scene that will receive the animationGroup
  54734. * @returns a new AnimationGroup
  54735. */
  54736. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  54737. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  54738. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  54739. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  54740. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  54741. var id = targetedAnimation.targetId;
  54742. var targetNode = scene.getNodeByID(id);
  54743. if (targetNode != null) {
  54744. animationGroup.addTargetedAnimation(animation, targetNode);
  54745. }
  54746. }
  54747. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null) {
  54748. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  54749. }
  54750. return animationGroup;
  54751. };
  54752. /**
  54753. * Returns the string "AnimationGroup"
  54754. * @returns "AnimationGroup"
  54755. */
  54756. AnimationGroup.prototype.getClassName = function () {
  54757. return "AnimationGroup";
  54758. };
  54759. /**
  54760. * Creates a detailled string about the object
  54761. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  54762. * @returns a string representing the object
  54763. */
  54764. AnimationGroup.prototype.toString = function (fullDetails) {
  54765. var ret = "Name: " + this.name;
  54766. ret += ", type: " + this.getClassName();
  54767. if (fullDetails) {
  54768. ret += ", from: " + this._from;
  54769. ret += ", to: " + this._to;
  54770. ret += ", isStarted: " + this._isStarted;
  54771. ret += ", speedRatio: " + this._speedRatio;
  54772. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  54773. ret += ", animatables length: " + this._animatables;
  54774. }
  54775. return ret;
  54776. };
  54777. return AnimationGroup;
  54778. }());
  54779. BABYLON.AnimationGroup = AnimationGroup;
  54780. })(BABYLON || (BABYLON = {}));
  54781. //# sourceMappingURL=animationGroup.js.map
  54782. var BABYLON;
  54783. (function (BABYLON) {
  54784. // Static values to help the garbage collector
  54785. // Quaternion
  54786. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  54787. // Vector3
  54788. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  54789. // Vector2
  54790. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  54791. // Size
  54792. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  54793. // Color3
  54794. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  54795. /**
  54796. * Defines a runtime animation
  54797. */
  54798. var RuntimeAnimation = /** @class */ (function () {
  54799. /**
  54800. * Create a new RuntimeAnimation object
  54801. * @param target defines the target of the animation
  54802. * @param animation defines the source animation object
  54803. * @param scene defines the hosting scene
  54804. * @param host defines the initiating Animatable
  54805. */
  54806. function RuntimeAnimation(target, animation, scene, host) {
  54807. var _this = this;
  54808. this._events = new Array();
  54809. /**
  54810. * The current frame of the runtime animation
  54811. */
  54812. this._currentFrame = 0;
  54813. /**
  54814. * The original value of the runtime animation
  54815. */
  54816. this._originalValue = new Array();
  54817. /**
  54818. * The offsets cache of the runtime animation
  54819. */
  54820. this._offsetsCache = {};
  54821. /**
  54822. * The high limits cache of the runtime animation
  54823. */
  54824. this._highLimitsCache = {};
  54825. /**
  54826. * Specifies if the runtime animation has been stopped
  54827. */
  54828. this._stopped = false;
  54829. /**
  54830. * The blending factor of the runtime animation
  54831. */
  54832. this._blendingFactor = 0;
  54833. /**
  54834. * The target path of the runtime animation
  54835. */
  54836. this._targetPath = "";
  54837. /**
  54838. * The weight of the runtime animation
  54839. */
  54840. this._weight = 1.0;
  54841. /**
  54842. * The ratio offset of the runtime animation
  54843. */
  54844. this._ratioOffset = 0;
  54845. /**
  54846. * The previous delay of the runtime animation
  54847. */
  54848. this._previousDelay = 0;
  54849. /**
  54850. * The previous ratio of the runtime animation
  54851. */
  54852. this._previousRatio = 0;
  54853. this._animation = animation;
  54854. this._target = target;
  54855. this._scene = scene;
  54856. this._host = host;
  54857. animation._runtimeAnimations.push(this);
  54858. // Cloning events locally
  54859. var events = animation.getEvents();
  54860. if (events && events.length > 0) {
  54861. events.forEach(function (e) {
  54862. _this._events.push(e._clone());
  54863. });
  54864. }
  54865. }
  54866. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  54867. /**
  54868. * Gets the current frame of the runtime animation
  54869. */
  54870. get: function () {
  54871. return this._currentFrame;
  54872. },
  54873. enumerable: true,
  54874. configurable: true
  54875. });
  54876. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  54877. /**
  54878. * Gets the weight of the runtime animation
  54879. */
  54880. get: function () {
  54881. return this._weight;
  54882. },
  54883. enumerable: true,
  54884. configurable: true
  54885. });
  54886. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  54887. /**
  54888. * Gets the current value of the runtime animation
  54889. */
  54890. get: function () {
  54891. return this._currentValue;
  54892. },
  54893. enumerable: true,
  54894. configurable: true
  54895. });
  54896. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  54897. /**
  54898. * Gets the target path of the runtime animation
  54899. */
  54900. get: function () {
  54901. return this._targetPath;
  54902. },
  54903. enumerable: true,
  54904. configurable: true
  54905. });
  54906. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  54907. /**
  54908. * Gets the actual target of the runtime animation
  54909. */
  54910. get: function () {
  54911. return this._activeTarget;
  54912. },
  54913. enumerable: true,
  54914. configurable: true
  54915. });
  54916. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  54917. /**
  54918. * Gets the animation from the runtime animation
  54919. */
  54920. get: function () {
  54921. return this._animation;
  54922. },
  54923. enumerable: true,
  54924. configurable: true
  54925. });
  54926. /**
  54927. * Resets the runtime animation to the beginning
  54928. * @param restoreOriginal defines whether to restore the target property to the original value
  54929. */
  54930. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  54931. if (restoreOriginal === void 0) { restoreOriginal = false; }
  54932. if (restoreOriginal) {
  54933. if (this._target instanceof Array) {
  54934. var index = 0;
  54935. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  54936. var target = _a[_i];
  54937. if (this._originalValue[index] !== undefined) {
  54938. this._setValue(target, this._originalValue[index], -1);
  54939. }
  54940. index++;
  54941. }
  54942. }
  54943. else {
  54944. if (this._originalValue[0] !== undefined) {
  54945. this._setValue(this._target, this._originalValue[0], -1);
  54946. }
  54947. }
  54948. }
  54949. this._offsetsCache = {};
  54950. this._highLimitsCache = {};
  54951. this._currentFrame = 0;
  54952. this._blendingFactor = 0;
  54953. this._originalValue = new Array();
  54954. // Events
  54955. for (var index = 0; index < this._events.length; index++) {
  54956. this._events[index].isDone = false;
  54957. }
  54958. };
  54959. /**
  54960. * Specifies if the runtime animation is stopped
  54961. * @returns Boolean specifying if the runtime animation is stopped
  54962. */
  54963. RuntimeAnimation.prototype.isStopped = function () {
  54964. return this._stopped;
  54965. };
  54966. /**
  54967. * Disposes of the runtime animation
  54968. */
  54969. RuntimeAnimation.prototype.dispose = function () {
  54970. var index = this._animation.runtimeAnimations.indexOf(this);
  54971. if (index > -1) {
  54972. this._animation.runtimeAnimations.splice(index, 1);
  54973. }
  54974. };
  54975. /**
  54976. * Interpolates the animation from the current frame
  54977. * @param currentFrame The frame to interpolate the animation to
  54978. * @param repeatCount The number of times that the animation should loop
  54979. * @param loopMode The type of looping mode to use
  54980. * @param offsetValue Animation offset value
  54981. * @param highLimitValue The high limit value
  54982. * @returns The interpolated value
  54983. */
  54984. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  54985. this._currentFrame = currentFrame;
  54986. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  54987. this._workValue = BABYLON.Matrix.Zero();
  54988. }
  54989. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  54990. };
  54991. /**
  54992. * Apply the interpolated value to the target
  54993. * @param currentValue defines the value computed by the animation
  54994. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  54995. */
  54996. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  54997. if (weight === void 0) { weight = 1.0; }
  54998. if (this._target instanceof Array) {
  54999. var index = 0;
  55000. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  55001. var target = _a[_i];
  55002. this._setValue(target, currentValue, weight, index);
  55003. index++;
  55004. }
  55005. }
  55006. else {
  55007. this._setValue(this._target, currentValue, weight);
  55008. }
  55009. };
  55010. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  55011. if (targetIndex === void 0) { targetIndex = 0; }
  55012. // Set value
  55013. var path;
  55014. var destination;
  55015. var targetPropertyPath = this._animation.targetPropertyPath;
  55016. if (targetPropertyPath.length > 1) {
  55017. var property = target[targetPropertyPath[0]];
  55018. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  55019. property = property[targetPropertyPath[index]];
  55020. }
  55021. path = targetPropertyPath[targetPropertyPath.length - 1];
  55022. destination = property;
  55023. }
  55024. else {
  55025. path = targetPropertyPath[0];
  55026. destination = target;
  55027. }
  55028. this._targetPath = path;
  55029. this._activeTarget = destination;
  55030. this._weight = weight;
  55031. if (this._originalValue[targetIndex] === undefined) {
  55032. var originalValue = void 0;
  55033. if (destination.getRestPose && path === "_matrix") { // For bones
  55034. originalValue = destination.getRestPose();
  55035. }
  55036. else {
  55037. originalValue = destination[path];
  55038. }
  55039. if (originalValue && originalValue.clone) {
  55040. this._originalValue[targetIndex] = originalValue.clone();
  55041. }
  55042. else {
  55043. this._originalValue[targetIndex] = originalValue;
  55044. }
  55045. }
  55046. // Blending
  55047. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  55048. if (enableBlending && this._blendingFactor <= 1.0) {
  55049. if (!this._originalBlendValue) {
  55050. var originalValue = destination[path];
  55051. if (originalValue.clone) {
  55052. this._originalBlendValue = originalValue.clone();
  55053. }
  55054. else {
  55055. this._originalBlendValue = originalValue;
  55056. }
  55057. }
  55058. if (this._originalBlendValue.m) { // Matrix
  55059. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  55060. if (this._currentValue) {
  55061. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  55062. }
  55063. else {
  55064. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  55065. }
  55066. }
  55067. else {
  55068. if (this._currentValue) {
  55069. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  55070. }
  55071. else {
  55072. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  55073. }
  55074. }
  55075. }
  55076. else {
  55077. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  55078. }
  55079. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  55080. this._blendingFactor += blendingSpeed;
  55081. }
  55082. else {
  55083. this._currentValue = currentValue;
  55084. }
  55085. if (weight !== -1.0) {
  55086. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  55087. }
  55088. else {
  55089. destination[path] = this._currentValue;
  55090. }
  55091. if (target.markAsDirty) {
  55092. target.markAsDirty(this._animation.targetProperty);
  55093. }
  55094. };
  55095. /**
  55096. * Gets the loop pmode of the runtime animation
  55097. * @returns Loop Mode
  55098. */
  55099. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  55100. if (this._target && this._target.animationPropertiesOverride) {
  55101. return this._target.animationPropertiesOverride.loopMode;
  55102. }
  55103. return this._animation.loopMode;
  55104. };
  55105. /**
  55106. * Move the current animation to a given frame
  55107. * @param frame defines the frame to move to
  55108. */
  55109. RuntimeAnimation.prototype.goToFrame = function (frame) {
  55110. var keys = this._animation.getKeys();
  55111. if (frame < keys[0].frame) {
  55112. frame = keys[0].frame;
  55113. }
  55114. else if (frame > keys[keys.length - 1].frame) {
  55115. frame = keys[keys.length - 1].frame;
  55116. }
  55117. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  55118. this.setValue(currentValue, -1);
  55119. };
  55120. /**
  55121. * @hidden Internal use only
  55122. */
  55123. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  55124. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  55125. this._ratioOffset = this._previousRatio - newRatio;
  55126. };
  55127. /**
  55128. * Execute the current animation
  55129. * @param delay defines the delay to add to the current frame
  55130. * @param from defines the lower bound of the animation range
  55131. * @param to defines the upper bound of the animation range
  55132. * @param loop defines if the current animation must loop
  55133. * @param speedRatio defines the current speed ratio
  55134. * @param weight defines the weight of the animation (default is -1 so no weight)
  55135. * @returns a boolean indicating if the animation is running
  55136. */
  55137. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  55138. if (weight === void 0) { weight = -1.0; }
  55139. var targetPropertyPath = this._animation.targetPropertyPath;
  55140. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  55141. this._stopped = true;
  55142. return false;
  55143. }
  55144. var returnValue = true;
  55145. var keys = this._animation.getKeys();
  55146. // Adding a start key at frame 0 if missing
  55147. if (keys[0].frame !== 0) {
  55148. var newKey = { frame: 0, value: keys[0].value };
  55149. keys.splice(0, 0, newKey);
  55150. }
  55151. // Adding a duplicate key when there is only one key at frame zero
  55152. else if (keys.length === 1) {
  55153. var newKey = { frame: 0.001, value: keys[0].value };
  55154. keys.push(newKey);
  55155. }
  55156. // Check limits
  55157. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  55158. from = keys[0].frame;
  55159. }
  55160. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  55161. to = keys[keys.length - 1].frame;
  55162. }
  55163. //to and from cannot be the same key
  55164. if (from === to) {
  55165. if (from > keys[0].frame) {
  55166. from--;
  55167. }
  55168. else if (to < keys[keys.length - 1].frame) {
  55169. to++;
  55170. }
  55171. }
  55172. // Compute ratio
  55173. var range = to - from;
  55174. var offsetValue;
  55175. // ratio represents the frame delta between from and to
  55176. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  55177. var highLimitValue = 0;
  55178. this._previousDelay = delay;
  55179. this._previousRatio = ratio;
  55180. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  55181. returnValue = false;
  55182. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  55183. }
  55184. else {
  55185. // Get max value if required
  55186. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  55187. var keyOffset = to.toString() + from.toString();
  55188. if (!this._offsetsCache[keyOffset]) {
  55189. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  55190. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  55191. switch (this._animation.dataType) {
  55192. // Float
  55193. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  55194. this._offsetsCache[keyOffset] = toValue - fromValue;
  55195. break;
  55196. // Quaternion
  55197. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  55198. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55199. break;
  55200. // Vector3
  55201. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  55202. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55203. // Vector2
  55204. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  55205. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55206. // Size
  55207. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  55208. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55209. // Color3
  55210. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  55211. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  55212. default:
  55213. break;
  55214. }
  55215. this._highLimitsCache[keyOffset] = toValue;
  55216. }
  55217. highLimitValue = this._highLimitsCache[keyOffset];
  55218. offsetValue = this._offsetsCache[keyOffset];
  55219. }
  55220. }
  55221. if (offsetValue === undefined) {
  55222. switch (this._animation.dataType) {
  55223. // Float
  55224. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  55225. offsetValue = 0;
  55226. break;
  55227. // Quaternion
  55228. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  55229. offsetValue = _staticOffsetValueQuaternion;
  55230. break;
  55231. // Vector3
  55232. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  55233. offsetValue = _staticOffsetValueVector3;
  55234. break;
  55235. // Vector2
  55236. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  55237. offsetValue = _staticOffsetValueVector2;
  55238. break;
  55239. // Size
  55240. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  55241. offsetValue = _staticOffsetValueSize;
  55242. break;
  55243. // Color3
  55244. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  55245. offsetValue = _staticOffsetValueColor3;
  55246. }
  55247. }
  55248. // Compute value
  55249. var repeatCount = (ratio / range) >> 0;
  55250. var currentFrame = returnValue ? from + ratio % range : to;
  55251. // Need to normalize?
  55252. if (this._host && this._host.syncRoot) {
  55253. var syncRoot = this._host.syncRoot;
  55254. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  55255. currentFrame = from + (to - from) * hostNormalizedFrame;
  55256. }
  55257. // Reset events if looping
  55258. var events = this._events;
  55259. if (range > 0 && this.currentFrame > currentFrame ||
  55260. range < 0 && this.currentFrame < currentFrame) {
  55261. // Need to reset animation events
  55262. for (var index = 0; index < events.length; index++) {
  55263. if (!events[index].onlyOnce) {
  55264. // reset event, the animation is looping
  55265. events[index].isDone = false;
  55266. }
  55267. }
  55268. }
  55269. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  55270. // Set value
  55271. this.setValue(currentValue, weight);
  55272. // Check events
  55273. for (var index = 0; index < events.length; index++) {
  55274. // Make sure current frame has passed event frame and that event frame is within the current range
  55275. // Also, handle both forward and reverse animations
  55276. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  55277. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  55278. var event = events[index];
  55279. if (!event.isDone) {
  55280. // If event should be done only once, remove it.
  55281. if (event.onlyOnce) {
  55282. events.splice(index, 1);
  55283. index--;
  55284. }
  55285. event.isDone = true;
  55286. event.action(currentFrame);
  55287. } // Don't do anything if the event has already be done.
  55288. }
  55289. }
  55290. if (!returnValue) {
  55291. this._stopped = true;
  55292. }
  55293. return returnValue;
  55294. };
  55295. return RuntimeAnimation;
  55296. }());
  55297. BABYLON.RuntimeAnimation = RuntimeAnimation;
  55298. })(BABYLON || (BABYLON = {}));
  55299. //# sourceMappingURL=runtimeAnimation.js.map
  55300. var BABYLON;
  55301. (function (BABYLON) {
  55302. /**
  55303. * Class used to store an actual running animation
  55304. */
  55305. var Animatable = /** @class */ (function () {
  55306. /**
  55307. * Creates a new Animatable
  55308. * @param scene defines the hosting scene
  55309. * @param target defines the target object
  55310. * @param fromFrame defines the starting frame number (default is 0)
  55311. * @param toFrame defines the ending frame number (default is 100)
  55312. * @param loopAnimation defines if the animation must loop (default is false)
  55313. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  55314. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  55315. * @param animations defines a group of animation to add to the new Animatable
  55316. */
  55317. function Animatable(scene,
  55318. /** defines the target object */
  55319. target,
  55320. /** defines the starting frame number (default is 0) */
  55321. fromFrame,
  55322. /** defines the ending frame number (default is 100) */
  55323. toFrame,
  55324. /** defines if the animation must loop (default is false) */
  55325. loopAnimation, speedRatio,
  55326. /** defines a callback to call when animation ends if it is not looping */
  55327. onAnimationEnd, animations) {
  55328. if (fromFrame === void 0) { fromFrame = 0; }
  55329. if (toFrame === void 0) { toFrame = 100; }
  55330. if (loopAnimation === void 0) { loopAnimation = false; }
  55331. if (speedRatio === void 0) { speedRatio = 1.0; }
  55332. this.target = target;
  55333. this.fromFrame = fromFrame;
  55334. this.toFrame = toFrame;
  55335. this.loopAnimation = loopAnimation;
  55336. this.onAnimationEnd = onAnimationEnd;
  55337. this._localDelayOffset = null;
  55338. this._pausedDelay = null;
  55339. this._runtimeAnimations = new Array();
  55340. this._paused = false;
  55341. this._speedRatio = 1;
  55342. this._weight = -1.0;
  55343. /**
  55344. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  55345. * This will only apply for non looping animation (default is true)
  55346. */
  55347. this.disposeOnEnd = true;
  55348. /**
  55349. * Gets a boolean indicating if the animation has started
  55350. */
  55351. this.animationStarted = false;
  55352. /**
  55353. * Observer raised when the animation ends
  55354. */
  55355. this.onAnimationEndObservable = new BABYLON.Observable();
  55356. this._scene = scene;
  55357. if (animations) {
  55358. this.appendAnimations(target, animations);
  55359. }
  55360. this._speedRatio = speedRatio;
  55361. scene._activeAnimatables.push(this);
  55362. }
  55363. Object.defineProperty(Animatable.prototype, "syncRoot", {
  55364. /**
  55365. * Gets the root Animatable used to synchronize and normalize animations
  55366. */
  55367. get: function () {
  55368. return this._syncRoot;
  55369. },
  55370. enumerable: true,
  55371. configurable: true
  55372. });
  55373. Object.defineProperty(Animatable.prototype, "masterFrame", {
  55374. /**
  55375. * Gets the current frame of the first RuntimeAnimation
  55376. * Used to synchronize Animatables
  55377. */
  55378. get: function () {
  55379. if (this._runtimeAnimations.length === 0) {
  55380. return 0;
  55381. }
  55382. return this._runtimeAnimations[0].currentFrame;
  55383. },
  55384. enumerable: true,
  55385. configurable: true
  55386. });
  55387. Object.defineProperty(Animatable.prototype, "weight", {
  55388. /**
  55389. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  55390. */
  55391. get: function () {
  55392. return this._weight;
  55393. },
  55394. set: function (value) {
  55395. if (value === -1) { // -1 is ok and means no weight
  55396. this._weight = -1;
  55397. return;
  55398. }
  55399. // Else weight must be in [0, 1] range
  55400. this._weight = Math.min(Math.max(value, 0), 1.0);
  55401. },
  55402. enumerable: true,
  55403. configurable: true
  55404. });
  55405. Object.defineProperty(Animatable.prototype, "speedRatio", {
  55406. /**
  55407. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  55408. */
  55409. get: function () {
  55410. return this._speedRatio;
  55411. },
  55412. set: function (value) {
  55413. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  55414. var animation = this._runtimeAnimations[index];
  55415. animation._prepareForSpeedRatioChange(value);
  55416. }
  55417. this._speedRatio = value;
  55418. },
  55419. enumerable: true,
  55420. configurable: true
  55421. });
  55422. // Methods
  55423. /**
  55424. * Synchronize and normalize current Animatable with a source Animatable
  55425. * This is useful when using animation weights and when animations are not of the same length
  55426. * @param root defines the root Animatable to synchronize with
  55427. * @returns the current Animatable
  55428. */
  55429. Animatable.prototype.syncWith = function (root) {
  55430. this._syncRoot = root;
  55431. if (root) {
  55432. // Make sure this animatable will animate after the root
  55433. var index = this._scene._activeAnimatables.indexOf(this);
  55434. if (index > -1) {
  55435. this._scene._activeAnimatables.splice(index, 1);
  55436. this._scene._activeAnimatables.push(this);
  55437. }
  55438. }
  55439. return this;
  55440. };
  55441. /**
  55442. * Gets the list of runtime animations
  55443. * @returns an array of RuntimeAnimation
  55444. */
  55445. Animatable.prototype.getAnimations = function () {
  55446. return this._runtimeAnimations;
  55447. };
  55448. /**
  55449. * Adds more animations to the current animatable
  55450. * @param target defines the target of the animations
  55451. * @param animations defines the new animations to add
  55452. */
  55453. Animatable.prototype.appendAnimations = function (target, animations) {
  55454. for (var index = 0; index < animations.length; index++) {
  55455. var animation = animations[index];
  55456. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  55457. }
  55458. };
  55459. /**
  55460. * Gets the source animation for a specific property
  55461. * @param property defines the propertyu to look for
  55462. * @returns null or the source animation for the given property
  55463. */
  55464. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  55465. var runtimeAnimations = this._runtimeAnimations;
  55466. for (var index = 0; index < runtimeAnimations.length; index++) {
  55467. if (runtimeAnimations[index].animation.targetProperty === property) {
  55468. return runtimeAnimations[index].animation;
  55469. }
  55470. }
  55471. return null;
  55472. };
  55473. /**
  55474. * Gets the runtime animation for a specific property
  55475. * @param property defines the propertyu to look for
  55476. * @returns null or the runtime animation for the given property
  55477. */
  55478. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  55479. var runtimeAnimations = this._runtimeAnimations;
  55480. for (var index = 0; index < runtimeAnimations.length; index++) {
  55481. if (runtimeAnimations[index].animation.targetProperty === property) {
  55482. return runtimeAnimations[index];
  55483. }
  55484. }
  55485. return null;
  55486. };
  55487. /**
  55488. * Resets the animatable to its original state
  55489. */
  55490. Animatable.prototype.reset = function () {
  55491. var runtimeAnimations = this._runtimeAnimations;
  55492. for (var index = 0; index < runtimeAnimations.length; index++) {
  55493. runtimeAnimations[index].reset(true);
  55494. }
  55495. this._localDelayOffset = null;
  55496. this._pausedDelay = null;
  55497. };
  55498. /**
  55499. * Allows the animatable to blend with current running animations
  55500. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  55501. * @param blendingSpeed defines the blending speed to use
  55502. */
  55503. Animatable.prototype.enableBlending = function (blendingSpeed) {
  55504. var runtimeAnimations = this._runtimeAnimations;
  55505. for (var index = 0; index < runtimeAnimations.length; index++) {
  55506. runtimeAnimations[index].animation.enableBlending = true;
  55507. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  55508. }
  55509. };
  55510. /**
  55511. * Disable animation blending
  55512. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  55513. */
  55514. Animatable.prototype.disableBlending = function () {
  55515. var runtimeAnimations = this._runtimeAnimations;
  55516. for (var index = 0; index < runtimeAnimations.length; index++) {
  55517. runtimeAnimations[index].animation.enableBlending = false;
  55518. }
  55519. };
  55520. /**
  55521. * Jump directly to a given frame
  55522. * @param frame defines the frame to jump to
  55523. */
  55524. Animatable.prototype.goToFrame = function (frame) {
  55525. var runtimeAnimations = this._runtimeAnimations;
  55526. if (runtimeAnimations[0]) {
  55527. var fps = runtimeAnimations[0].animation.framePerSecond;
  55528. var currentFrame = runtimeAnimations[0].currentFrame;
  55529. var adjustTime = frame - currentFrame;
  55530. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  55531. if (this._localDelayOffset === null) {
  55532. this._localDelayOffset = 0;
  55533. }
  55534. this._localDelayOffset -= delay;
  55535. }
  55536. for (var index = 0; index < runtimeAnimations.length; index++) {
  55537. runtimeAnimations[index].goToFrame(frame);
  55538. }
  55539. };
  55540. /**
  55541. * Pause the animation
  55542. */
  55543. Animatable.prototype.pause = function () {
  55544. if (this._paused) {
  55545. return;
  55546. }
  55547. this._paused = true;
  55548. };
  55549. /**
  55550. * Restart the animation
  55551. */
  55552. Animatable.prototype.restart = function () {
  55553. this._paused = false;
  55554. };
  55555. Animatable.prototype._raiseOnAnimationEnd = function () {
  55556. if (this.onAnimationEnd) {
  55557. this.onAnimationEnd();
  55558. }
  55559. this.onAnimationEndObservable.notifyObservers(this);
  55560. };
  55561. /**
  55562. * Stop and delete the current animation
  55563. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  55564. * @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)
  55565. */
  55566. Animatable.prototype.stop = function (animationName, targetMask) {
  55567. if (animationName || targetMask) {
  55568. var idx = this._scene._activeAnimatables.indexOf(this);
  55569. if (idx > -1) {
  55570. var runtimeAnimations = this._runtimeAnimations;
  55571. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  55572. var runtimeAnimation = runtimeAnimations[index];
  55573. if (animationName && runtimeAnimation.animation.name != animationName) {
  55574. continue;
  55575. }
  55576. if (targetMask && !targetMask(runtimeAnimation.target)) {
  55577. continue;
  55578. }
  55579. runtimeAnimation.dispose();
  55580. runtimeAnimations.splice(index, 1);
  55581. }
  55582. if (runtimeAnimations.length == 0) {
  55583. this._scene._activeAnimatables.splice(idx, 1);
  55584. this._raiseOnAnimationEnd();
  55585. }
  55586. }
  55587. }
  55588. else {
  55589. var index = this._scene._activeAnimatables.indexOf(this);
  55590. if (index > -1) {
  55591. this._scene._activeAnimatables.splice(index, 1);
  55592. var runtimeAnimations = this._runtimeAnimations;
  55593. for (var index = 0; index < runtimeAnimations.length; index++) {
  55594. runtimeAnimations[index].dispose();
  55595. }
  55596. this._raiseOnAnimationEnd();
  55597. }
  55598. }
  55599. };
  55600. /**
  55601. * Wait asynchronously for the animation to end
  55602. * @returns a promise which will be fullfilled when the animation ends
  55603. */
  55604. Animatable.prototype.waitAsync = function () {
  55605. var _this = this;
  55606. return new Promise(function (resolve, reject) {
  55607. _this.onAnimationEndObservable.add(function () {
  55608. resolve(_this);
  55609. }, undefined, undefined, _this, true);
  55610. });
  55611. };
  55612. /** @hidden */
  55613. Animatable.prototype._animate = function (delay) {
  55614. if (this._paused) {
  55615. this.animationStarted = false;
  55616. if (this._pausedDelay === null) {
  55617. this._pausedDelay = delay;
  55618. }
  55619. return true;
  55620. }
  55621. if (this._localDelayOffset === null) {
  55622. this._localDelayOffset = delay;
  55623. this._pausedDelay = null;
  55624. }
  55625. else if (this._pausedDelay !== null) {
  55626. this._localDelayOffset += delay - this._pausedDelay;
  55627. this._pausedDelay = null;
  55628. }
  55629. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  55630. return true;
  55631. }
  55632. // Animating
  55633. var running = false;
  55634. var runtimeAnimations = this._runtimeAnimations;
  55635. var index;
  55636. for (index = 0; index < runtimeAnimations.length; index++) {
  55637. var animation = runtimeAnimations[index];
  55638. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  55639. running = running || isRunning;
  55640. }
  55641. this.animationStarted = running;
  55642. if (!running) {
  55643. if (this.disposeOnEnd) {
  55644. // Remove from active animatables
  55645. index = this._scene._activeAnimatables.indexOf(this);
  55646. this._scene._activeAnimatables.splice(index, 1);
  55647. // Dispose all runtime animations
  55648. for (index = 0; index < runtimeAnimations.length; index++) {
  55649. runtimeAnimations[index].dispose();
  55650. }
  55651. }
  55652. this._raiseOnAnimationEnd();
  55653. if (this.disposeOnEnd) {
  55654. this.onAnimationEnd = null;
  55655. this.onAnimationEndObservable.clear();
  55656. }
  55657. }
  55658. return running;
  55659. };
  55660. return Animatable;
  55661. }());
  55662. BABYLON.Animatable = Animatable;
  55663. })(BABYLON || (BABYLON = {}));
  55664. //# sourceMappingURL=animatable.js.map
  55665. var BABYLON;
  55666. (function (BABYLON) {
  55667. /**
  55668. * Base class used for every default easing function.
  55669. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55670. */
  55671. var EasingFunction = /** @class */ (function () {
  55672. function EasingFunction() {
  55673. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  55674. }
  55675. /**
  55676. * Sets the easing mode of the current function.
  55677. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  55678. */
  55679. EasingFunction.prototype.setEasingMode = function (easingMode) {
  55680. var n = Math.min(Math.max(easingMode, 0), 2);
  55681. this._easingMode = n;
  55682. };
  55683. /**
  55684. * Gets the current easing mode.
  55685. * @returns the easing mode
  55686. */
  55687. EasingFunction.prototype.getEasingMode = function () {
  55688. return this._easingMode;
  55689. };
  55690. /**
  55691. * @hidden
  55692. */
  55693. EasingFunction.prototype.easeInCore = function (gradient) {
  55694. throw new Error('You must implement this method');
  55695. };
  55696. /**
  55697. * Given an input gradient between 0 and 1, this returns the corrseponding value
  55698. * of the easing function.
  55699. * @param gradient Defines the value between 0 and 1 we want the easing value for
  55700. * @returns the corresponding value on the curve defined by the easing function
  55701. */
  55702. EasingFunction.prototype.ease = function (gradient) {
  55703. switch (this._easingMode) {
  55704. case EasingFunction.EASINGMODE_EASEIN:
  55705. return this.easeInCore(gradient);
  55706. case EasingFunction.EASINGMODE_EASEOUT:
  55707. return (1 - this.easeInCore(1 - gradient));
  55708. }
  55709. if (gradient >= 0.5) {
  55710. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  55711. }
  55712. return (this.easeInCore(gradient * 2) * 0.5);
  55713. };
  55714. /**
  55715. * Interpolation follows the mathematical formula associated with the easing function.
  55716. */
  55717. EasingFunction.EASINGMODE_EASEIN = 0;
  55718. /**
  55719. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  55720. */
  55721. EasingFunction.EASINGMODE_EASEOUT = 1;
  55722. /**
  55723. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  55724. */
  55725. EasingFunction.EASINGMODE_EASEINOUT = 2;
  55726. return EasingFunction;
  55727. }());
  55728. BABYLON.EasingFunction = EasingFunction;
  55729. /**
  55730. * Easing function with a circle shape (see link below).
  55731. * @see https://easings.net/#easeInCirc
  55732. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55733. */
  55734. var CircleEase = /** @class */ (function (_super) {
  55735. __extends(CircleEase, _super);
  55736. function CircleEase() {
  55737. return _super !== null && _super.apply(this, arguments) || this;
  55738. }
  55739. /** @hidden */
  55740. CircleEase.prototype.easeInCore = function (gradient) {
  55741. gradient = Math.max(0, Math.min(1, gradient));
  55742. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  55743. };
  55744. return CircleEase;
  55745. }(EasingFunction));
  55746. BABYLON.CircleEase = CircleEase;
  55747. /**
  55748. * Easing function with a ease back shape (see link below).
  55749. * @see https://easings.net/#easeInBack
  55750. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55751. */
  55752. var BackEase = /** @class */ (function (_super) {
  55753. __extends(BackEase, _super);
  55754. /**
  55755. * Instantiates a back ease easing
  55756. * @see https://easings.net/#easeInBack
  55757. * @param amplitude Defines the amplitude of the function
  55758. */
  55759. function BackEase(
  55760. /** Defines the amplitude of the function */
  55761. amplitude) {
  55762. if (amplitude === void 0) { amplitude = 1; }
  55763. var _this = _super.call(this) || this;
  55764. _this.amplitude = amplitude;
  55765. return _this;
  55766. }
  55767. /** @hidden */
  55768. BackEase.prototype.easeInCore = function (gradient) {
  55769. var num = Math.max(0, this.amplitude);
  55770. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  55771. };
  55772. return BackEase;
  55773. }(EasingFunction));
  55774. BABYLON.BackEase = BackEase;
  55775. /**
  55776. * Easing function with a bouncing shape (see link below).
  55777. * @see https://easings.net/#easeInBounce
  55778. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55779. */
  55780. var BounceEase = /** @class */ (function (_super) {
  55781. __extends(BounceEase, _super);
  55782. /**
  55783. * Instantiates a bounce easing
  55784. * @see https://easings.net/#easeInBounce
  55785. * @param bounces Defines the number of bounces
  55786. * @param bounciness Defines the amplitude of the bounce
  55787. */
  55788. function BounceEase(
  55789. /** Defines the number of bounces */
  55790. bounces,
  55791. /** Defines the amplitude of the bounce */
  55792. bounciness) {
  55793. if (bounces === void 0) { bounces = 3; }
  55794. if (bounciness === void 0) { bounciness = 2; }
  55795. var _this = _super.call(this) || this;
  55796. _this.bounces = bounces;
  55797. _this.bounciness = bounciness;
  55798. return _this;
  55799. }
  55800. /** @hidden */
  55801. BounceEase.prototype.easeInCore = function (gradient) {
  55802. var y = Math.max(0.0, this.bounces);
  55803. var bounciness = this.bounciness;
  55804. if (bounciness <= 1.0) {
  55805. bounciness = 1.001;
  55806. }
  55807. var num9 = Math.pow(bounciness, y);
  55808. var num5 = 1.0 - bounciness;
  55809. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  55810. var num15 = gradient * num4;
  55811. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  55812. var num3 = Math.floor(num65);
  55813. var num13 = num3 + 1.0;
  55814. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  55815. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  55816. var num7 = (num8 + num12) * 0.5;
  55817. var num6 = gradient - num7;
  55818. var num2 = num7 - num8;
  55819. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  55820. };
  55821. return BounceEase;
  55822. }(EasingFunction));
  55823. BABYLON.BounceEase = BounceEase;
  55824. /**
  55825. * Easing function with a power of 3 shape (see link below).
  55826. * @see https://easings.net/#easeInCubic
  55827. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55828. */
  55829. var CubicEase = /** @class */ (function (_super) {
  55830. __extends(CubicEase, _super);
  55831. function CubicEase() {
  55832. return _super !== null && _super.apply(this, arguments) || this;
  55833. }
  55834. /** @hidden */
  55835. CubicEase.prototype.easeInCore = function (gradient) {
  55836. return (gradient * gradient * gradient);
  55837. };
  55838. return CubicEase;
  55839. }(EasingFunction));
  55840. BABYLON.CubicEase = CubicEase;
  55841. /**
  55842. * Easing function with an elastic shape (see link below).
  55843. * @see https://easings.net/#easeInElastic
  55844. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55845. */
  55846. var ElasticEase = /** @class */ (function (_super) {
  55847. __extends(ElasticEase, _super);
  55848. /**
  55849. * Instantiates an elastic easing function
  55850. * @see https://easings.net/#easeInElastic
  55851. * @param oscillations Defines the number of oscillations
  55852. * @param springiness Defines the amplitude of the oscillations
  55853. */
  55854. function ElasticEase(
  55855. /** Defines the number of oscillations*/
  55856. oscillations,
  55857. /** Defines the amplitude of the oscillations*/
  55858. springiness) {
  55859. if (oscillations === void 0) { oscillations = 3; }
  55860. if (springiness === void 0) { springiness = 3; }
  55861. var _this = _super.call(this) || this;
  55862. _this.oscillations = oscillations;
  55863. _this.springiness = springiness;
  55864. return _this;
  55865. }
  55866. /** @hidden */
  55867. ElasticEase.prototype.easeInCore = function (gradient) {
  55868. var num2;
  55869. var num3 = Math.max(0.0, this.oscillations);
  55870. var num = Math.max(0.0, this.springiness);
  55871. if (num == 0) {
  55872. num2 = gradient;
  55873. }
  55874. else {
  55875. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  55876. }
  55877. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  55878. };
  55879. return ElasticEase;
  55880. }(EasingFunction));
  55881. BABYLON.ElasticEase = ElasticEase;
  55882. /**
  55883. * Easing function with an exponential shape (see link below).
  55884. * @see https://easings.net/#easeInExpo
  55885. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55886. */
  55887. var ExponentialEase = /** @class */ (function (_super) {
  55888. __extends(ExponentialEase, _super);
  55889. /**
  55890. * Instantiates an exponential easing function
  55891. * @see https://easings.net/#easeInExpo
  55892. * @param exponent Defines the exponent of the function
  55893. */
  55894. function ExponentialEase(
  55895. /** Defines the exponent of the function */
  55896. exponent) {
  55897. if (exponent === void 0) { exponent = 2; }
  55898. var _this = _super.call(this) || this;
  55899. _this.exponent = exponent;
  55900. return _this;
  55901. }
  55902. /** @hidden */
  55903. ExponentialEase.prototype.easeInCore = function (gradient) {
  55904. if (this.exponent <= 0) {
  55905. return gradient;
  55906. }
  55907. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  55908. };
  55909. return ExponentialEase;
  55910. }(EasingFunction));
  55911. BABYLON.ExponentialEase = ExponentialEase;
  55912. /**
  55913. * Easing function with a power shape (see link below).
  55914. * @see https://easings.net/#easeInQuad
  55915. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55916. */
  55917. var PowerEase = /** @class */ (function (_super) {
  55918. __extends(PowerEase, _super);
  55919. /**
  55920. * Instantiates an power base easing function
  55921. * @see https://easings.net/#easeInQuad
  55922. * @param power Defines the power of the function
  55923. */
  55924. function PowerEase(
  55925. /** Defines the power of the function */
  55926. power) {
  55927. if (power === void 0) { power = 2; }
  55928. var _this = _super.call(this) || this;
  55929. _this.power = power;
  55930. return _this;
  55931. }
  55932. /** @hidden */
  55933. PowerEase.prototype.easeInCore = function (gradient) {
  55934. var y = Math.max(0.0, this.power);
  55935. return Math.pow(gradient, y);
  55936. };
  55937. return PowerEase;
  55938. }(EasingFunction));
  55939. BABYLON.PowerEase = PowerEase;
  55940. /**
  55941. * Easing function with a power of 2 shape (see link below).
  55942. * @see https://easings.net/#easeInQuad
  55943. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55944. */
  55945. var QuadraticEase = /** @class */ (function (_super) {
  55946. __extends(QuadraticEase, _super);
  55947. function QuadraticEase() {
  55948. return _super !== null && _super.apply(this, arguments) || this;
  55949. }
  55950. /** @hidden */
  55951. QuadraticEase.prototype.easeInCore = function (gradient) {
  55952. return (gradient * gradient);
  55953. };
  55954. return QuadraticEase;
  55955. }(EasingFunction));
  55956. BABYLON.QuadraticEase = QuadraticEase;
  55957. /**
  55958. * Easing function with a power of 4 shape (see link below).
  55959. * @see https://easings.net/#easeInQuart
  55960. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55961. */
  55962. var QuarticEase = /** @class */ (function (_super) {
  55963. __extends(QuarticEase, _super);
  55964. function QuarticEase() {
  55965. return _super !== null && _super.apply(this, arguments) || this;
  55966. }
  55967. /** @hidden */
  55968. QuarticEase.prototype.easeInCore = function (gradient) {
  55969. return (gradient * gradient * gradient * gradient);
  55970. };
  55971. return QuarticEase;
  55972. }(EasingFunction));
  55973. BABYLON.QuarticEase = QuarticEase;
  55974. /**
  55975. * Easing function with a power of 5 shape (see link below).
  55976. * @see https://easings.net/#easeInQuint
  55977. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55978. */
  55979. var QuinticEase = /** @class */ (function (_super) {
  55980. __extends(QuinticEase, _super);
  55981. function QuinticEase() {
  55982. return _super !== null && _super.apply(this, arguments) || this;
  55983. }
  55984. /** @hidden */
  55985. QuinticEase.prototype.easeInCore = function (gradient) {
  55986. return (gradient * gradient * gradient * gradient * gradient);
  55987. };
  55988. return QuinticEase;
  55989. }(EasingFunction));
  55990. BABYLON.QuinticEase = QuinticEase;
  55991. /**
  55992. * Easing function with a sin shape (see link below).
  55993. * @see https://easings.net/#easeInSine
  55994. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  55995. */
  55996. var SineEase = /** @class */ (function (_super) {
  55997. __extends(SineEase, _super);
  55998. function SineEase() {
  55999. return _super !== null && _super.apply(this, arguments) || this;
  56000. }
  56001. /** @hidden */
  56002. SineEase.prototype.easeInCore = function (gradient) {
  56003. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  56004. };
  56005. return SineEase;
  56006. }(EasingFunction));
  56007. BABYLON.SineEase = SineEase;
  56008. /**
  56009. * Easing function with a bezier shape (see link below).
  56010. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  56011. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  56012. */
  56013. var BezierCurveEase = /** @class */ (function (_super) {
  56014. __extends(BezierCurveEase, _super);
  56015. /**
  56016. * Instantiates a bezier function
  56017. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  56018. * @param x1 Defines the x component of the start tangent in the bezier curve
  56019. * @param y1 Defines the y component of the start tangent in the bezier curve
  56020. * @param x2 Defines the x component of the end tangent in the bezier curve
  56021. * @param y2 Defines the y component of the end tangent in the bezier curve
  56022. */
  56023. function BezierCurveEase(
  56024. /** Defines the x component of the start tangent in the bezier curve */
  56025. x1,
  56026. /** Defines the y component of the start tangent in the bezier curve */
  56027. y1,
  56028. /** Defines the x component of the end tangent in the bezier curve */
  56029. x2,
  56030. /** Defines the y component of the end tangent in the bezier curve */
  56031. y2) {
  56032. if (x1 === void 0) { x1 = 0; }
  56033. if (y1 === void 0) { y1 = 0; }
  56034. if (x2 === void 0) { x2 = 1; }
  56035. if (y2 === void 0) { y2 = 1; }
  56036. var _this = _super.call(this) || this;
  56037. _this.x1 = x1;
  56038. _this.y1 = y1;
  56039. _this.x2 = x2;
  56040. _this.y2 = y2;
  56041. return _this;
  56042. }
  56043. /** @hidden */
  56044. BezierCurveEase.prototype.easeInCore = function (gradient) {
  56045. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  56046. };
  56047. return BezierCurveEase;
  56048. }(EasingFunction));
  56049. BABYLON.BezierCurveEase = BezierCurveEase;
  56050. })(BABYLON || (BABYLON = {}));
  56051. //# sourceMappingURL=easing.js.map
  56052. var BABYLON;
  56053. (function (BABYLON) {
  56054. /**
  56055. * A Condition applied to an Action
  56056. */
  56057. var Condition = /** @class */ (function () {
  56058. /**
  56059. * Creates a new Condition
  56060. * @param actionManager the manager of the action the condition is applied to
  56061. */
  56062. function Condition(actionManager) {
  56063. this._actionManager = actionManager;
  56064. }
  56065. /**
  56066. * Check if the current condition is valid
  56067. * @returns a boolean
  56068. */
  56069. Condition.prototype.isValid = function () {
  56070. return true;
  56071. };
  56072. /**
  56073. * Internal only
  56074. * @hidden
  56075. */
  56076. Condition.prototype._getProperty = function (propertyPath) {
  56077. return this._actionManager._getProperty(propertyPath);
  56078. };
  56079. /**
  56080. * Internal only
  56081. * @hidden
  56082. */
  56083. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  56084. return this._actionManager._getEffectiveTarget(target, propertyPath);
  56085. };
  56086. /**
  56087. * Serialize placeholder for child classes
  56088. * @returns the serialized object
  56089. */
  56090. Condition.prototype.serialize = function () {
  56091. };
  56092. /**
  56093. * Internal only
  56094. * @hidden
  56095. */
  56096. Condition.prototype._serialize = function (serializedCondition) {
  56097. return {
  56098. type: 2,
  56099. children: [],
  56100. name: serializedCondition.name,
  56101. properties: serializedCondition.properties
  56102. };
  56103. };
  56104. return Condition;
  56105. }());
  56106. BABYLON.Condition = Condition;
  56107. /**
  56108. * Defines specific conditional operators as extensions of Condition
  56109. */
  56110. var ValueCondition = /** @class */ (function (_super) {
  56111. __extends(ValueCondition, _super);
  56112. /**
  56113. * Creates a new ValueCondition
  56114. * @param actionManager manager for the action the condition applies to
  56115. * @param target for the action
  56116. * @param propertyPath path to specify the property of the target the conditional operator uses
  56117. * @param value the value compared by the conditional operator against the current value of the property
  56118. * @param operator the conditional operator, default ValueCondition.IsEqual
  56119. */
  56120. function ValueCondition(actionManager, target,
  56121. /** path to specify the property of the target the conditional operator uses */
  56122. propertyPath,
  56123. /** the value compared by the conditional operator against the current value of the property */
  56124. value,
  56125. /** the conditional operator, default ValueCondition.IsEqual */
  56126. operator) {
  56127. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  56128. var _this = _super.call(this, actionManager) || this;
  56129. _this.propertyPath = propertyPath;
  56130. _this.value = value;
  56131. _this.operator = operator;
  56132. _this._target = target;
  56133. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  56134. _this._property = _this._getProperty(_this.propertyPath);
  56135. return _this;
  56136. }
  56137. Object.defineProperty(ValueCondition, "IsEqual", {
  56138. /**
  56139. * returns the number for IsEqual
  56140. */
  56141. get: function () {
  56142. return ValueCondition._IsEqual;
  56143. },
  56144. enumerable: true,
  56145. configurable: true
  56146. });
  56147. Object.defineProperty(ValueCondition, "IsDifferent", {
  56148. /**
  56149. * Returns the number for IsDifferent
  56150. */
  56151. get: function () {
  56152. return ValueCondition._IsDifferent;
  56153. },
  56154. enumerable: true,
  56155. configurable: true
  56156. });
  56157. Object.defineProperty(ValueCondition, "IsGreater", {
  56158. /**
  56159. * Returns the number for IsGreater
  56160. */
  56161. get: function () {
  56162. return ValueCondition._IsGreater;
  56163. },
  56164. enumerable: true,
  56165. configurable: true
  56166. });
  56167. Object.defineProperty(ValueCondition, "IsLesser", {
  56168. /**
  56169. * Returns the number for IsLesser
  56170. */
  56171. get: function () {
  56172. return ValueCondition._IsLesser;
  56173. },
  56174. enumerable: true,
  56175. configurable: true
  56176. });
  56177. /**
  56178. * Compares the given value with the property value for the specified conditional operator
  56179. * @returns the result of the comparison
  56180. */
  56181. ValueCondition.prototype.isValid = function () {
  56182. switch (this.operator) {
  56183. case ValueCondition.IsGreater:
  56184. return this._effectiveTarget[this._property] > this.value;
  56185. case ValueCondition.IsLesser:
  56186. return this._effectiveTarget[this._property] < this.value;
  56187. case ValueCondition.IsEqual:
  56188. case ValueCondition.IsDifferent:
  56189. var check;
  56190. if (this.value.equals) {
  56191. check = this.value.equals(this._effectiveTarget[this._property]);
  56192. }
  56193. else {
  56194. check = this.value === this._effectiveTarget[this._property];
  56195. }
  56196. return this.operator === ValueCondition.IsEqual ? check : !check;
  56197. }
  56198. return false;
  56199. };
  56200. /**
  56201. * Serialize the ValueCondition into a JSON compatible object
  56202. * @returns serialization object
  56203. */
  56204. ValueCondition.prototype.serialize = function () {
  56205. return this._serialize({
  56206. name: "ValueCondition",
  56207. properties: [
  56208. BABYLON.Action._GetTargetProperty(this._target),
  56209. { name: "propertyPath", value: this.propertyPath },
  56210. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  56211. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  56212. ]
  56213. });
  56214. };
  56215. /**
  56216. * Gets the name of the conditional operator for the ValueCondition
  56217. * @param operator the conditional operator
  56218. * @returns the name
  56219. */
  56220. ValueCondition.GetOperatorName = function (operator) {
  56221. switch (operator) {
  56222. case ValueCondition._IsEqual: return "IsEqual";
  56223. case ValueCondition._IsDifferent: return "IsDifferent";
  56224. case ValueCondition._IsGreater: return "IsGreater";
  56225. case ValueCondition._IsLesser: return "IsLesser";
  56226. default: return "";
  56227. }
  56228. };
  56229. /**
  56230. * Internal only
  56231. * @hidden
  56232. */
  56233. ValueCondition._IsEqual = 0;
  56234. /**
  56235. * Internal only
  56236. * @hidden
  56237. */
  56238. ValueCondition._IsDifferent = 1;
  56239. /**
  56240. * Internal only
  56241. * @hidden
  56242. */
  56243. ValueCondition._IsGreater = 2;
  56244. /**
  56245. * Internal only
  56246. * @hidden
  56247. */
  56248. ValueCondition._IsLesser = 3;
  56249. return ValueCondition;
  56250. }(Condition));
  56251. BABYLON.ValueCondition = ValueCondition;
  56252. /**
  56253. * Defines a predicate condition as an extension of Condition
  56254. */
  56255. var PredicateCondition = /** @class */ (function (_super) {
  56256. __extends(PredicateCondition, _super);
  56257. /**
  56258. * Creates a new PredicateCondition
  56259. * @param actionManager manager for the action the condition applies to
  56260. * @param predicate defines the predicate function used to validate the condition
  56261. */
  56262. function PredicateCondition(actionManager,
  56263. /** defines the predicate function used to validate the condition */
  56264. predicate) {
  56265. var _this = _super.call(this, actionManager) || this;
  56266. _this.predicate = predicate;
  56267. return _this;
  56268. }
  56269. /**
  56270. * @returns the validity of the predicate condition
  56271. */
  56272. PredicateCondition.prototype.isValid = function () {
  56273. return this.predicate();
  56274. };
  56275. return PredicateCondition;
  56276. }(Condition));
  56277. BABYLON.PredicateCondition = PredicateCondition;
  56278. /**
  56279. * Defines a state condition as an extension of Condition
  56280. */
  56281. var StateCondition = /** @class */ (function (_super) {
  56282. __extends(StateCondition, _super);
  56283. /**
  56284. * Creates a new StateCondition
  56285. * @param actionManager manager for the action the condition applies to
  56286. * @param target of the condition
  56287. * @param value to compare with target state
  56288. */
  56289. function StateCondition(actionManager, target,
  56290. /** Value to compare with target state */
  56291. value) {
  56292. var _this = _super.call(this, actionManager) || this;
  56293. _this.value = value;
  56294. _this._target = target;
  56295. return _this;
  56296. }
  56297. /**
  56298. * Gets a boolean indicating if the current condition is met
  56299. * @returns the validity of the state
  56300. */
  56301. StateCondition.prototype.isValid = function () {
  56302. return this._target.state === this.value;
  56303. };
  56304. /**
  56305. * Serialize the StateCondition into a JSON compatible object
  56306. * @returns serialization object
  56307. */
  56308. StateCondition.prototype.serialize = function () {
  56309. return this._serialize({
  56310. name: "StateCondition",
  56311. properties: [
  56312. BABYLON.Action._GetTargetProperty(this._target),
  56313. { name: "value", value: this.value }
  56314. ]
  56315. });
  56316. };
  56317. return StateCondition;
  56318. }(Condition));
  56319. BABYLON.StateCondition = StateCondition;
  56320. })(BABYLON || (BABYLON = {}));
  56321. //# sourceMappingURL=condition.js.map
  56322. var BABYLON;
  56323. (function (BABYLON) {
  56324. /**
  56325. * The action to be carried out following a trigger
  56326. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  56327. */
  56328. var Action = /** @class */ (function () {
  56329. /**
  56330. * Creates a new Action
  56331. * @param triggerOptions the trigger, with or without parameters, for the action
  56332. * @param condition an optional determinant of action
  56333. */
  56334. function Action(
  56335. /** the trigger, with or without parameters, for the action */
  56336. triggerOptions, condition) {
  56337. this.triggerOptions = triggerOptions;
  56338. /**
  56339. * An event triggered prior to action being executed.
  56340. */
  56341. this.onBeforeExecuteObservable = new BABYLON.Observable();
  56342. if (triggerOptions.parameter) {
  56343. this.trigger = triggerOptions.trigger;
  56344. this._triggerParameter = triggerOptions.parameter;
  56345. }
  56346. else if (triggerOptions.trigger) {
  56347. this.trigger = triggerOptions.trigger;
  56348. }
  56349. else {
  56350. this.trigger = triggerOptions;
  56351. }
  56352. this._nextActiveAction = this;
  56353. this._condition = condition;
  56354. }
  56355. /**
  56356. * Internal only
  56357. * @hidden
  56358. */
  56359. Action.prototype._prepare = function () {
  56360. };
  56361. /**
  56362. * Gets the trigger parameters
  56363. * @returns the trigger parameters
  56364. */
  56365. Action.prototype.getTriggerParameter = function () {
  56366. return this._triggerParameter;
  56367. };
  56368. /**
  56369. * Internal only - executes current action event
  56370. * @hidden
  56371. */
  56372. Action.prototype._executeCurrent = function (evt) {
  56373. if (this._nextActiveAction._condition) {
  56374. var condition = this._nextActiveAction._condition;
  56375. var currentRenderId = this._actionManager.getScene().getRenderId();
  56376. // We cache the current evaluation for the current frame
  56377. if (condition._evaluationId === currentRenderId) {
  56378. if (!condition._currentResult) {
  56379. return;
  56380. }
  56381. }
  56382. else {
  56383. condition._evaluationId = currentRenderId;
  56384. if (!condition.isValid()) {
  56385. condition._currentResult = false;
  56386. return;
  56387. }
  56388. condition._currentResult = true;
  56389. }
  56390. }
  56391. this.onBeforeExecuteObservable.notifyObservers(this);
  56392. this._nextActiveAction.execute(evt);
  56393. this.skipToNextActiveAction();
  56394. };
  56395. /**
  56396. * Execute placeholder for child classes
  56397. * @param evt optional action event
  56398. */
  56399. Action.prototype.execute = function (evt) {
  56400. };
  56401. /**
  56402. * Skips to next active action
  56403. */
  56404. Action.prototype.skipToNextActiveAction = function () {
  56405. if (this._nextActiveAction._child) {
  56406. if (!this._nextActiveAction._child._actionManager) {
  56407. this._nextActiveAction._child._actionManager = this._actionManager;
  56408. }
  56409. this._nextActiveAction = this._nextActiveAction._child;
  56410. }
  56411. else {
  56412. this._nextActiveAction = this;
  56413. }
  56414. };
  56415. /**
  56416. * Adds action to chain of actions, may be a DoNothingAction
  56417. * @param action defines the next action to execute
  56418. * @returns The action passed in
  56419. * @see https://www.babylonjs-playground.com/#1T30HR#0
  56420. */
  56421. Action.prototype.then = function (action) {
  56422. this._child = action;
  56423. action._actionManager = this._actionManager;
  56424. action._prepare();
  56425. return action;
  56426. };
  56427. /**
  56428. * Internal only
  56429. * @hidden
  56430. */
  56431. Action.prototype._getProperty = function (propertyPath) {
  56432. return this._actionManager._getProperty(propertyPath);
  56433. };
  56434. /**
  56435. * Internal only
  56436. * @hidden
  56437. */
  56438. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  56439. return this._actionManager._getEffectiveTarget(target, propertyPath);
  56440. };
  56441. /**
  56442. * Serialize placeholder for child classes
  56443. * @param parent of child
  56444. * @returns the serialized object
  56445. */
  56446. Action.prototype.serialize = function (parent) {
  56447. };
  56448. /**
  56449. * Internal only called by serialize
  56450. * @hidden
  56451. */
  56452. Action.prototype._serialize = function (serializedAction, parent) {
  56453. var serializationObject = {
  56454. type: 1,
  56455. children: [],
  56456. name: serializedAction.name,
  56457. properties: serializedAction.properties || []
  56458. };
  56459. // Serialize child
  56460. if (this._child) {
  56461. this._child.serialize(serializationObject);
  56462. }
  56463. // Check if "this" has a condition
  56464. if (this._condition) {
  56465. var serializedCondition = this._condition.serialize();
  56466. serializedCondition.children.push(serializationObject);
  56467. if (parent) {
  56468. parent.children.push(serializedCondition);
  56469. }
  56470. return serializedCondition;
  56471. }
  56472. if (parent) {
  56473. parent.children.push(serializationObject);
  56474. }
  56475. return serializationObject;
  56476. };
  56477. /**
  56478. * Internal only
  56479. * @hidden
  56480. */
  56481. Action._SerializeValueAsString = function (value) {
  56482. if (typeof value === "number") {
  56483. return value.toString();
  56484. }
  56485. if (typeof value === "boolean") {
  56486. return value ? "true" : "false";
  56487. }
  56488. if (value instanceof BABYLON.Vector2) {
  56489. return value.x + ", " + value.y;
  56490. }
  56491. if (value instanceof BABYLON.Vector3) {
  56492. return value.x + ", " + value.y + ", " + value.z;
  56493. }
  56494. if (value instanceof BABYLON.Color3) {
  56495. return value.r + ", " + value.g + ", " + value.b;
  56496. }
  56497. if (value instanceof BABYLON.Color4) {
  56498. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  56499. }
  56500. return value; // string
  56501. };
  56502. /**
  56503. * Internal only
  56504. * @hidden
  56505. */
  56506. Action._GetTargetProperty = function (target) {
  56507. return {
  56508. name: "target",
  56509. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  56510. : target instanceof BABYLON.Light ? "LightProperties"
  56511. : target instanceof BABYLON.Camera ? "CameraProperties"
  56512. : "SceneProperties",
  56513. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  56514. };
  56515. };
  56516. return Action;
  56517. }());
  56518. BABYLON.Action = Action;
  56519. })(BABYLON || (BABYLON = {}));
  56520. //# sourceMappingURL=action.js.map
  56521. var BABYLON;
  56522. (function (BABYLON) {
  56523. /**
  56524. * ActionEvent is the event being sent when an action is triggered.
  56525. */
  56526. var ActionEvent = /** @class */ (function () {
  56527. /**
  56528. * Creates a new ActionEvent
  56529. * @param source The mesh or sprite that triggered the action
  56530. * @param pointerX The X mouse cursor position at the time of the event
  56531. * @param pointerY The Y mouse cursor position at the time of the event
  56532. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  56533. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  56534. * @param additionalData additional data for the event
  56535. */
  56536. function ActionEvent(
  56537. /** The mesh or sprite that triggered the action */
  56538. source,
  56539. /** The X mouse cursor position at the time of the event */
  56540. pointerX,
  56541. /** The Y mouse cursor position at the time of the event */
  56542. pointerY,
  56543. /** The mesh that is currently pointed at (can be null) */
  56544. meshUnderPointer,
  56545. /** the original (browser) event that triggered the ActionEvent */
  56546. sourceEvent,
  56547. /** additional data for the event */
  56548. additionalData) {
  56549. this.source = source;
  56550. this.pointerX = pointerX;
  56551. this.pointerY = pointerY;
  56552. this.meshUnderPointer = meshUnderPointer;
  56553. this.sourceEvent = sourceEvent;
  56554. this.additionalData = additionalData;
  56555. }
  56556. /**
  56557. * Helper function to auto-create an ActionEvent from a source mesh.
  56558. * @param source The source mesh that triggered the event
  56559. * @param evt The original (browser) event
  56560. * @param additionalData additional data for the event
  56561. * @returns the new ActionEvent
  56562. */
  56563. ActionEvent.CreateNew = function (source, evt, additionalData) {
  56564. var scene = source.getScene();
  56565. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  56566. };
  56567. /**
  56568. * Helper function to auto-create an ActionEvent from a source sprite
  56569. * @param source The source sprite that triggered the event
  56570. * @param scene Scene associated with the sprite
  56571. * @param evt The original (browser) event
  56572. * @param additionalData additional data for the event
  56573. * @returns the new ActionEvent
  56574. */
  56575. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  56576. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  56577. };
  56578. /**
  56579. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  56580. * @param scene the scene where the event occurred
  56581. * @param evt The original (browser) event
  56582. * @returns the new ActionEvent
  56583. */
  56584. ActionEvent.CreateNewFromScene = function (scene, evt) {
  56585. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  56586. };
  56587. /**
  56588. * Helper function to auto-create an ActionEvent from a primitive
  56589. * @param prim defines the target primitive
  56590. * @param pointerPos defines the pointer position
  56591. * @param evt The original (browser) event
  56592. * @param additionalData additional data for the event
  56593. * @returns the new ActionEvent
  56594. */
  56595. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  56596. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  56597. };
  56598. return ActionEvent;
  56599. }());
  56600. BABYLON.ActionEvent = ActionEvent;
  56601. /**
  56602. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  56603. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  56604. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56605. */
  56606. var ActionManager = /** @class */ (function () {
  56607. /**
  56608. * Creates a new action manager
  56609. * @param scene defines the hosting scene
  56610. */
  56611. function ActionManager(scene) {
  56612. // Members
  56613. /** Gets the list of actions */
  56614. this.actions = new Array();
  56615. /** Gets the cursor to use when hovering items */
  56616. this.hoverCursor = '';
  56617. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56618. scene.actionManagers.push(this);
  56619. }
  56620. // Methods
  56621. /**
  56622. * Releases all associated resources
  56623. */
  56624. ActionManager.prototype.dispose = function () {
  56625. var index = this._scene.actionManagers.indexOf(this);
  56626. for (var i = 0; i < this.actions.length; i++) {
  56627. var action = this.actions[i];
  56628. ActionManager.Triggers[action.trigger]--;
  56629. if (ActionManager.Triggers[action.trigger] === 0) {
  56630. delete ActionManager.Triggers[action.trigger];
  56631. }
  56632. }
  56633. if (index > -1) {
  56634. this._scene.actionManagers.splice(index, 1);
  56635. }
  56636. };
  56637. /**
  56638. * Gets hosting scene
  56639. * @returns the hosting scene
  56640. */
  56641. ActionManager.prototype.getScene = function () {
  56642. return this._scene;
  56643. };
  56644. /**
  56645. * Does this action manager handles actions of any of the given triggers
  56646. * @param triggers defines the triggers to be tested
  56647. * @return a boolean indicating whether one (or more) of the triggers is handled
  56648. */
  56649. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  56650. for (var index = 0; index < this.actions.length; index++) {
  56651. var action = this.actions[index];
  56652. if (triggers.indexOf(action.trigger) > -1) {
  56653. return true;
  56654. }
  56655. }
  56656. return false;
  56657. };
  56658. /**
  56659. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  56660. * speed.
  56661. * @param triggerA defines the trigger to be tested
  56662. * @param triggerB defines the trigger to be tested
  56663. * @return a boolean indicating whether one (or more) of the triggers is handled
  56664. */
  56665. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  56666. for (var index = 0; index < this.actions.length; index++) {
  56667. var action = this.actions[index];
  56668. if (triggerA == action.trigger || triggerB == action.trigger) {
  56669. return true;
  56670. }
  56671. }
  56672. return false;
  56673. };
  56674. /**
  56675. * Does this action manager handles actions of a given trigger
  56676. * @param trigger defines the trigger to be tested
  56677. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  56678. * @return whether the trigger is handled
  56679. */
  56680. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  56681. for (var index = 0; index < this.actions.length; index++) {
  56682. var action = this.actions[index];
  56683. if (action.trigger === trigger) {
  56684. if (parameterPredicate) {
  56685. if (parameterPredicate(action.getTriggerParameter())) {
  56686. return true;
  56687. }
  56688. }
  56689. else {
  56690. return true;
  56691. }
  56692. }
  56693. }
  56694. return false;
  56695. };
  56696. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  56697. /**
  56698. * Does this action manager has pointer triggers
  56699. */
  56700. get: function () {
  56701. for (var index = 0; index < this.actions.length; index++) {
  56702. var action = this.actions[index];
  56703. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  56704. return true;
  56705. }
  56706. }
  56707. return false;
  56708. },
  56709. enumerable: true,
  56710. configurable: true
  56711. });
  56712. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  56713. /**
  56714. * Does this action manager has pick triggers
  56715. */
  56716. get: function () {
  56717. for (var index = 0; index < this.actions.length; index++) {
  56718. var action = this.actions[index];
  56719. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  56720. return true;
  56721. }
  56722. }
  56723. return false;
  56724. },
  56725. enumerable: true,
  56726. configurable: true
  56727. });
  56728. Object.defineProperty(ActionManager, "HasTriggers", {
  56729. /**
  56730. * Does exist one action manager with at least one trigger
  56731. **/
  56732. get: function () {
  56733. for (var t in ActionManager.Triggers) {
  56734. if (ActionManager.Triggers.hasOwnProperty(t)) {
  56735. return true;
  56736. }
  56737. }
  56738. return false;
  56739. },
  56740. enumerable: true,
  56741. configurable: true
  56742. });
  56743. Object.defineProperty(ActionManager, "HasPickTriggers", {
  56744. /**
  56745. * Does exist one action manager with at least one pick trigger
  56746. **/
  56747. get: function () {
  56748. for (var t in ActionManager.Triggers) {
  56749. if (ActionManager.Triggers.hasOwnProperty(t)) {
  56750. var t_int = parseInt(t);
  56751. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  56752. return true;
  56753. }
  56754. }
  56755. }
  56756. return false;
  56757. },
  56758. enumerable: true,
  56759. configurable: true
  56760. });
  56761. /**
  56762. * Does exist one action manager that handles actions of a given trigger
  56763. * @param trigger defines the trigger to be tested
  56764. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  56765. **/
  56766. ActionManager.HasSpecificTrigger = function (trigger) {
  56767. for (var t in ActionManager.Triggers) {
  56768. if (ActionManager.Triggers.hasOwnProperty(t)) {
  56769. var t_int = parseInt(t);
  56770. if (t_int === trigger) {
  56771. return true;
  56772. }
  56773. }
  56774. }
  56775. return false;
  56776. };
  56777. /**
  56778. * Registers an action to this action manager
  56779. * @param action defines the action to be registered
  56780. * @return the action amended (prepared) after registration
  56781. */
  56782. ActionManager.prototype.registerAction = function (action) {
  56783. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  56784. if (this.getScene().actionManager !== this) {
  56785. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  56786. return null;
  56787. }
  56788. }
  56789. this.actions.push(action);
  56790. if (ActionManager.Triggers[action.trigger]) {
  56791. ActionManager.Triggers[action.trigger]++;
  56792. }
  56793. else {
  56794. ActionManager.Triggers[action.trigger] = 1;
  56795. }
  56796. action._actionManager = this;
  56797. action._prepare();
  56798. return action;
  56799. };
  56800. /**
  56801. * Unregisters an action to this action manager
  56802. * @param action defines the action to be unregistered
  56803. * @return a boolean indicating whether the action has been unregistered
  56804. */
  56805. ActionManager.prototype.unregisterAction = function (action) {
  56806. var index = this.actions.indexOf(action);
  56807. if (index !== -1) {
  56808. this.actions.splice(index, 1);
  56809. ActionManager.Triggers[action.trigger] -= 1;
  56810. if (ActionManager.Triggers[action.trigger] === 0) {
  56811. delete ActionManager.Triggers[action.trigger];
  56812. }
  56813. delete action._actionManager;
  56814. return true;
  56815. }
  56816. return false;
  56817. };
  56818. /**
  56819. * Process a specific trigger
  56820. * @param trigger defines the trigger to process
  56821. * @param evt defines the event details to be processed
  56822. */
  56823. ActionManager.prototype.processTrigger = function (trigger, evt) {
  56824. for (var index = 0; index < this.actions.length; index++) {
  56825. var action = this.actions[index];
  56826. if (action.trigger === trigger) {
  56827. if (evt) {
  56828. if (trigger === ActionManager.OnKeyUpTrigger
  56829. || trigger === ActionManager.OnKeyDownTrigger) {
  56830. var parameter = action.getTriggerParameter();
  56831. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  56832. if (!parameter.toLowerCase) {
  56833. continue;
  56834. }
  56835. var lowerCase = parameter.toLowerCase();
  56836. if (lowerCase !== evt.sourceEvent.key) {
  56837. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  56838. var actualkey = String.fromCharCode(unicode).toLowerCase();
  56839. if (actualkey !== lowerCase) {
  56840. continue;
  56841. }
  56842. }
  56843. }
  56844. }
  56845. }
  56846. action._executeCurrent(evt);
  56847. }
  56848. }
  56849. };
  56850. /** @hidden */
  56851. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  56852. var properties = propertyPath.split(".");
  56853. for (var index = 0; index < properties.length - 1; index++) {
  56854. target = target[properties[index]];
  56855. }
  56856. return target;
  56857. };
  56858. /** @hidden */
  56859. ActionManager.prototype._getProperty = function (propertyPath) {
  56860. var properties = propertyPath.split(".");
  56861. return properties[properties.length - 1];
  56862. };
  56863. /**
  56864. * Serialize this manager to a JSON object
  56865. * @param name defines the property name to store this manager
  56866. * @returns a JSON representation of this manager
  56867. */
  56868. ActionManager.prototype.serialize = function (name) {
  56869. var root = {
  56870. children: new Array(),
  56871. name: name,
  56872. type: 3,
  56873. properties: new Array() // Empty for root but required
  56874. };
  56875. for (var i = 0; i < this.actions.length; i++) {
  56876. var triggerObject = {
  56877. type: 0,
  56878. children: new Array(),
  56879. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  56880. properties: new Array()
  56881. };
  56882. var triggerOptions = this.actions[i].triggerOptions;
  56883. if (triggerOptions && typeof triggerOptions !== "number") {
  56884. if (triggerOptions.parameter instanceof BABYLON.Node) {
  56885. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  56886. }
  56887. else {
  56888. var parameter = {};
  56889. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  56890. if (triggerOptions.parameter && triggerOptions.parameter.mesh) {
  56891. parameter._meshId = triggerOptions.parameter.mesh.id;
  56892. }
  56893. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  56894. }
  56895. }
  56896. // Serialize child action, recursively
  56897. this.actions[i].serialize(triggerObject);
  56898. // Add serialized trigger
  56899. root.children.push(triggerObject);
  56900. }
  56901. return root;
  56902. };
  56903. /**
  56904. * Creates a new ActionManager from a JSON data
  56905. * @param parsedActions defines the JSON data to read from
  56906. * @param object defines the hosting mesh
  56907. * @param scene defines the hosting scene
  56908. */
  56909. ActionManager.Parse = function (parsedActions, object, scene) {
  56910. var actionManager = new ActionManager(scene);
  56911. if (object === null) {
  56912. scene.actionManager = actionManager;
  56913. }
  56914. else {
  56915. object.actionManager = actionManager;
  56916. }
  56917. // instanciate a new object
  56918. var instanciate = function (name, params) {
  56919. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  56920. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  56921. newInstance.constructor.apply(newInstance, params);
  56922. return newInstance;
  56923. };
  56924. var parseParameter = function (name, value, target, propertyPath) {
  56925. if (propertyPath === null) {
  56926. // String, boolean or float
  56927. var floatValue = parseFloat(value);
  56928. if (value === "true" || value === "false") {
  56929. return value === "true";
  56930. }
  56931. else {
  56932. return isNaN(floatValue) ? value : floatValue;
  56933. }
  56934. }
  56935. var effectiveTarget = propertyPath.split(".");
  56936. var values = value.split(",");
  56937. // Get effective Target
  56938. for (var i = 0; i < effectiveTarget.length; i++) {
  56939. target = target[effectiveTarget[i]];
  56940. }
  56941. // Return appropriate value with its type
  56942. if (typeof (target) === "boolean") {
  56943. return values[0] === "true";
  56944. }
  56945. if (typeof (target) === "string") {
  56946. return values[0];
  56947. }
  56948. // Parameters with multiple values such as Vector3 etc.
  56949. var split = new Array();
  56950. for (var i = 0; i < values.length; i++) {
  56951. split.push(parseFloat(values[i]));
  56952. }
  56953. if (target instanceof BABYLON.Vector3) {
  56954. return BABYLON.Vector3.FromArray(split);
  56955. }
  56956. if (target instanceof BABYLON.Vector4) {
  56957. return BABYLON.Vector4.FromArray(split);
  56958. }
  56959. if (target instanceof BABYLON.Color3) {
  56960. return BABYLON.Color3.FromArray(split);
  56961. }
  56962. if (target instanceof BABYLON.Color4) {
  56963. return BABYLON.Color4.FromArray(split);
  56964. }
  56965. return parseFloat(values[0]);
  56966. };
  56967. // traverse graph per trigger
  56968. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  56969. if (combineArray === void 0) { combineArray = null; }
  56970. if (parsedAction.detached) {
  56971. return;
  56972. }
  56973. var parameters = new Array();
  56974. var target = null;
  56975. var propertyPath = null;
  56976. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  56977. // Parameters
  56978. if (parsedAction.type === 2) {
  56979. parameters.push(actionManager);
  56980. }
  56981. else {
  56982. parameters.push(trigger);
  56983. }
  56984. if (combine) {
  56985. var actions = new Array();
  56986. for (var j = 0; j < parsedAction.combine.length; j++) {
  56987. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  56988. }
  56989. parameters.push(actions);
  56990. }
  56991. else {
  56992. for (var i = 0; i < parsedAction.properties.length; i++) {
  56993. var value = parsedAction.properties[i].value;
  56994. var name = parsedAction.properties[i].name;
  56995. var targetType = parsedAction.properties[i].targetType;
  56996. if (name === "target") {
  56997. if (targetType !== null && targetType === "SceneProperties") {
  56998. value = target = scene;
  56999. }
  57000. else {
  57001. value = target = scene.getNodeByName(value);
  57002. }
  57003. }
  57004. else if (name === "parent") {
  57005. value = scene.getNodeByName(value);
  57006. }
  57007. else if (name === "sound") {
  57008. // Can not externalize to component, so only checks for the presence off the API.
  57009. if (scene.getSoundByName) {
  57010. value = scene.getSoundByName(value);
  57011. }
  57012. }
  57013. else if (name !== "propertyPath") {
  57014. if (parsedAction.type === 2 && name === "operator") {
  57015. value = BABYLON.ValueCondition[value];
  57016. }
  57017. else {
  57018. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  57019. }
  57020. }
  57021. else {
  57022. propertyPath = value;
  57023. }
  57024. parameters.push(value);
  57025. }
  57026. }
  57027. if (combineArray === null) {
  57028. parameters.push(condition);
  57029. }
  57030. else {
  57031. parameters.push(null);
  57032. }
  57033. // If interpolate value action
  57034. if (parsedAction.name === "InterpolateValueAction") {
  57035. var param = parameters[parameters.length - 2];
  57036. parameters[parameters.length - 1] = param;
  57037. parameters[parameters.length - 2] = condition;
  57038. }
  57039. // Action or condition(s) and not CombineAction
  57040. var newAction = instanciate(parsedAction.name, parameters);
  57041. if (newAction instanceof BABYLON.Condition && condition !== null) {
  57042. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  57043. if (action) {
  57044. action.then(nothing);
  57045. }
  57046. else {
  57047. actionManager.registerAction(nothing);
  57048. }
  57049. action = nothing;
  57050. }
  57051. if (combineArray === null) {
  57052. if (newAction instanceof BABYLON.Condition) {
  57053. condition = newAction;
  57054. newAction = action;
  57055. }
  57056. else {
  57057. condition = null;
  57058. if (action) {
  57059. action.then(newAction);
  57060. }
  57061. else {
  57062. actionManager.registerAction(newAction);
  57063. }
  57064. }
  57065. }
  57066. else {
  57067. combineArray.push(newAction);
  57068. }
  57069. for (var i = 0; i < parsedAction.children.length; i++) {
  57070. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  57071. }
  57072. };
  57073. // triggers
  57074. for (var i = 0; i < parsedActions.children.length; i++) {
  57075. var triggerParams;
  57076. var trigger = parsedActions.children[i];
  57077. if (trigger.properties.length > 0) {
  57078. var param = trigger.properties[0].value;
  57079. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  57080. if (value._meshId) {
  57081. value.mesh = scene.getMeshByID(value._meshId);
  57082. }
  57083. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  57084. }
  57085. else {
  57086. triggerParams = ActionManager[trigger.name];
  57087. }
  57088. for (var j = 0; j < trigger.children.length; j++) {
  57089. if (!trigger.detached) {
  57090. traverse(trigger.children[j], triggerParams, null, null);
  57091. }
  57092. }
  57093. }
  57094. };
  57095. /**
  57096. * Get a trigger name by index
  57097. * @param trigger defines the trigger index
  57098. * @returns a trigger name
  57099. */
  57100. ActionManager.GetTriggerName = function (trigger) {
  57101. switch (trigger) {
  57102. case 0: return "NothingTrigger";
  57103. case 1: return "OnPickTrigger";
  57104. case 2: return "OnLeftPickTrigger";
  57105. case 3: return "OnRightPickTrigger";
  57106. case 4: return "OnCenterPickTrigger";
  57107. case 5: return "OnPickDownTrigger";
  57108. case 6: return "OnPickUpTrigger";
  57109. case 7: return "OnLongPressTrigger";
  57110. case 8: return "OnPointerOverTrigger";
  57111. case 9: return "OnPointerOutTrigger";
  57112. case 10: return "OnEveryFrameTrigger";
  57113. case 11: return "OnIntersectionEnterTrigger";
  57114. case 12: return "OnIntersectionExitTrigger";
  57115. case 13: return "OnKeyDownTrigger";
  57116. case 14: return "OnKeyUpTrigger";
  57117. case 15: return "OnPickOutTrigger";
  57118. default: return "";
  57119. }
  57120. };
  57121. /**
  57122. * Nothing
  57123. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57124. */
  57125. ActionManager.NothingTrigger = 0;
  57126. /**
  57127. * On pick
  57128. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57129. */
  57130. ActionManager.OnPickTrigger = 1;
  57131. /**
  57132. * On left pick
  57133. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57134. */
  57135. ActionManager.OnLeftPickTrigger = 2;
  57136. /**
  57137. * On right pick
  57138. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57139. */
  57140. ActionManager.OnRightPickTrigger = 3;
  57141. /**
  57142. * On center pick
  57143. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57144. */
  57145. ActionManager.OnCenterPickTrigger = 4;
  57146. /**
  57147. * On pick down
  57148. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57149. */
  57150. ActionManager.OnPickDownTrigger = 5;
  57151. /**
  57152. * On double pick
  57153. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57154. */
  57155. ActionManager.OnDoublePickTrigger = 6;
  57156. /**
  57157. * On pick up
  57158. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57159. */
  57160. ActionManager.OnPickUpTrigger = 7;
  57161. /**
  57162. * On pick out.
  57163. * This trigger will only be raised if you also declared a OnPickDown
  57164. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57165. */
  57166. ActionManager.OnPickOutTrigger = 16;
  57167. /**
  57168. * On long press
  57169. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57170. */
  57171. ActionManager.OnLongPressTrigger = 8;
  57172. /**
  57173. * On pointer over
  57174. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57175. */
  57176. ActionManager.OnPointerOverTrigger = 9;
  57177. /**
  57178. * On pointer out
  57179. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57180. */
  57181. ActionManager.OnPointerOutTrigger = 10;
  57182. /**
  57183. * On every frame
  57184. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57185. */
  57186. ActionManager.OnEveryFrameTrigger = 11;
  57187. /**
  57188. * On intersection enter
  57189. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57190. */
  57191. ActionManager.OnIntersectionEnterTrigger = 12;
  57192. /**
  57193. * On intersection exit
  57194. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57195. */
  57196. ActionManager.OnIntersectionExitTrigger = 13;
  57197. /**
  57198. * On key down
  57199. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57200. */
  57201. ActionManager.OnKeyDownTrigger = 14;
  57202. /**
  57203. * On key up
  57204. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  57205. */
  57206. ActionManager.OnKeyUpTrigger = 15;
  57207. /** Gets the list of active triggers */
  57208. ActionManager.Triggers = {};
  57209. return ActionManager;
  57210. }());
  57211. BABYLON.ActionManager = ActionManager;
  57212. })(BABYLON || (BABYLON = {}));
  57213. //# sourceMappingURL=actionManager.js.map
  57214. var BABYLON;
  57215. (function (BABYLON) {
  57216. /**
  57217. * This defines an action responsible to change the value of a property
  57218. * by interpolating between its current value and the newly set one once triggered.
  57219. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57220. */
  57221. var InterpolateValueAction = /** @class */ (function (_super) {
  57222. __extends(InterpolateValueAction, _super);
  57223. /**
  57224. * Instantiate the action
  57225. * @param triggerOptions defines the trigger options
  57226. * @param target defines the object containing the value to interpolate
  57227. * @param propertyPath defines the path to the property in the target object
  57228. * @param value defines the target value at the end of the interpolation
  57229. * @param duration deines the time it will take for the property to interpolate to the value.
  57230. * @param condition defines the trigger related conditions
  57231. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  57232. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  57233. */
  57234. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  57235. if (duration === void 0) { duration = 1000; }
  57236. var _this = _super.call(this, triggerOptions, condition) || this;
  57237. /**
  57238. * Defines the time it will take for the property to interpolate to the value.
  57239. */
  57240. _this.duration = 1000;
  57241. /**
  57242. * Observable triggered once the interpolation animation has been done.
  57243. */
  57244. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  57245. _this.propertyPath = propertyPath;
  57246. _this.value = value;
  57247. _this.duration = duration;
  57248. _this.stopOtherAnimations = stopOtherAnimations;
  57249. _this.onInterpolationDone = onInterpolationDone;
  57250. _this._target = _this._effectiveTarget = target;
  57251. return _this;
  57252. }
  57253. /** @hidden */
  57254. InterpolateValueAction.prototype._prepare = function () {
  57255. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  57256. this._property = this._getProperty(this.propertyPath);
  57257. };
  57258. /**
  57259. * Execute the action starts the value interpolation.
  57260. */
  57261. InterpolateValueAction.prototype.execute = function () {
  57262. var _this = this;
  57263. var scene = this._actionManager.getScene();
  57264. var keys = [
  57265. {
  57266. frame: 0,
  57267. value: this._effectiveTarget[this._property]
  57268. }, {
  57269. frame: 100,
  57270. value: this.value
  57271. }
  57272. ];
  57273. var dataType;
  57274. if (typeof this.value === "number") {
  57275. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  57276. }
  57277. else if (this.value instanceof BABYLON.Color3) {
  57278. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  57279. }
  57280. else if (this.value instanceof BABYLON.Vector3) {
  57281. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  57282. }
  57283. else if (this.value instanceof BABYLON.Matrix) {
  57284. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  57285. }
  57286. else if (this.value instanceof BABYLON.Quaternion) {
  57287. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  57288. }
  57289. else {
  57290. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  57291. return;
  57292. }
  57293. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  57294. animation.setKeys(keys);
  57295. if (this.stopOtherAnimations) {
  57296. scene.stopAnimation(this._effectiveTarget);
  57297. }
  57298. var wrapper = function () {
  57299. _this.onInterpolationDoneObservable.notifyObservers(_this);
  57300. if (_this.onInterpolationDone) {
  57301. _this.onInterpolationDone();
  57302. }
  57303. };
  57304. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  57305. };
  57306. /**
  57307. * Serializes the actions and its related information.
  57308. * @param parent defines the object to serialize in
  57309. * @returns the serialized object
  57310. */
  57311. InterpolateValueAction.prototype.serialize = function (parent) {
  57312. return _super.prototype._serialize.call(this, {
  57313. name: "InterpolateValueAction",
  57314. properties: [
  57315. BABYLON.Action._GetTargetProperty(this._target),
  57316. { name: "propertyPath", value: this.propertyPath },
  57317. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  57318. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  57319. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  57320. ]
  57321. }, parent);
  57322. };
  57323. return InterpolateValueAction;
  57324. }(BABYLON.Action));
  57325. BABYLON.InterpolateValueAction = InterpolateValueAction;
  57326. })(BABYLON || (BABYLON = {}));
  57327. //# sourceMappingURL=interpolateValueAction.js.map
  57328. var BABYLON;
  57329. (function (BABYLON) {
  57330. /**
  57331. * This defines an action responsible to toggle a boolean once triggered.
  57332. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57333. */
  57334. var SwitchBooleanAction = /** @class */ (function (_super) {
  57335. __extends(SwitchBooleanAction, _super);
  57336. /**
  57337. * Instantiate the action
  57338. * @param triggerOptions defines the trigger options
  57339. * @param target defines the object containing the boolean
  57340. * @param propertyPath defines the path to the boolean property in the target object
  57341. * @param condition defines the trigger related conditions
  57342. */
  57343. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  57344. var _this = _super.call(this, triggerOptions, condition) || this;
  57345. _this.propertyPath = propertyPath;
  57346. _this._target = _this._effectiveTarget = target;
  57347. return _this;
  57348. }
  57349. /** @hidden */
  57350. SwitchBooleanAction.prototype._prepare = function () {
  57351. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  57352. this._property = this._getProperty(this.propertyPath);
  57353. };
  57354. /**
  57355. * Execute the action toggle the boolean value.
  57356. */
  57357. SwitchBooleanAction.prototype.execute = function () {
  57358. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  57359. };
  57360. /**
  57361. * Serializes the actions and its related information.
  57362. * @param parent defines the object to serialize in
  57363. * @returns the serialized object
  57364. */
  57365. SwitchBooleanAction.prototype.serialize = function (parent) {
  57366. return _super.prototype._serialize.call(this, {
  57367. name: "SwitchBooleanAction",
  57368. properties: [
  57369. BABYLON.Action._GetTargetProperty(this._target),
  57370. { name: "propertyPath", value: this.propertyPath }
  57371. ]
  57372. }, parent);
  57373. };
  57374. return SwitchBooleanAction;
  57375. }(BABYLON.Action));
  57376. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  57377. /**
  57378. * This defines an action responsible to set a the state field of the target
  57379. * to a desired value once triggered.
  57380. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57381. */
  57382. var SetStateAction = /** @class */ (function (_super) {
  57383. __extends(SetStateAction, _super);
  57384. /**
  57385. * Instantiate the action
  57386. * @param triggerOptions defines the trigger options
  57387. * @param target defines the object containing the state property
  57388. * @param value defines the value to store in the state field
  57389. * @param condition defines the trigger related conditions
  57390. */
  57391. function SetStateAction(triggerOptions, target, value, condition) {
  57392. var _this = _super.call(this, triggerOptions, condition) || this;
  57393. _this.value = value;
  57394. _this._target = target;
  57395. return _this;
  57396. }
  57397. /**
  57398. * Execute the action and store the value on the target state property.
  57399. */
  57400. SetStateAction.prototype.execute = function () {
  57401. this._target.state = this.value;
  57402. };
  57403. /**
  57404. * Serializes the actions and its related information.
  57405. * @param parent defines the object to serialize in
  57406. * @returns the serialized object
  57407. */
  57408. SetStateAction.prototype.serialize = function (parent) {
  57409. return _super.prototype._serialize.call(this, {
  57410. name: "SetStateAction",
  57411. properties: [
  57412. BABYLON.Action._GetTargetProperty(this._target),
  57413. { name: "value", value: this.value }
  57414. ]
  57415. }, parent);
  57416. };
  57417. return SetStateAction;
  57418. }(BABYLON.Action));
  57419. BABYLON.SetStateAction = SetStateAction;
  57420. /**
  57421. * This defines an action responsible to set a property of the target
  57422. * to a desired value once triggered.
  57423. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57424. */
  57425. var SetValueAction = /** @class */ (function (_super) {
  57426. __extends(SetValueAction, _super);
  57427. /**
  57428. * Instantiate the action
  57429. * @param triggerOptions defines the trigger options
  57430. * @param target defines the object containing the property
  57431. * @param propertyPath defines the path of the property to set in the target
  57432. * @param value defines the value to set in the property
  57433. * @param condition defines the trigger related conditions
  57434. */
  57435. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  57436. var _this = _super.call(this, triggerOptions, condition) || this;
  57437. _this.propertyPath = propertyPath;
  57438. _this.value = value;
  57439. _this._target = _this._effectiveTarget = target;
  57440. return _this;
  57441. }
  57442. /** @hidden */
  57443. SetValueAction.prototype._prepare = function () {
  57444. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  57445. this._property = this._getProperty(this.propertyPath);
  57446. };
  57447. /**
  57448. * Execute the action and set the targetted property to the desired value.
  57449. */
  57450. SetValueAction.prototype.execute = function () {
  57451. this._effectiveTarget[this._property] = this.value;
  57452. if (this._target.markAsDirty) {
  57453. this._target.markAsDirty(this._property);
  57454. }
  57455. };
  57456. /**
  57457. * Serializes the actions and its related information.
  57458. * @param parent defines the object to serialize in
  57459. * @returns the serialized object
  57460. */
  57461. SetValueAction.prototype.serialize = function (parent) {
  57462. return _super.prototype._serialize.call(this, {
  57463. name: "SetValueAction",
  57464. properties: [
  57465. BABYLON.Action._GetTargetProperty(this._target),
  57466. { name: "propertyPath", value: this.propertyPath },
  57467. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  57468. ]
  57469. }, parent);
  57470. };
  57471. return SetValueAction;
  57472. }(BABYLON.Action));
  57473. BABYLON.SetValueAction = SetValueAction;
  57474. /**
  57475. * This defines an action responsible to increment the target value
  57476. * to a desired value once triggered.
  57477. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57478. */
  57479. var IncrementValueAction = /** @class */ (function (_super) {
  57480. __extends(IncrementValueAction, _super);
  57481. /**
  57482. * Instantiate the action
  57483. * @param triggerOptions defines the trigger options
  57484. * @param target defines the object containing the property
  57485. * @param propertyPath defines the path of the property to increment in the target
  57486. * @param value defines the value value we should increment the property by
  57487. * @param condition defines the trigger related conditions
  57488. */
  57489. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  57490. var _this = _super.call(this, triggerOptions, condition) || this;
  57491. _this.propertyPath = propertyPath;
  57492. _this.value = value;
  57493. _this._target = _this._effectiveTarget = target;
  57494. return _this;
  57495. }
  57496. /** @hidden */
  57497. IncrementValueAction.prototype._prepare = function () {
  57498. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  57499. this._property = this._getProperty(this.propertyPath);
  57500. if (typeof this._effectiveTarget[this._property] !== "number") {
  57501. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  57502. }
  57503. };
  57504. /**
  57505. * Execute the action and increment the target of the value amount.
  57506. */
  57507. IncrementValueAction.prototype.execute = function () {
  57508. this._effectiveTarget[this._property] += this.value;
  57509. if (this._target.markAsDirty) {
  57510. this._target.markAsDirty(this._property);
  57511. }
  57512. };
  57513. /**
  57514. * Serializes the actions and its related information.
  57515. * @param parent defines the object to serialize in
  57516. * @returns the serialized object
  57517. */
  57518. IncrementValueAction.prototype.serialize = function (parent) {
  57519. return _super.prototype._serialize.call(this, {
  57520. name: "IncrementValueAction",
  57521. properties: [
  57522. BABYLON.Action._GetTargetProperty(this._target),
  57523. { name: "propertyPath", value: this.propertyPath },
  57524. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  57525. ]
  57526. }, parent);
  57527. };
  57528. return IncrementValueAction;
  57529. }(BABYLON.Action));
  57530. BABYLON.IncrementValueAction = IncrementValueAction;
  57531. /**
  57532. * This defines an action responsible to start an animation once triggered.
  57533. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57534. */
  57535. var PlayAnimationAction = /** @class */ (function (_super) {
  57536. __extends(PlayAnimationAction, _super);
  57537. /**
  57538. * Instantiate the action
  57539. * @param triggerOptions defines the trigger options
  57540. * @param target defines the target animation or animation name
  57541. * @param from defines from where the animation should start (animation frame)
  57542. * @param end defines where the animation should stop (animation frame)
  57543. * @param loop defines if the animation should loop or stop after the first play
  57544. * @param condition defines the trigger related conditions
  57545. */
  57546. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  57547. var _this = _super.call(this, triggerOptions, condition) || this;
  57548. _this.from = from;
  57549. _this.to = to;
  57550. _this.loop = loop;
  57551. _this._target = target;
  57552. return _this;
  57553. }
  57554. /** @hidden */
  57555. PlayAnimationAction.prototype._prepare = function () {
  57556. };
  57557. /**
  57558. * Execute the action and play the animation.
  57559. */
  57560. PlayAnimationAction.prototype.execute = function () {
  57561. var scene = this._actionManager.getScene();
  57562. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  57563. };
  57564. /**
  57565. * Serializes the actions and its related information.
  57566. * @param parent defines the object to serialize in
  57567. * @returns the serialized object
  57568. */
  57569. PlayAnimationAction.prototype.serialize = function (parent) {
  57570. return _super.prototype._serialize.call(this, {
  57571. name: "PlayAnimationAction",
  57572. properties: [
  57573. BABYLON.Action._GetTargetProperty(this._target),
  57574. { name: "from", value: String(this.from) },
  57575. { name: "to", value: String(this.to) },
  57576. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  57577. ]
  57578. }, parent);
  57579. };
  57580. return PlayAnimationAction;
  57581. }(BABYLON.Action));
  57582. BABYLON.PlayAnimationAction = PlayAnimationAction;
  57583. /**
  57584. * This defines an action responsible to stop an animation once triggered.
  57585. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57586. */
  57587. var StopAnimationAction = /** @class */ (function (_super) {
  57588. __extends(StopAnimationAction, _super);
  57589. /**
  57590. * Instantiate the action
  57591. * @param triggerOptions defines the trigger options
  57592. * @param target defines the target animation or animation name
  57593. * @param condition defines the trigger related conditions
  57594. */
  57595. function StopAnimationAction(triggerOptions, target, condition) {
  57596. var _this = _super.call(this, triggerOptions, condition) || this;
  57597. _this._target = target;
  57598. return _this;
  57599. }
  57600. /** @hidden */
  57601. StopAnimationAction.prototype._prepare = function () {
  57602. };
  57603. /**
  57604. * Execute the action and stop the animation.
  57605. */
  57606. StopAnimationAction.prototype.execute = function () {
  57607. var scene = this._actionManager.getScene();
  57608. scene.stopAnimation(this._target);
  57609. };
  57610. /**
  57611. * Serializes the actions and its related information.
  57612. * @param parent defines the object to serialize in
  57613. * @returns the serialized object
  57614. */
  57615. StopAnimationAction.prototype.serialize = function (parent) {
  57616. return _super.prototype._serialize.call(this, {
  57617. name: "StopAnimationAction",
  57618. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  57619. }, parent);
  57620. };
  57621. return StopAnimationAction;
  57622. }(BABYLON.Action));
  57623. BABYLON.StopAnimationAction = StopAnimationAction;
  57624. /**
  57625. * This defines an action responsible that does nothing once triggered.
  57626. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57627. */
  57628. var DoNothingAction = /** @class */ (function (_super) {
  57629. __extends(DoNothingAction, _super);
  57630. /**
  57631. * Instantiate the action
  57632. * @param triggerOptions defines the trigger options
  57633. * @param condition defines the trigger related conditions
  57634. */
  57635. function DoNothingAction(triggerOptions, condition) {
  57636. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  57637. return _super.call(this, triggerOptions, condition) || this;
  57638. }
  57639. /**
  57640. * Execute the action and do nothing.
  57641. */
  57642. DoNothingAction.prototype.execute = function () {
  57643. };
  57644. /**
  57645. * Serializes the actions and its related information.
  57646. * @param parent defines the object to serialize in
  57647. * @returns the serialized object
  57648. */
  57649. DoNothingAction.prototype.serialize = function (parent) {
  57650. return _super.prototype._serialize.call(this, {
  57651. name: "DoNothingAction",
  57652. properties: []
  57653. }, parent);
  57654. };
  57655. return DoNothingAction;
  57656. }(BABYLON.Action));
  57657. BABYLON.DoNothingAction = DoNothingAction;
  57658. /**
  57659. * This defines an action responsible to trigger several actions once triggered.
  57660. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57661. */
  57662. var CombineAction = /** @class */ (function (_super) {
  57663. __extends(CombineAction, _super);
  57664. /**
  57665. * Instantiate the action
  57666. * @param triggerOptions defines the trigger options
  57667. * @param children defines the list of aggregated animations to run
  57668. * @param condition defines the trigger related conditions
  57669. */
  57670. function CombineAction(triggerOptions, children, condition) {
  57671. var _this = _super.call(this, triggerOptions, condition) || this;
  57672. _this.children = children;
  57673. return _this;
  57674. }
  57675. /** @hidden */
  57676. CombineAction.prototype._prepare = function () {
  57677. for (var index = 0; index < this.children.length; index++) {
  57678. this.children[index]._actionManager = this._actionManager;
  57679. this.children[index]._prepare();
  57680. }
  57681. };
  57682. /**
  57683. * Execute the action and executes all the aggregated actions.
  57684. */
  57685. CombineAction.prototype.execute = function (evt) {
  57686. for (var index = 0; index < this.children.length; index++) {
  57687. this.children[index].execute(evt);
  57688. }
  57689. };
  57690. /**
  57691. * Serializes the actions and its related information.
  57692. * @param parent defines the object to serialize in
  57693. * @returns the serialized object
  57694. */
  57695. CombineAction.prototype.serialize = function (parent) {
  57696. var serializationObject = _super.prototype._serialize.call(this, {
  57697. name: "CombineAction",
  57698. properties: [],
  57699. combine: []
  57700. }, parent);
  57701. for (var i = 0; i < this.children.length; i++) {
  57702. serializationObject.combine.push(this.children[i].serialize(null));
  57703. }
  57704. return serializationObject;
  57705. };
  57706. return CombineAction;
  57707. }(BABYLON.Action));
  57708. BABYLON.CombineAction = CombineAction;
  57709. /**
  57710. * This defines an action responsible to run code (external event) once triggered.
  57711. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57712. */
  57713. var ExecuteCodeAction = /** @class */ (function (_super) {
  57714. __extends(ExecuteCodeAction, _super);
  57715. /**
  57716. * Instantiate the action
  57717. * @param triggerOptions defines the trigger options
  57718. * @param func defines the callback function to run
  57719. * @param condition defines the trigger related conditions
  57720. */
  57721. function ExecuteCodeAction(triggerOptions, func, condition) {
  57722. var _this = _super.call(this, triggerOptions, condition) || this;
  57723. _this.func = func;
  57724. return _this;
  57725. }
  57726. /**
  57727. * Execute the action and run the attached code.
  57728. */
  57729. ExecuteCodeAction.prototype.execute = function (evt) {
  57730. this.func(evt);
  57731. };
  57732. return ExecuteCodeAction;
  57733. }(BABYLON.Action));
  57734. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  57735. /**
  57736. * This defines an action responsible to set the parent property of the target once triggered.
  57737. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  57738. */
  57739. var SetParentAction = /** @class */ (function (_super) {
  57740. __extends(SetParentAction, _super);
  57741. /**
  57742. * Instantiate the action
  57743. * @param triggerOptions defines the trigger options
  57744. * @param target defines the target containing the parent property
  57745. * @param parent defines from where the animation should start (animation frame)
  57746. * @param condition defines the trigger related conditions
  57747. */
  57748. function SetParentAction(triggerOptions, target, parent, condition) {
  57749. var _this = _super.call(this, triggerOptions, condition) || this;
  57750. _this._target = target;
  57751. _this._parent = parent;
  57752. return _this;
  57753. }
  57754. /** @hidden */
  57755. SetParentAction.prototype._prepare = function () {
  57756. };
  57757. /**
  57758. * Execute the action and set the parent property.
  57759. */
  57760. SetParentAction.prototype.execute = function () {
  57761. if (this._target.parent === this._parent) {
  57762. return;
  57763. }
  57764. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  57765. invertParentWorldMatrix.invert();
  57766. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  57767. this._target.parent = this._parent;
  57768. };
  57769. /**
  57770. * Serializes the actions and its related information.
  57771. * @param parent defines the object to serialize in
  57772. * @returns the serialized object
  57773. */
  57774. SetParentAction.prototype.serialize = function (parent) {
  57775. return _super.prototype._serialize.call(this, {
  57776. name: "SetParentAction",
  57777. properties: [
  57778. BABYLON.Action._GetTargetProperty(this._target),
  57779. BABYLON.Action._GetTargetProperty(this._parent),
  57780. ]
  57781. }, parent);
  57782. };
  57783. return SetParentAction;
  57784. }(BABYLON.Action));
  57785. BABYLON.SetParentAction = SetParentAction;
  57786. })(BABYLON || (BABYLON = {}));
  57787. //# sourceMappingURL=directActions.js.map
  57788. var BABYLON;
  57789. (function (BABYLON) {
  57790. /**
  57791. * Class used to manage multiple sprites on the same spritesheet
  57792. * @see http://doc.babylonjs.com/babylon101/sprites
  57793. */
  57794. var SpriteManager = /** @class */ (function () {
  57795. /**
  57796. * Creates a new sprite manager
  57797. * @param name defines the manager's name
  57798. * @param imgUrl defines the sprite sheet url
  57799. * @param capacity defines the maximum allowed number of sprites
  57800. * @param cellSize defines the size of a sprite cell
  57801. * @param scene defines the hosting scene
  57802. * @param epsilon defines the epsilon value to align texture (0.01 by default)
  57803. * @param samplingMode defines the smapling mode to use with spritesheet
  57804. */
  57805. function SpriteManager(
  57806. /** defines the manager's name */
  57807. name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  57808. if (epsilon === void 0) { epsilon = 0.01; }
  57809. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57810. this.name = name;
  57811. /** Gets the list of sprites */
  57812. this.sprites = new Array();
  57813. /** Gets or sets the rendering group id (0 by default) */
  57814. this.renderingGroupId = 0;
  57815. /** Gets or sets camera layer mask */
  57816. this.layerMask = 0x0FFFFFFF;
  57817. /** Gets or sets a boolean indicating if the manager must consider scene fog when rendering */
  57818. this.fogEnabled = true;
  57819. /** Gets or sets a boolean indicating if the sprites are pickable */
  57820. this.isPickable = false;
  57821. /**
  57822. * An event triggered when the manager is disposed.
  57823. */
  57824. this.onDisposeObservable = new BABYLON.Observable();
  57825. this._vertexBuffers = {};
  57826. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  57827. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  57828. }
  57829. this._capacity = capacity;
  57830. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  57831. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57832. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57833. if (cellSize.width && cellSize.height) {
  57834. this.cellWidth = cellSize.width;
  57835. this.cellHeight = cellSize.height;
  57836. }
  57837. else if (cellSize !== undefined) {
  57838. this.cellWidth = cellSize;
  57839. this.cellHeight = cellSize;
  57840. }
  57841. else {
  57842. return;
  57843. }
  57844. this._epsilon = epsilon;
  57845. this._scene = scene;
  57846. this._scene.spriteManagers.push(this);
  57847. var indices = [];
  57848. var index = 0;
  57849. for (var count = 0; count < capacity; count++) {
  57850. indices.push(index);
  57851. indices.push(index + 1);
  57852. indices.push(index + 2);
  57853. indices.push(index);
  57854. indices.push(index + 2);
  57855. indices.push(index + 3);
  57856. index += 4;
  57857. }
  57858. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  57859. // VBO
  57860. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  57861. this._vertexData = new Float32Array(capacity * 16 * 4);
  57862. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  57863. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  57864. var options = this._buffer.createVertexBuffer("options", 4, 4);
  57865. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  57866. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  57867. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  57868. this._vertexBuffers["options"] = options;
  57869. this._vertexBuffers["cellInfo"] = cellInfo;
  57870. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  57871. // Effects
  57872. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  57873. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  57874. }
  57875. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  57876. /**
  57877. * Callback called when the manager is disposed
  57878. */
  57879. set: function (callback) {
  57880. if (this._onDisposeObserver) {
  57881. this.onDisposeObservable.remove(this._onDisposeObserver);
  57882. }
  57883. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  57884. },
  57885. enumerable: true,
  57886. configurable: true
  57887. });
  57888. Object.defineProperty(SpriteManager.prototype, "texture", {
  57889. /**
  57890. * Gets or sets the spritesheet texture
  57891. */
  57892. get: function () {
  57893. return this._spriteTexture;
  57894. },
  57895. set: function (value) {
  57896. this._spriteTexture = value;
  57897. },
  57898. enumerable: true,
  57899. configurable: true
  57900. });
  57901. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  57902. var arrayOffset = index * 16;
  57903. if (offsetX === 0) {
  57904. offsetX = this._epsilon;
  57905. }
  57906. else if (offsetX === 1) {
  57907. offsetX = 1 - this._epsilon;
  57908. }
  57909. if (offsetY === 0) {
  57910. offsetY = this._epsilon;
  57911. }
  57912. else if (offsetY === 1) {
  57913. offsetY = 1 - this._epsilon;
  57914. }
  57915. this._vertexData[arrayOffset] = sprite.position.x;
  57916. this._vertexData[arrayOffset + 1] = sprite.position.y;
  57917. this._vertexData[arrayOffset + 2] = sprite.position.z;
  57918. this._vertexData[arrayOffset + 3] = sprite.angle;
  57919. this._vertexData[arrayOffset + 4] = sprite.width;
  57920. this._vertexData[arrayOffset + 5] = sprite.height;
  57921. this._vertexData[arrayOffset + 6] = offsetX;
  57922. this._vertexData[arrayOffset + 7] = offsetY;
  57923. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  57924. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  57925. var offset = (sprite.cellIndex / rowSize) >> 0;
  57926. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  57927. this._vertexData[arrayOffset + 11] = offset;
  57928. // Color
  57929. this._vertexData[arrayOffset + 12] = sprite.color.r;
  57930. this._vertexData[arrayOffset + 13] = sprite.color.g;
  57931. this._vertexData[arrayOffset + 14] = sprite.color.b;
  57932. this._vertexData[arrayOffset + 15] = sprite.color.a;
  57933. };
  57934. /**
  57935. * Intersects the sprites with a ray
  57936. * @param ray defines the ray to intersect with
  57937. * @param camera defines the current active camera
  57938. * @param predicate defines a predicate used to select candidate sprites
  57939. * @param fastCheck defines if a fast check only must be done (the first potential sprite is will be used and not the closer)
  57940. * @returns null if no hit or a PickingInfo
  57941. */
  57942. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  57943. var count = Math.min(this._capacity, this.sprites.length);
  57944. var min = BABYLON.Vector3.Zero();
  57945. var max = BABYLON.Vector3.Zero();
  57946. var distance = Number.MAX_VALUE;
  57947. var currentSprite = null;
  57948. var cameraSpacePosition = BABYLON.Vector3.Zero();
  57949. var cameraView = camera.getViewMatrix();
  57950. for (var index = 0; index < count; index++) {
  57951. var sprite = this.sprites[index];
  57952. if (!sprite) {
  57953. continue;
  57954. }
  57955. if (predicate) {
  57956. if (!predicate(sprite)) {
  57957. continue;
  57958. }
  57959. }
  57960. else if (!sprite.isPickable) {
  57961. continue;
  57962. }
  57963. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  57964. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  57965. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  57966. if (ray.intersectsBoxMinMax(min, max)) {
  57967. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  57968. if (distance > currentDistance) {
  57969. distance = currentDistance;
  57970. currentSprite = sprite;
  57971. if (fastCheck) {
  57972. break;
  57973. }
  57974. }
  57975. }
  57976. }
  57977. if (currentSprite) {
  57978. var result = new BABYLON.PickingInfo();
  57979. result.hit = true;
  57980. result.pickedSprite = currentSprite;
  57981. result.distance = distance;
  57982. return result;
  57983. }
  57984. return null;
  57985. };
  57986. /**
  57987. * Render all child sprites
  57988. */
  57989. SpriteManager.prototype.render = function () {
  57990. // Check
  57991. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady()) {
  57992. return;
  57993. }
  57994. var engine = this._scene.getEngine();
  57995. var baseSize = this._spriteTexture.getBaseSize();
  57996. // Sprites
  57997. var deltaTime = engine.getDeltaTime();
  57998. var max = Math.min(this._capacity, this.sprites.length);
  57999. var rowSize = baseSize.width / this.cellWidth;
  58000. var offset = 0;
  58001. for (var index = 0; index < max; index++) {
  58002. var sprite = this.sprites[index];
  58003. if (!sprite || !sprite.isVisible) {
  58004. continue;
  58005. }
  58006. sprite._animate(deltaTime);
  58007. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  58008. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  58009. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  58010. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  58011. }
  58012. this._buffer.update(this._vertexData);
  58013. // Render
  58014. var effect = this._effectBase;
  58015. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  58016. effect = this._effectFog;
  58017. }
  58018. engine.enableEffect(effect);
  58019. var viewMatrix = this._scene.getViewMatrix();
  58020. effect.setTexture("diffuseSampler", this._spriteTexture);
  58021. effect.setMatrix("view", viewMatrix);
  58022. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  58023. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  58024. // Fog
  58025. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  58026. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  58027. effect.setColor3("vFogColor", this._scene.fogColor);
  58028. }
  58029. // VBOs
  58030. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  58031. // Draw order
  58032. engine.setDepthFunctionToLessOrEqual();
  58033. effect.setBool("alphaTest", true);
  58034. engine.setColorWrite(false);
  58035. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  58036. engine.setColorWrite(true);
  58037. effect.setBool("alphaTest", false);
  58038. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58039. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  58040. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58041. };
  58042. /**
  58043. * Release associated resources
  58044. */
  58045. SpriteManager.prototype.dispose = function () {
  58046. if (this._buffer) {
  58047. this._buffer.dispose();
  58048. this._buffer = null;
  58049. }
  58050. if (this._indexBuffer) {
  58051. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  58052. this._indexBuffer = null;
  58053. }
  58054. if (this._spriteTexture) {
  58055. this._spriteTexture.dispose();
  58056. this._spriteTexture = null;
  58057. }
  58058. // Remove from scene
  58059. var index = this._scene.spriteManagers.indexOf(this);
  58060. this._scene.spriteManagers.splice(index, 1);
  58061. // Callback
  58062. this.onDisposeObservable.notifyObservers(this);
  58063. this.onDisposeObservable.clear();
  58064. };
  58065. return SpriteManager;
  58066. }());
  58067. BABYLON.SpriteManager = SpriteManager;
  58068. })(BABYLON || (BABYLON = {}));
  58069. //# sourceMappingURL=spriteManager.js.map
  58070. var BABYLON;
  58071. (function (BABYLON) {
  58072. /**
  58073. * Class used to represent a sprite
  58074. * @see http://doc.babylonjs.com/babylon101/sprites
  58075. */
  58076. var Sprite = /** @class */ (function () {
  58077. /**
  58078. * Creates a new Sprite
  58079. * @param name defines the name
  58080. * @param manager defines the manager
  58081. */
  58082. function Sprite(
  58083. /** defines the name */
  58084. name, manager) {
  58085. this.name = name;
  58086. /** Gets or sets the main color */
  58087. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58088. /** Gets or sets the width */
  58089. this.width = 1.0;
  58090. /** Gets or sets the height */
  58091. this.height = 1.0;
  58092. /** Gets or sets rotation angle */
  58093. this.angle = 0;
  58094. /** Gets or sets the cell index in the sprite sheet */
  58095. this.cellIndex = 0;
  58096. /** Gets or sets a boolean indicating if UV coordinates should be inverted in U axis */
  58097. this.invertU = 0;
  58098. /** Gets or sets a boolean indicating if UV coordinates should be inverted in B axis */
  58099. this.invertV = 0;
  58100. /** Gets the list of attached animations */
  58101. this.animations = new Array();
  58102. /** Gets or sets a boolean indicating if the sprite can be picked */
  58103. this.isPickable = false;
  58104. this._animationStarted = false;
  58105. this._loopAnimation = false;
  58106. this._fromIndex = 0;
  58107. this._toIndex = 0;
  58108. this._delay = 0;
  58109. this._direction = 1;
  58110. this._time = 0;
  58111. /**
  58112. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  58113. */
  58114. this.isVisible = true;
  58115. this._manager = manager;
  58116. this._manager.sprites.push(this);
  58117. this.position = BABYLON.Vector3.Zero();
  58118. }
  58119. Object.defineProperty(Sprite.prototype, "size", {
  58120. /**
  58121. * Gets or sets the sprite size
  58122. */
  58123. get: function () {
  58124. return this.width;
  58125. },
  58126. set: function (value) {
  58127. this.width = value;
  58128. this.height = value;
  58129. },
  58130. enumerable: true,
  58131. configurable: true
  58132. });
  58133. /**
  58134. * Starts an animation
  58135. * @param from defines the initial key
  58136. * @param to defines the end key
  58137. * @param loop defines if the animation must loop
  58138. * @param delay defines the start delay (in ms)
  58139. * @param onAnimationEnd defines a callback to call when animation ends
  58140. */
  58141. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  58142. this._fromIndex = from;
  58143. this._toIndex = to;
  58144. this._loopAnimation = loop;
  58145. this._delay = delay;
  58146. this._animationStarted = true;
  58147. this._direction = from < to ? 1 : -1;
  58148. this.cellIndex = from;
  58149. this._time = 0;
  58150. this._onAnimationEnd = onAnimationEnd;
  58151. };
  58152. /** Stops current animation (if any) */
  58153. Sprite.prototype.stopAnimation = function () {
  58154. this._animationStarted = false;
  58155. };
  58156. /** @hidden */
  58157. Sprite.prototype._animate = function (deltaTime) {
  58158. if (!this._animationStarted) {
  58159. return;
  58160. }
  58161. this._time += deltaTime;
  58162. if (this._time > this._delay) {
  58163. this._time = this._time % this._delay;
  58164. this.cellIndex += this._direction;
  58165. if (this.cellIndex > this._toIndex) {
  58166. if (this._loopAnimation) {
  58167. this.cellIndex = this._fromIndex;
  58168. }
  58169. else {
  58170. this.cellIndex = this._toIndex;
  58171. this._animationStarted = false;
  58172. if (this._onAnimationEnd) {
  58173. this._onAnimationEnd();
  58174. }
  58175. if (this.disposeWhenFinishedAnimating) {
  58176. this.dispose();
  58177. }
  58178. }
  58179. }
  58180. }
  58181. };
  58182. /** Release associated resources */
  58183. Sprite.prototype.dispose = function () {
  58184. for (var i = 0; i < this._manager.sprites.length; i++) {
  58185. if (this._manager.sprites[i] == this) {
  58186. this._manager.sprites.splice(i, 1);
  58187. }
  58188. }
  58189. };
  58190. return Sprite;
  58191. }());
  58192. BABYLON.Sprite = Sprite;
  58193. })(BABYLON || (BABYLON = {}));
  58194. //# sourceMappingURL=sprite.js.map
  58195. var BABYLON;
  58196. (function (BABYLON) {
  58197. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  58198. if (!BABYLON.PickingInfo) {
  58199. return null;
  58200. }
  58201. var pickingInfo = null;
  58202. if (!camera) {
  58203. if (!this.activeCamera) {
  58204. return null;
  58205. }
  58206. camera = this.activeCamera;
  58207. }
  58208. if (this.spriteManagers.length > 0) {
  58209. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  58210. var spriteManager = this.spriteManagers[spriteIndex];
  58211. if (!spriteManager.isPickable) {
  58212. continue;
  58213. }
  58214. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  58215. if (!result || !result.hit) {
  58216. continue;
  58217. }
  58218. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
  58219. continue;
  58220. }
  58221. pickingInfo = result;
  58222. if (fastCheck) {
  58223. break;
  58224. }
  58225. }
  58226. }
  58227. return pickingInfo || new BABYLON.PickingInfo();
  58228. };
  58229. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  58230. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  58231. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  58232. };
  58233. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  58234. if (!this._tempSpritePickingRay) {
  58235. return null;
  58236. }
  58237. if (!camera) {
  58238. if (!this.activeCamera) {
  58239. return null;
  58240. }
  58241. camera = this.activeCamera;
  58242. }
  58243. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  58244. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  58245. };
  58246. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  58247. if (this._pointerOverSprite === sprite) {
  58248. return;
  58249. }
  58250. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  58251. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  58252. }
  58253. this._pointerOverSprite = sprite;
  58254. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  58255. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  58256. }
  58257. };
  58258. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  58259. return this._pointerOverSprite;
  58260. };
  58261. /**
  58262. * Defines the sprite scene component responsible to manage sprites
  58263. * in a given scene.
  58264. */
  58265. var SpriteSceneComponent = /** @class */ (function () {
  58266. /**
  58267. * Creates a new instance of the component for the given scene
  58268. * @param scene Defines the scene to register the component in
  58269. */
  58270. function SpriteSceneComponent(scene) {
  58271. /**
  58272. * The component name helpfull to identify the component in the list of scene components.
  58273. */
  58274. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  58275. this.scene = scene;
  58276. this.scene.spriteManagers = new Array();
  58277. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  58278. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  58279. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  58280. this._spritePredicate = function (sprite) {
  58281. if (!sprite.actionManager) {
  58282. return false;
  58283. }
  58284. return sprite.isPickable && sprite.actionManager.hasPointerTriggers;
  58285. };
  58286. }
  58287. /**
  58288. * Registers the component in a given scene
  58289. */
  58290. SpriteSceneComponent.prototype.register = function () {
  58291. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  58292. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  58293. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  58294. };
  58295. /**
  58296. * Rebuilds the elements related to this component in case of
  58297. * context lost for instance.
  58298. */
  58299. SpriteSceneComponent.prototype.rebuild = function () {
  58300. /** Nothing to do for sprites */
  58301. };
  58302. /**
  58303. * Disposes the component and the associated ressources.
  58304. */
  58305. SpriteSceneComponent.prototype.dispose = function () {
  58306. this.scene.onBeforeSpritesRenderingObservable.clear();
  58307. this.scene.onAfterSpritesRenderingObservable.clear();
  58308. var spriteManagers = this.scene.spriteManagers;
  58309. while (spriteManagers.length) {
  58310. spriteManagers[0].dispose();
  58311. }
  58312. };
  58313. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  58314. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  58315. if (result) {
  58316. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  58317. }
  58318. return result;
  58319. };
  58320. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  58321. var scene = this.scene;
  58322. if (isMeshPicked) {
  58323. scene.setPointerOverSprite(null);
  58324. }
  58325. else {
  58326. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  58327. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  58328. scene.setPointerOverSprite(pickResult.pickedSprite);
  58329. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  58330. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  58331. }
  58332. else {
  58333. canvas.style.cursor = scene.hoverCursor;
  58334. }
  58335. }
  58336. else {
  58337. scene.setPointerOverSprite(null);
  58338. }
  58339. }
  58340. return pickResult;
  58341. };
  58342. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  58343. var scene = this.scene;
  58344. scene._pickedDownSprite = null;
  58345. if (scene.spriteManagers.length > 0) {
  58346. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  58347. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  58348. if (pickResult.pickedSprite.actionManager) {
  58349. scene._pickedDownSprite = pickResult.pickedSprite;
  58350. switch (evt.button) {
  58351. case 0:
  58352. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  58353. break;
  58354. case 1:
  58355. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  58356. break;
  58357. case 2:
  58358. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  58359. break;
  58360. }
  58361. if (pickResult.pickedSprite.actionManager) {
  58362. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  58363. }
  58364. }
  58365. }
  58366. }
  58367. return pickResult;
  58368. };
  58369. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  58370. var scene = this.scene;
  58371. if (scene.spriteManagers.length > 0) {
  58372. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  58373. if (spritePickResult) {
  58374. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  58375. if (spritePickResult.pickedSprite.actionManager) {
  58376. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  58377. if (spritePickResult.pickedSprite.actionManager) {
  58378. if (!this.scene._isPointerSwiping()) {
  58379. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  58380. }
  58381. }
  58382. }
  58383. }
  58384. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  58385. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  58386. }
  58387. }
  58388. }
  58389. return pickResult;
  58390. };
  58391. return SpriteSceneComponent;
  58392. }());
  58393. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  58394. })(BABYLON || (BABYLON = {}));
  58395. //# sourceMappingURL=spriteSceneComponent.js.map
  58396. var BABYLON;
  58397. (function (BABYLON) {
  58398. /**
  58399. * @hidden
  58400. */
  58401. var IntersectionInfo = /** @class */ (function () {
  58402. function IntersectionInfo(bu, bv, distance) {
  58403. this.bu = bu;
  58404. this.bv = bv;
  58405. this.distance = distance;
  58406. this.faceId = 0;
  58407. this.subMeshId = 0;
  58408. }
  58409. return IntersectionInfo;
  58410. }());
  58411. BABYLON.IntersectionInfo = IntersectionInfo;
  58412. /**
  58413. * Information about the result of picking within a scene
  58414. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  58415. */
  58416. var PickingInfo = /** @class */ (function () {
  58417. function PickingInfo() {
  58418. /**
  58419. * If the pick collided with an object
  58420. */
  58421. this.hit = false;
  58422. /**
  58423. * Distance away where the pick collided
  58424. */
  58425. this.distance = 0;
  58426. /**
  58427. * The location of pick collision
  58428. */
  58429. this.pickedPoint = null;
  58430. /**
  58431. * The mesh corresponding the the pick collision
  58432. */
  58433. this.pickedMesh = null;
  58434. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  58435. this.bu = 0;
  58436. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  58437. this.bv = 0;
  58438. /** The id of the face on the mesh that was picked */
  58439. this.faceId = -1;
  58440. /** Id of the the submesh that was picked */
  58441. this.subMeshId = 0;
  58442. /** If a sprite was picked, this will be the sprite the pick collided with */
  58443. this.pickedSprite = null;
  58444. /**
  58445. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  58446. */
  58447. this.originMesh = null;
  58448. /**
  58449. * The ray that was used to perform the picking.
  58450. */
  58451. this.ray = null;
  58452. }
  58453. /**
  58454. * Gets the normal correspodning to the face the pick collided with
  58455. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  58456. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  58457. * @returns The normal correspodning to the face the pick collided with
  58458. */
  58459. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  58460. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  58461. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  58462. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  58463. return null;
  58464. }
  58465. var indices = this.pickedMesh.getIndices();
  58466. if (!indices) {
  58467. return null;
  58468. }
  58469. var result;
  58470. if (useVerticesNormals) {
  58471. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58472. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  58473. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  58474. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  58475. normal0 = normal0.scale(this.bu);
  58476. normal1 = normal1.scale(this.bv);
  58477. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  58478. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  58479. }
  58480. else {
  58481. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58482. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  58483. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  58484. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  58485. var p1p2 = vertex1.subtract(vertex2);
  58486. var p3p2 = vertex3.subtract(vertex2);
  58487. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  58488. }
  58489. if (useWorldCoordinates) {
  58490. var wm = this.pickedMesh.getWorldMatrix();
  58491. if (this.pickedMesh.nonUniformScaling) {
  58492. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  58493. wm = BABYLON.Tmp.Matrix[0];
  58494. wm.setTranslationFromFloats(0, 0, 0);
  58495. wm.invert();
  58496. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  58497. wm = BABYLON.Tmp.Matrix[1];
  58498. }
  58499. result = BABYLON.Vector3.TransformNormal(result, wm);
  58500. }
  58501. result.normalize();
  58502. return result;
  58503. };
  58504. /**
  58505. * Gets the texture coordinates of where the pick occured
  58506. * @returns the vector containing the coordnates of the texture
  58507. */
  58508. PickingInfo.prototype.getTextureCoordinates = function () {
  58509. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58510. return null;
  58511. }
  58512. var indices = this.pickedMesh.getIndices();
  58513. if (!indices) {
  58514. return null;
  58515. }
  58516. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58517. if (!uvs) {
  58518. return null;
  58519. }
  58520. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  58521. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  58522. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  58523. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  58524. uv1 = uv1.scale(this.bu);
  58525. uv2 = uv2.scale(this.bv);
  58526. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  58527. };
  58528. return PickingInfo;
  58529. }());
  58530. BABYLON.PickingInfo = PickingInfo;
  58531. })(BABYLON || (BABYLON = {}));
  58532. //# sourceMappingURL=pickingInfo.js.map
  58533. var BABYLON;
  58534. (function (BABYLON) {
  58535. /**
  58536. * Class representing a ray with position and direction
  58537. */
  58538. var Ray = /** @class */ (function () {
  58539. /**
  58540. * Creates a new ray
  58541. * @param origin origin point
  58542. * @param direction direction
  58543. * @param length length of the ray
  58544. */
  58545. function Ray(
  58546. /** origin point */
  58547. origin,
  58548. /** direction */
  58549. direction,
  58550. /** length of the ray */
  58551. length) {
  58552. if (length === void 0) { length = Number.MAX_VALUE; }
  58553. this.origin = origin;
  58554. this.direction = direction;
  58555. this.length = length;
  58556. }
  58557. // Methods
  58558. /**
  58559. * Checks if the ray intersects a box
  58560. * @param minimum bound of the box
  58561. * @param maximum bound of the box
  58562. * @param intersectionTreshold extra extend to be added to the box in all direction
  58563. * @returns if the box was hit
  58564. */
  58565. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum, intersectionTreshold) {
  58566. if (intersectionTreshold === void 0) { intersectionTreshold = 0; }
  58567. var newMinimum = Ray.TmpVector3[0].copyFromFloats(minimum.x - intersectionTreshold, minimum.y - intersectionTreshold, minimum.z - intersectionTreshold);
  58568. var newMaximum = Ray.TmpVector3[1].copyFromFloats(maximum.x + intersectionTreshold, maximum.y + intersectionTreshold, maximum.z + intersectionTreshold);
  58569. var d = 0.0;
  58570. var maxValue = Number.MAX_VALUE;
  58571. var inv;
  58572. var min;
  58573. var max;
  58574. var temp;
  58575. if (Math.abs(this.direction.x) < 0.0000001) {
  58576. if (this.origin.x < newMinimum.x || this.origin.x > newMaximum.x) {
  58577. return false;
  58578. }
  58579. }
  58580. else {
  58581. inv = 1.0 / this.direction.x;
  58582. min = (newMinimum.x - this.origin.x) * inv;
  58583. max = (newMaximum.x - this.origin.x) * inv;
  58584. if (max === -Infinity) {
  58585. max = Infinity;
  58586. }
  58587. if (min > max) {
  58588. temp = min;
  58589. min = max;
  58590. max = temp;
  58591. }
  58592. d = Math.max(min, d);
  58593. maxValue = Math.min(max, maxValue);
  58594. if (d > maxValue) {
  58595. return false;
  58596. }
  58597. }
  58598. if (Math.abs(this.direction.y) < 0.0000001) {
  58599. if (this.origin.y < newMinimum.y || this.origin.y > newMaximum.y) {
  58600. return false;
  58601. }
  58602. }
  58603. else {
  58604. inv = 1.0 / this.direction.y;
  58605. min = (newMinimum.y - this.origin.y) * inv;
  58606. max = (newMaximum.y - this.origin.y) * inv;
  58607. if (max === -Infinity) {
  58608. max = Infinity;
  58609. }
  58610. if (min > max) {
  58611. temp = min;
  58612. min = max;
  58613. max = temp;
  58614. }
  58615. d = Math.max(min, d);
  58616. maxValue = Math.min(max, maxValue);
  58617. if (d > maxValue) {
  58618. return false;
  58619. }
  58620. }
  58621. if (Math.abs(this.direction.z) < 0.0000001) {
  58622. if (this.origin.z < newMinimum.z || this.origin.z > newMaximum.z) {
  58623. return false;
  58624. }
  58625. }
  58626. else {
  58627. inv = 1.0 / this.direction.z;
  58628. min = (newMinimum.z - this.origin.z) * inv;
  58629. max = (newMaximum.z - this.origin.z) * inv;
  58630. if (max === -Infinity) {
  58631. max = Infinity;
  58632. }
  58633. if (min > max) {
  58634. temp = min;
  58635. min = max;
  58636. max = temp;
  58637. }
  58638. d = Math.max(min, d);
  58639. maxValue = Math.min(max, maxValue);
  58640. if (d > maxValue) {
  58641. return false;
  58642. }
  58643. }
  58644. return true;
  58645. };
  58646. /**
  58647. * Checks if the ray intersects a box
  58648. * @param box the bounding box to check
  58649. * @param intersectionTreshold extra extend to be added to the BoundingBox in all direction
  58650. * @returns if the box was hit
  58651. */
  58652. Ray.prototype.intersectsBox = function (box, intersectionTreshold) {
  58653. if (intersectionTreshold === void 0) { intersectionTreshold = 0; }
  58654. return this.intersectsBoxMinMax(box.minimum, box.maximum, intersectionTreshold);
  58655. };
  58656. /**
  58657. * If the ray hits a sphere
  58658. * @param sphere the bounding sphere to check
  58659. * @param intersectionTreshold extra extend to be added to the BoundingSphere in all direction
  58660. * @returns true if it hits the sphere
  58661. */
  58662. Ray.prototype.intersectsSphere = function (sphere, intersectionTreshold) {
  58663. if (intersectionTreshold === void 0) { intersectionTreshold = 0; }
  58664. var x = sphere.center.x - this.origin.x;
  58665. var y = sphere.center.y - this.origin.y;
  58666. var z = sphere.center.z - this.origin.z;
  58667. var pyth = (x * x) + (y * y) + (z * z);
  58668. var radius = sphere.radius + intersectionTreshold;
  58669. var rr = radius * radius;
  58670. if (pyth <= rr) {
  58671. return true;
  58672. }
  58673. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  58674. if (dot < 0.0) {
  58675. return false;
  58676. }
  58677. var temp = pyth - (dot * dot);
  58678. return temp <= rr;
  58679. };
  58680. /**
  58681. * If the ray hits a triange
  58682. * @param vertex0 triangle vertex
  58683. * @param vertex1 triangle vertex
  58684. * @param vertex2 triangle vertex
  58685. * @returns intersection information if hit
  58686. */
  58687. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  58688. var edge1 = Ray.TmpVector3[0];
  58689. var edge2 = Ray.TmpVector3[1];
  58690. var pvec = Ray.TmpVector3[2];
  58691. var tvec = Ray.TmpVector3[3];
  58692. var qvec = Ray.TmpVector3[4];
  58693. vertex1.subtractToRef(vertex0, edge1);
  58694. vertex2.subtractToRef(vertex0, edge2);
  58695. BABYLON.Vector3.CrossToRef(this.direction, edge2, pvec);
  58696. var det = BABYLON.Vector3.Dot(edge1, pvec);
  58697. if (det === 0) {
  58698. return null;
  58699. }
  58700. var invdet = 1 / det;
  58701. this.origin.subtractToRef(vertex0, tvec);
  58702. var bu = BABYLON.Vector3.Dot(tvec, pvec) * invdet;
  58703. if (bu < 0 || bu > 1.0) {
  58704. return null;
  58705. }
  58706. BABYLON.Vector3.CrossToRef(tvec, edge1, qvec);
  58707. var bv = BABYLON.Vector3.Dot(this.direction, qvec) * invdet;
  58708. if (bv < 0 || bu + bv > 1.0) {
  58709. return null;
  58710. }
  58711. //check if the distance is longer than the predefined length.
  58712. var distance = BABYLON.Vector3.Dot(edge2, qvec) * invdet;
  58713. if (distance > this.length) {
  58714. return null;
  58715. }
  58716. return new BABYLON.IntersectionInfo(bu, bv, distance);
  58717. };
  58718. /**
  58719. * Checks if ray intersects a plane
  58720. * @param plane the plane to check
  58721. * @returns the distance away it was hit
  58722. */
  58723. Ray.prototype.intersectsPlane = function (plane) {
  58724. var distance;
  58725. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  58726. if (Math.abs(result1) < 9.99999997475243E-07) {
  58727. return null;
  58728. }
  58729. else {
  58730. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  58731. distance = (-plane.d - result2) / result1;
  58732. if (distance < 0.0) {
  58733. if (distance < -9.99999997475243E-07) {
  58734. return null;
  58735. }
  58736. else {
  58737. return 0;
  58738. }
  58739. }
  58740. return distance;
  58741. }
  58742. };
  58743. /**
  58744. * Checks if ray intersects a mesh
  58745. * @param mesh the mesh to check
  58746. * @param fastCheck if only the bounding box should checked
  58747. * @returns picking info of the intersecton
  58748. */
  58749. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  58750. var tm = BABYLON.Tmp.Matrix[0];
  58751. mesh.getWorldMatrix().invertToRef(tm);
  58752. if (this._tmpRay) {
  58753. Ray.TransformToRef(this, tm, this._tmpRay);
  58754. }
  58755. else {
  58756. this._tmpRay = Ray.Transform(this, tm);
  58757. }
  58758. return mesh.intersects(this._tmpRay, fastCheck);
  58759. };
  58760. /**
  58761. * Checks if ray intersects a mesh
  58762. * @param meshes the meshes to check
  58763. * @param fastCheck if only the bounding box should checked
  58764. * @param results array to store result in
  58765. * @returns Array of picking infos
  58766. */
  58767. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  58768. if (results) {
  58769. results.length = 0;
  58770. }
  58771. else {
  58772. results = [];
  58773. }
  58774. for (var i = 0; i < meshes.length; i++) {
  58775. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  58776. if (pickInfo.hit) {
  58777. results.push(pickInfo);
  58778. }
  58779. }
  58780. results.sort(this._comparePickingInfo);
  58781. return results;
  58782. };
  58783. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  58784. if (pickingInfoA.distance < pickingInfoB.distance) {
  58785. return -1;
  58786. }
  58787. else if (pickingInfoA.distance > pickingInfoB.distance) {
  58788. return 1;
  58789. }
  58790. else {
  58791. return 0;
  58792. }
  58793. };
  58794. /**
  58795. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  58796. * @param sega the first point of the segment to test the intersection against
  58797. * @param segb the second point of the segment to test the intersection against
  58798. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  58799. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  58800. */
  58801. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  58802. var o = this.origin;
  58803. var u = BABYLON.Tmp.Vector3[0];
  58804. var rsegb = BABYLON.Tmp.Vector3[1];
  58805. var v = BABYLON.Tmp.Vector3[2];
  58806. var w = BABYLON.Tmp.Vector3[3];
  58807. segb.subtractToRef(sega, u);
  58808. this.direction.scaleToRef(Ray.rayl, v);
  58809. o.addToRef(v, rsegb);
  58810. sega.subtractToRef(o, w);
  58811. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  58812. var b = BABYLON.Vector3.Dot(u, v);
  58813. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  58814. var d = BABYLON.Vector3.Dot(u, w);
  58815. var e = BABYLON.Vector3.Dot(v, w);
  58816. var D = a * c - b * b; // always >= 0
  58817. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  58818. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  58819. // compute the line parameters of the two closest points
  58820. if (D < Ray.smallnum) { // the lines are almost parallel
  58821. sN = 0.0; // force using point P0 on segment S1
  58822. sD = 1.0; // to prevent possible division by 0.0 later
  58823. tN = e;
  58824. tD = c;
  58825. }
  58826. else { // get the closest points on the infinite lines
  58827. sN = (b * e - c * d);
  58828. tN = (a * e - b * d);
  58829. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  58830. sN = 0.0;
  58831. tN = e;
  58832. tD = c;
  58833. }
  58834. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  58835. sN = sD;
  58836. tN = e + b;
  58837. tD = c;
  58838. }
  58839. }
  58840. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  58841. tN = 0.0;
  58842. // recompute sc for this edge
  58843. if (-d < 0.0) {
  58844. sN = 0.0;
  58845. }
  58846. else if (-d > a) {
  58847. sN = sD;
  58848. }
  58849. else {
  58850. sN = -d;
  58851. sD = a;
  58852. }
  58853. }
  58854. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  58855. tN = tD;
  58856. // recompute sc for this edge
  58857. if ((-d + b) < 0.0) {
  58858. sN = 0;
  58859. }
  58860. else if ((-d + b) > a) {
  58861. sN = sD;
  58862. }
  58863. else {
  58864. sN = (-d + b);
  58865. sD = a;
  58866. }
  58867. }
  58868. // finally do the division to get sc and tc
  58869. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  58870. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  58871. // get the difference of the two closest points
  58872. var qtc = BABYLON.Tmp.Vector3[4];
  58873. v.scaleToRef(tc, qtc);
  58874. var dP = BABYLON.Tmp.Vector3[5];
  58875. u.scaleToRef(sc, dP);
  58876. dP.addInPlace(w).subtractInPlace(qtc); // = S1(sc) - S2(tc)
  58877. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  58878. if (isIntersected) {
  58879. return qtc.length();
  58880. }
  58881. return -1;
  58882. };
  58883. /**
  58884. * Update the ray from viewport position
  58885. * @param x position
  58886. * @param y y position
  58887. * @param viewportWidth viewport width
  58888. * @param viewportHeight viewport height
  58889. * @param world world matrix
  58890. * @param view view matrix
  58891. * @param projection projection matrix
  58892. * @returns this ray updated
  58893. */
  58894. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  58895. BABYLON.Vector3.UnprojectRayToRef(x, y, viewportWidth, viewportHeight, world, view, projection, this);
  58896. return this;
  58897. };
  58898. // Statics
  58899. /**
  58900. * Creates a ray with origin and direction of 0,0,0
  58901. * @returns the new ray
  58902. */
  58903. Ray.Zero = function () {
  58904. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  58905. };
  58906. /**
  58907. * Creates a new ray from screen space and viewport
  58908. * @param x position
  58909. * @param y y position
  58910. * @param viewportWidth viewport width
  58911. * @param viewportHeight viewport height
  58912. * @param world world matrix
  58913. * @param view view matrix
  58914. * @param projection projection matrix
  58915. * @returns new ray
  58916. */
  58917. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  58918. var result = Ray.Zero();
  58919. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  58920. };
  58921. /**
  58922. * 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
  58923. * transformed to the given world matrix.
  58924. * @param origin The origin point
  58925. * @param end The end point
  58926. * @param world a matrix to transform the ray to. Default is the identity matrix.
  58927. * @returns the new ray
  58928. */
  58929. Ray.CreateNewFromTo = function (origin, end, world) {
  58930. if (world === void 0) { world = BABYLON.Matrix.IdentityReadOnly; }
  58931. var direction = end.subtract(origin);
  58932. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  58933. direction.normalize();
  58934. return Ray.Transform(new Ray(origin, direction, length), world);
  58935. };
  58936. /**
  58937. * Transforms a ray by a matrix
  58938. * @param ray ray to transform
  58939. * @param matrix matrix to apply
  58940. * @returns the resulting new ray
  58941. */
  58942. Ray.Transform = function (ray, matrix) {
  58943. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  58944. Ray.TransformToRef(ray, matrix, result);
  58945. return result;
  58946. };
  58947. /**
  58948. * Transforms a ray by a matrix
  58949. * @param ray ray to transform
  58950. * @param matrix matrix to apply
  58951. * @param result ray to store result in
  58952. */
  58953. Ray.TransformToRef = function (ray, matrix, result) {
  58954. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  58955. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  58956. result.length = ray.length;
  58957. var dir = result.direction;
  58958. var len = dir.length();
  58959. if (!(len === 0 || len === 1)) {
  58960. var num = 1.0 / len;
  58961. dir.x *= num;
  58962. dir.y *= num;
  58963. dir.z *= num;
  58964. result.length *= len;
  58965. }
  58966. };
  58967. Ray.TmpVector3 = BABYLON.Tools.BuildArray(6, BABYLON.Vector3.Zero);
  58968. Ray.smallnum = 0.00000001;
  58969. Ray.rayl = 10e8;
  58970. return Ray;
  58971. }());
  58972. BABYLON.Ray = Ray;
  58973. })(BABYLON || (BABYLON = {}));
  58974. //# sourceMappingURL=ray.js.map
  58975. var BABYLON;
  58976. (function (BABYLON) {
  58977. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  58978. if (boxMin.x > sphereCenter.x + sphereRadius) {
  58979. return false;
  58980. }
  58981. if (sphereCenter.x - sphereRadius > boxMax.x) {
  58982. return false;
  58983. }
  58984. if (boxMin.y > sphereCenter.y + sphereRadius) {
  58985. return false;
  58986. }
  58987. if (sphereCenter.y - sphereRadius > boxMax.y) {
  58988. return false;
  58989. }
  58990. if (boxMin.z > sphereCenter.z + sphereRadius) {
  58991. return false;
  58992. }
  58993. if (sphereCenter.z - sphereRadius > boxMax.z) {
  58994. return false;
  58995. }
  58996. return true;
  58997. };
  58998. var getLowestRoot = (function () {
  58999. var result = { root: 0, found: false };
  59000. return function (a, b, c, maxR) {
  59001. result.root = 0;
  59002. result.found = false;
  59003. var determinant = b * b - 4.0 * a * c;
  59004. if (determinant < 0) {
  59005. return result;
  59006. }
  59007. var sqrtD = Math.sqrt(determinant);
  59008. var r1 = (-b - sqrtD) / (2.0 * a);
  59009. var r2 = (-b + sqrtD) / (2.0 * a);
  59010. if (r1 > r2) {
  59011. var temp = r2;
  59012. r2 = r1;
  59013. r1 = temp;
  59014. }
  59015. if (r1 > 0 && r1 < maxR) {
  59016. result.root = r1;
  59017. result.found = true;
  59018. return result;
  59019. }
  59020. if (r2 > 0 && r2 < maxR) {
  59021. result.root = r2;
  59022. result.found = true;
  59023. return result;
  59024. }
  59025. return result;
  59026. };
  59027. })();
  59028. /** @hidden */
  59029. var Collider = /** @class */ (function () {
  59030. function Collider() {
  59031. this._collisionPoint = BABYLON.Vector3.Zero();
  59032. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  59033. this._tempVector = BABYLON.Vector3.Zero();
  59034. this._tempVector2 = BABYLON.Vector3.Zero();
  59035. this._tempVector3 = BABYLON.Vector3.Zero();
  59036. this._tempVector4 = BABYLON.Vector3.Zero();
  59037. this._edge = BABYLON.Vector3.Zero();
  59038. this._baseToVertex = BABYLON.Vector3.Zero();
  59039. this._destinationPoint = BABYLON.Vector3.Zero();
  59040. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  59041. this._displacementVector = BABYLON.Vector3.Zero();
  59042. /** @hidden */
  59043. this._radius = BABYLON.Vector3.One();
  59044. /** @hidden */
  59045. this._retry = 0;
  59046. /** @hidden */
  59047. this._basePointWorld = BABYLON.Vector3.Zero();
  59048. this._velocityWorld = BABYLON.Vector3.Zero();
  59049. this._normalizedVelocity = BABYLON.Vector3.Zero();
  59050. this._collisionMask = -1;
  59051. }
  59052. Object.defineProperty(Collider.prototype, "collisionMask", {
  59053. get: function () {
  59054. return this._collisionMask;
  59055. },
  59056. set: function (mask) {
  59057. this._collisionMask = !isNaN(mask) ? mask : -1;
  59058. },
  59059. enumerable: true,
  59060. configurable: true
  59061. });
  59062. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  59063. /**
  59064. * Gets the plane normal used to compute the sliding response (in local space)
  59065. */
  59066. get: function () {
  59067. return this._slidePlaneNormal;
  59068. },
  59069. enumerable: true,
  59070. configurable: true
  59071. });
  59072. // Methods
  59073. /** @hidden */
  59074. Collider.prototype._initialize = function (source, dir, e) {
  59075. this._velocity = dir;
  59076. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  59077. this._basePoint = source;
  59078. source.multiplyToRef(this._radius, this._basePointWorld);
  59079. dir.multiplyToRef(this._radius, this._velocityWorld);
  59080. this._velocityWorldLength = this._velocityWorld.length();
  59081. this._epsilon = e;
  59082. this.collisionFound = false;
  59083. };
  59084. /** @hidden */
  59085. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  59086. pa.subtractToRef(point, this._tempVector);
  59087. pb.subtractToRef(point, this._tempVector2);
  59088. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  59089. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  59090. if (d < 0) {
  59091. return false;
  59092. }
  59093. pc.subtractToRef(point, this._tempVector3);
  59094. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  59095. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  59096. if (d < 0) {
  59097. return false;
  59098. }
  59099. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  59100. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  59101. return d >= 0;
  59102. };
  59103. /** @hidden */
  59104. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  59105. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  59106. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  59107. if (distance > this._velocityWorldLength + max + sphereRadius) {
  59108. return false;
  59109. }
  59110. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max)) {
  59111. return false;
  59112. }
  59113. return true;
  59114. };
  59115. /** @hidden */
  59116. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  59117. var t0;
  59118. var embeddedInPlane = false;
  59119. //defensive programming, actually not needed.
  59120. if (!trianglePlaneArray) {
  59121. trianglePlaneArray = [];
  59122. }
  59123. if (!trianglePlaneArray[faceIndex]) {
  59124. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  59125. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  59126. }
  59127. var trianglePlane = trianglePlaneArray[faceIndex];
  59128. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0)) {
  59129. return;
  59130. }
  59131. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  59132. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  59133. if (normalDotVelocity == 0) {
  59134. if (Math.abs(signedDistToTrianglePlane) >= 1.0) {
  59135. return;
  59136. }
  59137. embeddedInPlane = true;
  59138. t0 = 0;
  59139. }
  59140. else {
  59141. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  59142. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  59143. if (t0 > t1) {
  59144. var temp = t1;
  59145. t1 = t0;
  59146. t0 = temp;
  59147. }
  59148. if (t0 > 1.0 || t1 < 0.0) {
  59149. return;
  59150. }
  59151. if (t0 < 0) {
  59152. t0 = 0;
  59153. }
  59154. if (t0 > 1.0) {
  59155. t0 = 1.0;
  59156. }
  59157. }
  59158. this._collisionPoint.copyFromFloats(0, 0, 0);
  59159. var found = false;
  59160. var t = 1.0;
  59161. if (!embeddedInPlane) {
  59162. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  59163. this._velocity.scaleToRef(t0, this._tempVector);
  59164. this._planeIntersectionPoint.addInPlace(this._tempVector);
  59165. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  59166. found = true;
  59167. t = t0;
  59168. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  59169. }
  59170. }
  59171. if (!found) {
  59172. var velocitySquaredLength = this._velocity.lengthSquared();
  59173. var a = velocitySquaredLength;
  59174. this._basePoint.subtractToRef(p1, this._tempVector);
  59175. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  59176. var c = this._tempVector.lengthSquared() - 1.0;
  59177. var lowestRoot = getLowestRoot(a, b, c, t);
  59178. if (lowestRoot.found) {
  59179. t = lowestRoot.root;
  59180. found = true;
  59181. this._collisionPoint.copyFrom(p1);
  59182. }
  59183. this._basePoint.subtractToRef(p2, this._tempVector);
  59184. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  59185. c = this._tempVector.lengthSquared() - 1.0;
  59186. lowestRoot = getLowestRoot(a, b, c, t);
  59187. if (lowestRoot.found) {
  59188. t = lowestRoot.root;
  59189. found = true;
  59190. this._collisionPoint.copyFrom(p2);
  59191. }
  59192. this._basePoint.subtractToRef(p3, this._tempVector);
  59193. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  59194. c = this._tempVector.lengthSquared() - 1.0;
  59195. lowestRoot = getLowestRoot(a, b, c, t);
  59196. if (lowestRoot.found) {
  59197. t = lowestRoot.root;
  59198. found = true;
  59199. this._collisionPoint.copyFrom(p3);
  59200. }
  59201. p2.subtractToRef(p1, this._edge);
  59202. p1.subtractToRef(this._basePoint, this._baseToVertex);
  59203. var edgeSquaredLength = this._edge.lengthSquared();
  59204. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  59205. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  59206. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  59207. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  59208. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  59209. lowestRoot = getLowestRoot(a, b, c, t);
  59210. if (lowestRoot.found) {
  59211. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  59212. if (f >= 0.0 && f <= 1.0) {
  59213. t = lowestRoot.root;
  59214. found = true;
  59215. this._edge.scaleInPlace(f);
  59216. p1.addToRef(this._edge, this._collisionPoint);
  59217. }
  59218. }
  59219. p3.subtractToRef(p2, this._edge);
  59220. p2.subtractToRef(this._basePoint, this._baseToVertex);
  59221. edgeSquaredLength = this._edge.lengthSquared();
  59222. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  59223. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  59224. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  59225. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  59226. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  59227. lowestRoot = getLowestRoot(a, b, c, t);
  59228. if (lowestRoot.found) {
  59229. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  59230. if (f >= 0.0 && f <= 1.0) {
  59231. t = lowestRoot.root;
  59232. found = true;
  59233. this._edge.scaleInPlace(f);
  59234. p2.addToRef(this._edge, this._collisionPoint);
  59235. }
  59236. }
  59237. p1.subtractToRef(p3, this._edge);
  59238. p3.subtractToRef(this._basePoint, this._baseToVertex);
  59239. edgeSquaredLength = this._edge.lengthSquared();
  59240. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  59241. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  59242. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  59243. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  59244. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  59245. lowestRoot = getLowestRoot(a, b, c, t);
  59246. if (lowestRoot.found) {
  59247. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  59248. if (f >= 0.0 && f <= 1.0) {
  59249. t = lowestRoot.root;
  59250. found = true;
  59251. this._edge.scaleInPlace(f);
  59252. p3.addToRef(this._edge, this._collisionPoint);
  59253. }
  59254. }
  59255. }
  59256. if (found) {
  59257. var distToCollision = t * this._velocity.length();
  59258. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  59259. if (!this.intersectionPoint) {
  59260. this.intersectionPoint = this._collisionPoint.clone();
  59261. }
  59262. else {
  59263. this.intersectionPoint.copyFrom(this._collisionPoint);
  59264. }
  59265. this._nearestDistance = distToCollision;
  59266. this.collisionFound = true;
  59267. }
  59268. }
  59269. };
  59270. /** @hidden */
  59271. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  59272. for (var i = indexStart; i < indexEnd; i += 3) {
  59273. var p1 = pts[indices[i] - decal];
  59274. var p2 = pts[indices[i + 1] - decal];
  59275. var p3 = pts[indices[i + 2] - decal];
  59276. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  59277. }
  59278. };
  59279. /** @hidden */
  59280. Collider.prototype._getResponse = function (pos, vel) {
  59281. pos.addToRef(vel, this._destinationPoint);
  59282. vel.scaleInPlace((this._nearestDistance / vel.length()));
  59283. this._basePoint.addToRef(vel, pos);
  59284. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  59285. this._slidePlaneNormal.normalize();
  59286. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  59287. pos.addInPlace(this._displacementVector);
  59288. this.intersectionPoint.addInPlace(this._displacementVector);
  59289. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  59290. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  59291. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  59292. };
  59293. return Collider;
  59294. }());
  59295. BABYLON.Collider = Collider;
  59296. })(BABYLON || (BABYLON = {}));
  59297. //# sourceMappingURL=collider.js.map
  59298. var BABYLON;
  59299. (function (BABYLON) {
  59300. //WebWorker code will be inserted to this variable.
  59301. /** @hidden */
  59302. BABYLON.CollisionWorker = "";
  59303. /** Defines supported task for worker process */
  59304. var WorkerTaskType;
  59305. (function (WorkerTaskType) {
  59306. /** Initialization */
  59307. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  59308. /** Update of geometry */
  59309. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  59310. /** Evaluate collision */
  59311. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  59312. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  59313. /** Defines kind of replies returned by worker */
  59314. var WorkerReplyType;
  59315. (function (WorkerReplyType) {
  59316. /** Success */
  59317. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  59318. /** Unkown error */
  59319. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  59320. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  59321. /** @hidden */
  59322. var CollisionCoordinatorWorker = /** @class */ (function () {
  59323. function CollisionCoordinatorWorker() {
  59324. var _this = this;
  59325. this._scaledPosition = BABYLON.Vector3.Zero();
  59326. this._scaledVelocity = BABYLON.Vector3.Zero();
  59327. this.onMeshUpdated = function (transformNode) {
  59328. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  59329. };
  59330. this.onGeometryUpdated = function (geometry) {
  59331. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  59332. };
  59333. this._afterRender = function () {
  59334. if (!_this._init) {
  59335. return;
  59336. }
  59337. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  59338. return;
  59339. }
  59340. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  59341. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  59342. if (_this._runningUpdated > 4) {
  59343. return;
  59344. }
  59345. ++_this._runningUpdated;
  59346. var payload = {
  59347. updatedMeshes: _this._addUpdateMeshesList,
  59348. updatedGeometries: _this._addUpdateGeometriesList,
  59349. removedGeometries: _this._toRemoveGeometryArray,
  59350. removedMeshes: _this._toRemoveMeshesArray
  59351. };
  59352. var message = {
  59353. payload: payload,
  59354. taskType: WorkerTaskType.UPDATE
  59355. };
  59356. var serializable = [];
  59357. for (var id in payload.updatedGeometries) {
  59358. if (payload.updatedGeometries.hasOwnProperty(id)) {
  59359. //prepare transferables
  59360. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  59361. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  59362. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  59363. }
  59364. }
  59365. _this._worker.postMessage(message, serializable);
  59366. _this._addUpdateMeshesList = {};
  59367. _this._addUpdateGeometriesList = {};
  59368. _this._toRemoveGeometryArray = [];
  59369. _this._toRemoveMeshesArray = [];
  59370. };
  59371. this._onMessageFromWorker = function (e) {
  59372. var returnData = e.data;
  59373. if (returnData.error != WorkerReplyType.SUCCESS) {
  59374. //TODO what errors can be returned from the worker?
  59375. BABYLON.Tools.Warn("error returned from worker!");
  59376. return;
  59377. }
  59378. switch (returnData.taskType) {
  59379. case WorkerTaskType.INIT:
  59380. _this._init = true;
  59381. //Update the worked with ALL of the scene's current state
  59382. _this._scene.meshes.forEach(function (mesh) {
  59383. _this.onMeshAdded(mesh);
  59384. });
  59385. _this._scene.getGeometries().forEach(function (geometry) {
  59386. _this.onGeometryAdded(geometry);
  59387. });
  59388. break;
  59389. case WorkerTaskType.UPDATE:
  59390. _this._runningUpdated--;
  59391. break;
  59392. case WorkerTaskType.COLLIDE:
  59393. var returnPayload = returnData.payload;
  59394. if (!_this._collisionsCallbackArray[returnPayload.collisionId]) {
  59395. return;
  59396. }
  59397. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  59398. if (callback) {
  59399. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  59400. if (mesh) {
  59401. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  59402. }
  59403. }
  59404. //cleanup
  59405. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  59406. break;
  59407. }
  59408. };
  59409. this._collisionsCallbackArray = [];
  59410. this._init = false;
  59411. this._runningUpdated = 0;
  59412. this._addUpdateMeshesList = {};
  59413. this._addUpdateGeometriesList = {};
  59414. this._toRemoveGeometryArray = [];
  59415. this._toRemoveMeshesArray = [];
  59416. }
  59417. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  59418. if (!this._init) {
  59419. return;
  59420. }
  59421. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000]) {
  59422. return;
  59423. }
  59424. position.divideToRef(collider._radius, this._scaledPosition);
  59425. displacement.divideToRef(collider._radius, this._scaledVelocity);
  59426. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  59427. var payload = {
  59428. collider: {
  59429. position: this._scaledPosition.asArray(),
  59430. velocity: this._scaledVelocity.asArray(),
  59431. radius: collider._radius.asArray()
  59432. },
  59433. collisionId: collisionIndex,
  59434. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  59435. maximumRetry: maximumRetry
  59436. };
  59437. var message = {
  59438. payload: payload,
  59439. taskType: WorkerTaskType.COLLIDE
  59440. };
  59441. this._worker.postMessage(message);
  59442. };
  59443. CollisionCoordinatorWorker.prototype.init = function (scene) {
  59444. this._scene = scene;
  59445. this._scene.registerAfterRender(this._afterRender);
  59446. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  59447. this._worker = new Worker(workerUrl);
  59448. this._worker.onmessage = this._onMessageFromWorker;
  59449. var message = {
  59450. payload: {},
  59451. taskType: WorkerTaskType.INIT
  59452. };
  59453. this._worker.postMessage(message);
  59454. };
  59455. CollisionCoordinatorWorker.prototype.destroy = function () {
  59456. this._scene.unregisterAfterRender(this._afterRender);
  59457. this._worker.terminate();
  59458. };
  59459. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  59460. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  59461. this.onMeshUpdated(mesh);
  59462. };
  59463. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  59464. this._toRemoveMeshesArray.push(mesh.uniqueId);
  59465. };
  59466. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  59467. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  59468. geometry.onGeometryUpdated = this.onGeometryUpdated;
  59469. this.onGeometryUpdated(geometry);
  59470. };
  59471. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  59472. this._toRemoveGeometryArray.push(geometry.id);
  59473. };
  59474. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  59475. var submeshes = [];
  59476. if (mesh.subMeshes) {
  59477. submeshes = mesh.subMeshes.map(function (sm, idx) {
  59478. var boundingInfo = sm.getBoundingInfo();
  59479. return {
  59480. position: idx,
  59481. verticesStart: sm.verticesStart,
  59482. verticesCount: sm.verticesCount,
  59483. indexStart: sm.indexStart,
  59484. indexCount: sm.indexCount,
  59485. hasMaterial: !!sm.getMaterial(),
  59486. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  59487. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  59488. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  59489. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  59490. };
  59491. });
  59492. }
  59493. var geometryId = null;
  59494. if (mesh instanceof BABYLON.Mesh) {
  59495. var geometry = mesh.geometry;
  59496. geometryId = geometry ? geometry.id : null;
  59497. }
  59498. else if (mesh instanceof BABYLON.InstancedMesh) {
  59499. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  59500. geometryId = geometry ? geometry.id : null;
  59501. }
  59502. var boundingInfo = mesh.getBoundingInfo();
  59503. return {
  59504. uniqueId: mesh.uniqueId,
  59505. id: mesh.id,
  59506. name: mesh.name,
  59507. geometryId: geometryId,
  59508. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  59509. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  59510. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  59511. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  59512. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  59513. subMeshes: submeshes,
  59514. checkCollisions: mesh.checkCollisions
  59515. };
  59516. };
  59517. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  59518. return {
  59519. id: geometry.id,
  59520. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  59521. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  59522. indices: new Uint32Array(geometry.getIndices() || []),
  59523. };
  59524. };
  59525. return CollisionCoordinatorWorker;
  59526. }());
  59527. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  59528. /** @hidden */
  59529. var CollisionCoordinatorLegacy = /** @class */ (function () {
  59530. function CollisionCoordinatorLegacy() {
  59531. this._scaledPosition = BABYLON.Vector3.Zero();
  59532. this._scaledVelocity = BABYLON.Vector3.Zero();
  59533. this._finalPosition = BABYLON.Vector3.Zero();
  59534. }
  59535. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  59536. position.divideToRef(collider._radius, this._scaledPosition);
  59537. displacement.divideToRef(collider._radius, this._scaledVelocity);
  59538. collider.collidedMesh = null;
  59539. collider._retry = 0;
  59540. collider._initialVelocity = this._scaledVelocity;
  59541. collider._initialPosition = this._scaledPosition;
  59542. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  59543. this._finalPosition.multiplyInPlace(collider._radius);
  59544. //run the callback
  59545. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  59546. };
  59547. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  59548. this._scene = scene;
  59549. };
  59550. CollisionCoordinatorLegacy.prototype.destroy = function () {
  59551. //Legacy need no destruction method.
  59552. };
  59553. //No update in legacy mode
  59554. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  59555. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  59556. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  59557. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  59558. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  59559. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  59560. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  59561. if (excludedMesh === void 0) { excludedMesh = null; }
  59562. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  59563. if (collider._retry >= maximumRetry) {
  59564. finalPosition.copyFrom(position);
  59565. return;
  59566. }
  59567. // Check if this is a mesh else camera or -1
  59568. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  59569. collider._initialize(position, velocity, closeDistance);
  59570. // Check all meshes
  59571. for (var index = 0; index < this._scene.meshes.length; index++) {
  59572. var mesh = this._scene.meshes[index];
  59573. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  59574. mesh._checkCollision(collider);
  59575. }
  59576. }
  59577. if (!collider.collisionFound) {
  59578. position.addToRef(velocity, finalPosition);
  59579. return;
  59580. }
  59581. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  59582. collider._getResponse(position, velocity);
  59583. }
  59584. if (velocity.length() <= closeDistance) {
  59585. finalPosition.copyFrom(position);
  59586. return;
  59587. }
  59588. collider._retry++;
  59589. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  59590. };
  59591. return CollisionCoordinatorLegacy;
  59592. }());
  59593. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  59594. })(BABYLON || (BABYLON = {}));
  59595. //# sourceMappingURL=collisionCoordinator.js.map
  59596. var BABYLON;
  59597. (function (BABYLON) {
  59598. /**
  59599. * A particle represents one of the element emitted by a particle system.
  59600. * This is mainly define by its coordinates, direction, velocity and age.
  59601. */
  59602. var Particle = /** @class */ (function () {
  59603. /**
  59604. * Creates a new instance Particle
  59605. * @param particleSystem the particle system the particle belongs to
  59606. */
  59607. function Particle(
  59608. /**
  59609. * The particle system the particle belongs to.
  59610. */
  59611. particleSystem) {
  59612. this.particleSystem = particleSystem;
  59613. /**
  59614. * The world position of the particle in the scene.
  59615. */
  59616. this.position = BABYLON.Vector3.Zero();
  59617. /**
  59618. * The world direction of the particle in the scene.
  59619. */
  59620. this.direction = BABYLON.Vector3.Zero();
  59621. /**
  59622. * The color of the particle.
  59623. */
  59624. this.color = new BABYLON.Color4(0, 0, 0, 0);
  59625. /**
  59626. * The color change of the particle per step.
  59627. */
  59628. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  59629. /**
  59630. * Defines how long will the life of the particle be.
  59631. */
  59632. this.lifeTime = 1.0;
  59633. /**
  59634. * The current age of the particle.
  59635. */
  59636. this.age = 0;
  59637. /**
  59638. * The current size of the particle.
  59639. */
  59640. this.size = 0;
  59641. /**
  59642. * The current scale of the particle.
  59643. */
  59644. this.scale = new BABYLON.Vector2(1, 1);
  59645. /**
  59646. * The current angle of the particle.
  59647. */
  59648. this.angle = 0;
  59649. /**
  59650. * Defines how fast is the angle changing.
  59651. */
  59652. this.angularSpeed = 0;
  59653. /**
  59654. * Defines the cell index used by the particle to be rendered from a sprite.
  59655. */
  59656. this.cellIndex = 0;
  59657. /** @hidden */
  59658. this._attachedSubEmitters = null;
  59659. /** @hidden */
  59660. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  59661. /** @hidden */
  59662. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  59663. /** @hidden */
  59664. this._currentSize1 = 0;
  59665. /** @hidden */
  59666. this._currentSize2 = 0;
  59667. /** @hidden */
  59668. this._currentAngularSpeed1 = 0;
  59669. /** @hidden */
  59670. this._currentAngularSpeed2 = 0;
  59671. /** @hidden */
  59672. this._currentVelocity1 = 0;
  59673. /** @hidden */
  59674. this._currentVelocity2 = 0;
  59675. /** @hidden */
  59676. this._currentLimitVelocity1 = 0;
  59677. /** @hidden */
  59678. this._currentLimitVelocity2 = 0;
  59679. /** @hidden */
  59680. this._currentDrag1 = 0;
  59681. /** @hidden */
  59682. this._currentDrag2 = 0;
  59683. this.id = Particle._Count++;
  59684. if (!this.particleSystem.isAnimationSheetEnabled) {
  59685. return;
  59686. }
  59687. this.updateCellInfoFromSystem();
  59688. }
  59689. Particle.prototype.updateCellInfoFromSystem = function () {
  59690. this.cellIndex = this.particleSystem.startSpriteCellID;
  59691. };
  59692. /**
  59693. * Defines how the sprite cell index is updated for the particle
  59694. */
  59695. Particle.prototype.updateCellIndex = function () {
  59696. var offsetAge = this.age;
  59697. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  59698. if (this.particleSystem.spriteRandomStartCell) {
  59699. if (this._randomCellOffset === undefined) {
  59700. this._randomCellOffset = Math.random() * this.lifeTime;
  59701. }
  59702. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  59703. changeSpeed = 1;
  59704. offsetAge = this._randomCellOffset;
  59705. }
  59706. else {
  59707. offsetAge += this._randomCellOffset;
  59708. }
  59709. }
  59710. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  59711. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  59712. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  59713. };
  59714. /** @hidden */
  59715. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  59716. if (subEmitter.particleSystem.emitter.position) {
  59717. var emitterMesh = subEmitter.particleSystem.emitter;
  59718. emitterMesh.position.copyFrom(this.position);
  59719. if (subEmitter.inheritDirection) {
  59720. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  59721. // Look at using Y as forward
  59722. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  59723. }
  59724. }
  59725. else {
  59726. var emitterPosition = subEmitter.particleSystem.emitter;
  59727. emitterPosition.copyFrom(this.position);
  59728. }
  59729. // Set inheritedVelocityOffset to be used when new particles are created
  59730. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  59731. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  59732. };
  59733. /** @hidden */
  59734. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  59735. var _this = this;
  59736. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  59737. this._attachedSubEmitters.forEach(function (subEmitter) {
  59738. _this._inheritParticleInfoToSubEmitter(subEmitter);
  59739. });
  59740. }
  59741. };
  59742. /** @hidden */
  59743. Particle.prototype._reset = function () {
  59744. this.age = 0;
  59745. this._currentColorGradient = null;
  59746. this._currentSizeGradient = null;
  59747. this._currentAngularSpeedGradient = null;
  59748. this._currentVelocityGradient = null;
  59749. this._currentLimitVelocityGradient = null;
  59750. this._currentDragGradient = null;
  59751. this.cellIndex = this.particleSystem.startSpriteCellID;
  59752. this._randomCellOffset = undefined;
  59753. };
  59754. /**
  59755. * Copy the properties of particle to another one.
  59756. * @param other the particle to copy the information to.
  59757. */
  59758. Particle.prototype.copyTo = function (other) {
  59759. other.position.copyFrom(this.position);
  59760. if (this._initialDirection) {
  59761. if (other._initialDirection) {
  59762. other._initialDirection.copyFrom(this._initialDirection);
  59763. }
  59764. else {
  59765. other._initialDirection = this._initialDirection.clone();
  59766. }
  59767. }
  59768. else {
  59769. other._initialDirection = null;
  59770. }
  59771. other.direction.copyFrom(this.direction);
  59772. other.color.copyFrom(this.color);
  59773. other.colorStep.copyFrom(this.colorStep);
  59774. other.lifeTime = this.lifeTime;
  59775. other.age = this.age;
  59776. other._randomCellOffset = this._randomCellOffset;
  59777. other.size = this.size;
  59778. other.scale.copyFrom(this.scale);
  59779. other.angle = this.angle;
  59780. other.angularSpeed = this.angularSpeed;
  59781. other.particleSystem = this.particleSystem;
  59782. other.cellIndex = this.cellIndex;
  59783. other.id = this.id;
  59784. other._attachedSubEmitters = this._attachedSubEmitters;
  59785. if (this._currentColorGradient) {
  59786. other._currentColorGradient = this._currentColorGradient;
  59787. other._currentColor1.copyFrom(this._currentColor1);
  59788. other._currentColor2.copyFrom(this._currentColor2);
  59789. }
  59790. if (this._currentSizeGradient) {
  59791. other._currentSizeGradient = this._currentSizeGradient;
  59792. other._currentSize1 = this._currentSize1;
  59793. other._currentSize2 = this._currentSize2;
  59794. }
  59795. if (this._currentAngularSpeedGradient) {
  59796. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  59797. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  59798. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  59799. }
  59800. if (this._currentVelocityGradient) {
  59801. other._currentVelocityGradient = this._currentVelocityGradient;
  59802. other._currentVelocity1 = this._currentVelocity1;
  59803. other._currentVelocity2 = this._currentVelocity2;
  59804. }
  59805. if (this._currentLimitVelocityGradient) {
  59806. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  59807. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  59808. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  59809. }
  59810. if (this._currentDragGradient) {
  59811. other._currentDragGradient = this._currentDragGradient;
  59812. other._currentDrag1 = this._currentDrag1;
  59813. other._currentDrag2 = this._currentDrag2;
  59814. }
  59815. if (this.particleSystem.isAnimationSheetEnabled) {
  59816. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  59817. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  59818. }
  59819. if (this.particleSystem.useRampGradients) {
  59820. other.remapData.copyFrom(this.remapData);
  59821. }
  59822. if (this._randomNoiseCoordinates1) {
  59823. if (other._randomNoiseCoordinates1) {
  59824. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  59825. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  59826. }
  59827. else {
  59828. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  59829. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  59830. }
  59831. }
  59832. };
  59833. Particle._Count = 0;
  59834. return Particle;
  59835. }());
  59836. BABYLON.Particle = Particle;
  59837. })(BABYLON || (BABYLON = {}));
  59838. //# sourceMappingURL=particle.js.map
  59839. var BABYLON;
  59840. (function (BABYLON) {
  59841. /**
  59842. * This represents the base class for particle system in Babylon.
  59843. * 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.
  59844. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  59845. * @example https://doc.babylonjs.com/babylon101/particles
  59846. */
  59847. var BaseParticleSystem = /** @class */ (function () {
  59848. /**
  59849. * Instantiates a particle system.
  59850. * 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.
  59851. * @param name The name of the particle system
  59852. */
  59853. function BaseParticleSystem(name) {
  59854. /**
  59855. * List of animations used by the particle system.
  59856. */
  59857. this.animations = [];
  59858. /**
  59859. * The rendering group used by the Particle system to chose when to render.
  59860. */
  59861. this.renderingGroupId = 0;
  59862. /**
  59863. * The emitter represents the Mesh or position we are attaching the particle system to.
  59864. */
  59865. this.emitter = null;
  59866. /**
  59867. * The maximum number of particles to emit per frame
  59868. */
  59869. this.emitRate = 10;
  59870. /**
  59871. * If you want to launch only a few particles at once, that can be done, as well.
  59872. */
  59873. this.manualEmitCount = -1;
  59874. /**
  59875. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  59876. */
  59877. this.updateSpeed = 0.01;
  59878. /**
  59879. * The amount of time the particle system is running (depends of the overall update speed).
  59880. */
  59881. this.targetStopDuration = 0;
  59882. /**
  59883. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  59884. */
  59885. this.disposeOnStop = false;
  59886. /**
  59887. * Minimum power of emitting particles.
  59888. */
  59889. this.minEmitPower = 1;
  59890. /**
  59891. * Maximum power of emitting particles.
  59892. */
  59893. this.maxEmitPower = 1;
  59894. /**
  59895. * Minimum life time of emitting particles.
  59896. */
  59897. this.minLifeTime = 1;
  59898. /**
  59899. * Maximum life time of emitting particles.
  59900. */
  59901. this.maxLifeTime = 1;
  59902. /**
  59903. * Minimum Size of emitting particles.
  59904. */
  59905. this.minSize = 1;
  59906. /**
  59907. * Maximum Size of emitting particles.
  59908. */
  59909. this.maxSize = 1;
  59910. /**
  59911. * Minimum scale of emitting particles on X axis.
  59912. */
  59913. this.minScaleX = 1;
  59914. /**
  59915. * Maximum scale of emitting particles on X axis.
  59916. */
  59917. this.maxScaleX = 1;
  59918. /**
  59919. * Minimum scale of emitting particles on Y axis.
  59920. */
  59921. this.minScaleY = 1;
  59922. /**
  59923. * Maximum scale of emitting particles on Y axis.
  59924. */
  59925. this.maxScaleY = 1;
  59926. /**
  59927. * Gets or sets the minimal initial rotation in radians.
  59928. */
  59929. this.minInitialRotation = 0;
  59930. /**
  59931. * Gets or sets the maximal initial rotation in radians.
  59932. */
  59933. this.maxInitialRotation = 0;
  59934. /**
  59935. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  59936. */
  59937. this.minAngularSpeed = 0;
  59938. /**
  59939. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  59940. */
  59941. this.maxAngularSpeed = 0;
  59942. /**
  59943. * The layer mask we are rendering the particles through.
  59944. */
  59945. this.layerMask = 0x0FFFFFFF;
  59946. /**
  59947. * This can help using your own shader to render the particle system.
  59948. * The according effect will be created
  59949. */
  59950. this.customShader = null;
  59951. /**
  59952. * By default particle system starts as soon as they are created. This prevents the
  59953. * automatic start to happen and let you decide when to start emitting particles.
  59954. */
  59955. this.preventAutoStart = false;
  59956. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  59957. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  59958. /**
  59959. * Callback triggered when the particle animation is ending.
  59960. */
  59961. this.onAnimationEnd = null;
  59962. /**
  59963. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  59964. */
  59965. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  59966. /**
  59967. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  59968. * to override the particles.
  59969. */
  59970. this.forceDepthWrite = false;
  59971. /** 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 */
  59972. this.preWarmCycles = 0;
  59973. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  59974. this.preWarmStepOffset = 1;
  59975. /**
  59976. * 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)
  59977. */
  59978. this.spriteCellChangeSpeed = 1;
  59979. /**
  59980. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  59981. */
  59982. this.startSpriteCellID = 0;
  59983. /**
  59984. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  59985. */
  59986. this.endSpriteCellID = 0;
  59987. /**
  59988. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  59989. */
  59990. this.spriteCellWidth = 0;
  59991. /**
  59992. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  59993. */
  59994. this.spriteCellHeight = 0;
  59995. /**
  59996. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  59997. */
  59998. this.spriteRandomStartCell = false;
  59999. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  60000. this.translationPivot = new BABYLON.Vector2(0, 0);
  60001. /**
  60002. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  60003. */
  60004. this.beginAnimationOnStart = false;
  60005. /**
  60006. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  60007. */
  60008. this.beginAnimationFrom = 0;
  60009. /**
  60010. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  60011. */
  60012. this.beginAnimationTo = 60;
  60013. /**
  60014. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  60015. */
  60016. this.beginAnimationLoop = false;
  60017. /**
  60018. * You can use gravity if you want to give an orientation to your particles.
  60019. */
  60020. this.gravity = BABYLON.Vector3.Zero();
  60021. this._colorGradients = null;
  60022. this._sizeGradients = null;
  60023. this._lifeTimeGradients = null;
  60024. this._angularSpeedGradients = null;
  60025. this._velocityGradients = null;
  60026. this._limitVelocityGradients = null;
  60027. this._dragGradients = null;
  60028. this._emitRateGradients = null;
  60029. this._startSizeGradients = null;
  60030. this._rampGradients = null;
  60031. this._colorRemapGradients = null;
  60032. this._alphaRemapGradients = null;
  60033. /**
  60034. * Defines the delay in milliseconds before starting the system (0 by default)
  60035. */
  60036. this.startDelay = 0;
  60037. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  60038. this.limitVelocityDamping = 0.4;
  60039. /**
  60040. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  60041. */
  60042. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60043. /**
  60044. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  60045. */
  60046. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60047. /**
  60048. * Color the particle will have at the end of its lifetime
  60049. */
  60050. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  60051. /**
  60052. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  60053. */
  60054. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60055. /** @hidden */
  60056. this._isSubEmitter = false;
  60057. /**
  60058. * Gets or sets the billboard mode to use when isBillboardBased = true.
  60059. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  60060. */
  60061. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  60062. this._isBillboardBased = true;
  60063. /**
  60064. * Local cache of defines for image processing.
  60065. */
  60066. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  60067. this.id = name;
  60068. this.name = name;
  60069. }
  60070. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  60071. /**
  60072. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  60073. */
  60074. get: function () {
  60075. return this._isAnimationSheetEnabled;
  60076. },
  60077. set: function (value) {
  60078. if (this._isAnimationSheetEnabled == value) {
  60079. return;
  60080. }
  60081. this._isAnimationSheetEnabled = value;
  60082. this._reset();
  60083. },
  60084. enumerable: true,
  60085. configurable: true
  60086. });
  60087. /**
  60088. * Get hosting scene
  60089. * @returns the scene
  60090. */
  60091. BaseParticleSystem.prototype.getScene = function () {
  60092. return this._scene;
  60093. };
  60094. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  60095. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  60096. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  60097. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  60098. };
  60099. /**
  60100. * Gets the current list of drag gradients.
  60101. * You must use addDragGradient and removeDragGradient to udpate this list
  60102. * @returns the list of drag gradients
  60103. */
  60104. BaseParticleSystem.prototype.getDragGradients = function () {
  60105. return this._dragGradients;
  60106. };
  60107. /**
  60108. * Gets the current list of limit velocity gradients.
  60109. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  60110. * @returns the list of limit velocity gradients
  60111. */
  60112. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  60113. return this._limitVelocityGradients;
  60114. };
  60115. /**
  60116. * Gets the current list of color gradients.
  60117. * You must use addColorGradient and removeColorGradient to udpate this list
  60118. * @returns the list of color gradients
  60119. */
  60120. BaseParticleSystem.prototype.getColorGradients = function () {
  60121. return this._colorGradients;
  60122. };
  60123. /**
  60124. * Gets the current list of size gradients.
  60125. * You must use addSizeGradient and removeSizeGradient to udpate this list
  60126. * @returns the list of size gradients
  60127. */
  60128. BaseParticleSystem.prototype.getSizeGradients = function () {
  60129. return this._sizeGradients;
  60130. };
  60131. /**
  60132. * Gets the current list of color remap gradients.
  60133. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  60134. * @returns the list of color remap gradients
  60135. */
  60136. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  60137. return this._colorRemapGradients;
  60138. };
  60139. /**
  60140. * Gets the current list of alpha remap gradients.
  60141. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  60142. * @returns the list of alpha remap gradients
  60143. */
  60144. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  60145. return this._alphaRemapGradients;
  60146. };
  60147. /**
  60148. * Gets the current list of life time gradients.
  60149. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  60150. * @returns the list of life time gradients
  60151. */
  60152. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  60153. return this._lifeTimeGradients;
  60154. };
  60155. /**
  60156. * Gets the current list of angular speed gradients.
  60157. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  60158. * @returns the list of angular speed gradients
  60159. */
  60160. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  60161. return this._angularSpeedGradients;
  60162. };
  60163. /**
  60164. * Gets the current list of velocity gradients.
  60165. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  60166. * @returns the list of velocity gradients
  60167. */
  60168. BaseParticleSystem.prototype.getVelocityGradients = function () {
  60169. return this._velocityGradients;
  60170. };
  60171. /**
  60172. * Gets the current list of start size gradients.
  60173. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  60174. * @returns the list of start size gradients
  60175. */
  60176. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  60177. return this._startSizeGradients;
  60178. };
  60179. /**
  60180. * Gets the current list of emit rate gradients.
  60181. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  60182. * @returns the list of emit rate gradients
  60183. */
  60184. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  60185. return this._emitRateGradients;
  60186. };
  60187. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  60188. /**
  60189. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60190. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60191. */
  60192. get: function () {
  60193. if (this.particleEmitterType.direction1) {
  60194. return this.particleEmitterType.direction1;
  60195. }
  60196. return BABYLON.Vector3.Zero();
  60197. },
  60198. set: function (value) {
  60199. if (this.particleEmitterType.direction1) {
  60200. this.particleEmitterType.direction1 = value;
  60201. }
  60202. },
  60203. enumerable: true,
  60204. configurable: true
  60205. });
  60206. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  60207. /**
  60208. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60209. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60210. */
  60211. get: function () {
  60212. if (this.particleEmitterType.direction2) {
  60213. return this.particleEmitterType.direction2;
  60214. }
  60215. return BABYLON.Vector3.Zero();
  60216. },
  60217. set: function (value) {
  60218. if (this.particleEmitterType.direction2) {
  60219. this.particleEmitterType.direction2 = value;
  60220. }
  60221. },
  60222. enumerable: true,
  60223. configurable: true
  60224. });
  60225. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  60226. /**
  60227. * 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.
  60228. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60229. */
  60230. get: function () {
  60231. if (this.particleEmitterType.minEmitBox) {
  60232. return this.particleEmitterType.minEmitBox;
  60233. }
  60234. return BABYLON.Vector3.Zero();
  60235. },
  60236. set: function (value) {
  60237. if (this.particleEmitterType.minEmitBox) {
  60238. this.particleEmitterType.minEmitBox = value;
  60239. }
  60240. },
  60241. enumerable: true,
  60242. configurable: true
  60243. });
  60244. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  60245. /**
  60246. * 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.
  60247. * This only works when particleEmitterTyps is a BoxParticleEmitter
  60248. */
  60249. get: function () {
  60250. if (this.particleEmitterType.maxEmitBox) {
  60251. return this.particleEmitterType.maxEmitBox;
  60252. }
  60253. return BABYLON.Vector3.Zero();
  60254. },
  60255. set: function (value) {
  60256. if (this.particleEmitterType.maxEmitBox) {
  60257. this.particleEmitterType.maxEmitBox = value;
  60258. }
  60259. },
  60260. enumerable: true,
  60261. configurable: true
  60262. });
  60263. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  60264. /**
  60265. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  60266. */
  60267. get: function () {
  60268. return this._isBillboardBased;
  60269. },
  60270. set: function (value) {
  60271. if (this._isBillboardBased === value) {
  60272. return;
  60273. }
  60274. this._isBillboardBased = value;
  60275. this._reset();
  60276. },
  60277. enumerable: true,
  60278. configurable: true
  60279. });
  60280. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  60281. /**
  60282. * Gets the image processing configuration used either in this material.
  60283. */
  60284. get: function () {
  60285. return this._imageProcessingConfiguration;
  60286. },
  60287. /**
  60288. * Sets the Default image processing configuration used either in the this material.
  60289. *
  60290. * If sets to null, the scene one is in use.
  60291. */
  60292. set: function (value) {
  60293. this._attachImageProcessingConfiguration(value);
  60294. },
  60295. enumerable: true,
  60296. configurable: true
  60297. });
  60298. /**
  60299. * Attaches a new image processing configuration to the Standard Material.
  60300. * @param configuration
  60301. */
  60302. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  60303. if (configuration === this._imageProcessingConfiguration) {
  60304. return;
  60305. }
  60306. // Pick the scene configuration if needed.
  60307. if (!configuration) {
  60308. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  60309. }
  60310. else {
  60311. this._imageProcessingConfiguration = configuration;
  60312. }
  60313. };
  60314. /** @hidden */
  60315. BaseParticleSystem.prototype._reset = function () {
  60316. };
  60317. /** @hidden */
  60318. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  60319. if (!gradients) {
  60320. return this;
  60321. }
  60322. var index = 0;
  60323. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  60324. var valueGradient = gradients_1[_i];
  60325. if (valueGradient.gradient === gradient) {
  60326. gradients.splice(index, 1);
  60327. break;
  60328. }
  60329. index++;
  60330. }
  60331. if (texture) {
  60332. texture.dispose();
  60333. }
  60334. return this;
  60335. };
  60336. /**
  60337. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  60338. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  60339. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  60340. * @returns the emitter
  60341. */
  60342. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  60343. var particleEmitter = new BABYLON.PointParticleEmitter();
  60344. particleEmitter.direction1 = direction1;
  60345. particleEmitter.direction2 = direction2;
  60346. this.particleEmitterType = particleEmitter;
  60347. return particleEmitter;
  60348. };
  60349. /**
  60350. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  60351. * @param radius The radius of the hemisphere to emit from
  60352. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  60353. * @returns the emitter
  60354. */
  60355. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  60356. if (radius === void 0) { radius = 1; }
  60357. if (radiusRange === void 0) { radiusRange = 1; }
  60358. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  60359. this.particleEmitterType = particleEmitter;
  60360. return particleEmitter;
  60361. };
  60362. /**
  60363. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  60364. * @param radius The radius of the sphere to emit from
  60365. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  60366. * @returns the emitter
  60367. */
  60368. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  60369. if (radius === void 0) { radius = 1; }
  60370. if (radiusRange === void 0) { radiusRange = 1; }
  60371. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  60372. this.particleEmitterType = particleEmitter;
  60373. return particleEmitter;
  60374. };
  60375. /**
  60376. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  60377. * @param radius The radius of the sphere to emit from
  60378. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  60379. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  60380. * @returns the emitter
  60381. */
  60382. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  60383. if (radius === void 0) { radius = 1; }
  60384. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  60385. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  60386. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  60387. this.particleEmitterType = particleEmitter;
  60388. return particleEmitter;
  60389. };
  60390. /**
  60391. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  60392. * @param radius The radius of the emission cylinder
  60393. * @param height The height of the emission cylinder
  60394. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  60395. * @param directionRandomizer How much to randomize the particle direction [0-1]
  60396. * @returns the emitter
  60397. */
  60398. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  60399. if (radius === void 0) { radius = 1; }
  60400. if (height === void 0) { height = 1; }
  60401. if (radiusRange === void 0) { radiusRange = 1; }
  60402. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60403. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  60404. this.particleEmitterType = particleEmitter;
  60405. return particleEmitter;
  60406. };
  60407. /**
  60408. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  60409. * @param radius The radius of the cylinder to emit from
  60410. * @param height The height of the emission cylinder
  60411. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60412. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  60413. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  60414. * @returns the emitter
  60415. */
  60416. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  60417. if (radius === void 0) { radius = 1; }
  60418. if (height === void 0) { height = 1; }
  60419. if (radiusRange === void 0) { radiusRange = 1; }
  60420. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  60421. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  60422. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  60423. this.particleEmitterType = particleEmitter;
  60424. return particleEmitter;
  60425. };
  60426. /**
  60427. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  60428. * @param radius The radius of the cone to emit from
  60429. * @param angle The base angle of the cone
  60430. * @returns the emitter
  60431. */
  60432. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  60433. if (radius === void 0) { radius = 1; }
  60434. if (angle === void 0) { angle = Math.PI / 4; }
  60435. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  60436. this.particleEmitterType = particleEmitter;
  60437. return particleEmitter;
  60438. };
  60439. /**
  60440. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  60441. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  60442. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  60443. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  60444. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  60445. * @returns the emitter
  60446. */
  60447. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  60448. var particleEmitter = new BABYLON.BoxParticleEmitter();
  60449. this.particleEmitterType = particleEmitter;
  60450. this.direction1 = direction1;
  60451. this.direction2 = direction2;
  60452. this.minEmitBox = minEmitBox;
  60453. this.maxEmitBox = maxEmitBox;
  60454. return particleEmitter;
  60455. };
  60456. /**
  60457. * Source color is added to the destination color without alpha affecting the result
  60458. */
  60459. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  60460. /**
  60461. * Blend current color and particle color using particle’s alpha
  60462. */
  60463. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  60464. /**
  60465. * Add current color and particle color multiplied by particle’s alpha
  60466. */
  60467. BaseParticleSystem.BLENDMODE_ADD = 2;
  60468. /**
  60469. * Multiply current color with particle color
  60470. */
  60471. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  60472. /**
  60473. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  60474. */
  60475. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  60476. return BaseParticleSystem;
  60477. }());
  60478. BABYLON.BaseParticleSystem = BaseParticleSystem;
  60479. })(BABYLON || (BABYLON = {}));
  60480. //# sourceMappingURL=baseParticleSystem.js.map
  60481. var BABYLON;
  60482. (function (BABYLON) {
  60483. /**
  60484. * This represents a particle system in Babylon.
  60485. * 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.
  60486. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  60487. * @example https://doc.babylonjs.com/babylon101/particles
  60488. */
  60489. var ParticleSystem = /** @class */ (function (_super) {
  60490. __extends(ParticleSystem, _super);
  60491. /**
  60492. * Instantiates a particle system.
  60493. * 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.
  60494. * @param name The name of the particle system
  60495. * @param capacity The max number of particles alive at the same time
  60496. * @param scene The scene the particle system belongs to
  60497. * @param customEffect a custom effect used to change the way particles are rendered by default
  60498. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  60499. * @param epsilon Offset used to render the particles
  60500. */
  60501. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  60502. if (customEffect === void 0) { customEffect = null; }
  60503. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60504. if (epsilon === void 0) { epsilon = 0.01; }
  60505. var _this = _super.call(this, name) || this;
  60506. /**
  60507. * @hidden
  60508. */
  60509. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  60510. /**
  60511. * An event triggered when the system is disposed
  60512. */
  60513. _this.onDisposeObservable = new BABYLON.Observable();
  60514. _this._particles = new Array();
  60515. _this._stockParticles = new Array();
  60516. _this._newPartsExcess = 0;
  60517. _this._vertexBuffers = {};
  60518. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  60519. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  60520. _this._scaledDirection = BABYLON.Vector3.Zero();
  60521. _this._scaledGravity = BABYLON.Vector3.Zero();
  60522. _this._currentRenderId = -1;
  60523. _this._useInstancing = false;
  60524. _this._started = false;
  60525. _this._stopped = false;
  60526. _this._actualFrame = 0;
  60527. /** @hidden */
  60528. _this._currentEmitRate1 = 0;
  60529. /** @hidden */
  60530. _this._currentEmitRate2 = 0;
  60531. /** @hidden */
  60532. _this._currentStartSize1 = 0;
  60533. /** @hidden */
  60534. _this._currentStartSize2 = 0;
  60535. _this._rawTextureWidth = 256;
  60536. _this._useRampGradients = false;
  60537. /**
  60538. * @hidden
  60539. * If the particle systems emitter should be disposed when the particle system is disposed
  60540. */
  60541. _this._disposeEmitterOnDispose = false;
  60542. // start of sub system methods
  60543. /**
  60544. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  60545. * Its lifetime will start back at 0.
  60546. */
  60547. _this.recycleParticle = function (particle) {
  60548. // move particle from activeParticle list to stock particles
  60549. var lastParticle = _this._particles.pop();
  60550. if (lastParticle !== particle) {
  60551. lastParticle.copyTo(particle);
  60552. }
  60553. _this._stockParticles.push(lastParticle);
  60554. };
  60555. _this._createParticle = function () {
  60556. var particle;
  60557. if (_this._stockParticles.length !== 0) {
  60558. particle = _this._stockParticles.pop();
  60559. particle._reset();
  60560. }
  60561. else {
  60562. particle = new BABYLON.Particle(_this);
  60563. }
  60564. // Attach emitters
  60565. if (_this._subEmitters && _this._subEmitters.length > 0) {
  60566. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  60567. particle._attachedSubEmitters = [];
  60568. subEmitters.forEach(function (subEmitter) {
  60569. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  60570. var newEmitter = subEmitter.clone();
  60571. particle._attachedSubEmitters.push(newEmitter);
  60572. newEmitter.particleSystem.start();
  60573. }
  60574. });
  60575. }
  60576. return particle;
  60577. };
  60578. _this._emitFromParticle = function (particle) {
  60579. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  60580. return;
  60581. }
  60582. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  60583. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  60584. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  60585. var subSystem = subEmitter.clone();
  60586. particle._inheritParticleInfoToSubEmitter(subSystem);
  60587. subSystem.particleSystem._rootParticleSystem = _this;
  60588. _this.activeSubSystems.push(subSystem.particleSystem);
  60589. subSystem.particleSystem.start();
  60590. }
  60591. });
  60592. };
  60593. _this._capacity = capacity;
  60594. _this._epsilon = epsilon;
  60595. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  60596. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60597. // Setup the default processing configuration to the scene.
  60598. _this._attachImageProcessingConfiguration(null);
  60599. _this._customEffect = customEffect;
  60600. _this._scene.particleSystems.push(_this);
  60601. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  60602. _this._createIndexBuffer();
  60603. _this._createVertexBuffers();
  60604. // Default emitter type
  60605. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  60606. // Update
  60607. _this.updateFunction = function (particles) {
  60608. var noiseTextureSize = null;
  60609. var noiseTextureData = null;
  60610. if (_this.noiseTexture) { // We need to get texture data back to CPU
  60611. noiseTextureSize = _this.noiseTexture.getSize();
  60612. noiseTextureData = (_this.noiseTexture.getContent());
  60613. }
  60614. var _loop_1 = function () {
  60615. particle = particles[index];
  60616. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  60617. var previousAge = particle.age;
  60618. particle.age += scaledUpdateSpeed;
  60619. // Evaluate step to death
  60620. if (particle.age > particle.lifeTime) {
  60621. var diff = particle.age - previousAge;
  60622. var oldDiff = particle.lifeTime - previousAge;
  60623. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  60624. particle.age = particle.lifeTime;
  60625. }
  60626. var ratio = particle.age / particle.lifeTime;
  60627. // Color
  60628. if (_this._colorGradients && _this._colorGradients.length > 0) {
  60629. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  60630. if (currentGradient !== particle._currentColorGradient) {
  60631. particle._currentColor1.copyFrom(particle._currentColor2);
  60632. nextGradient.getColorToRef(particle._currentColor2);
  60633. particle._currentColorGradient = currentGradient;
  60634. }
  60635. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  60636. });
  60637. }
  60638. else {
  60639. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  60640. particle.color.addInPlace(_this._scaledColorStep);
  60641. if (particle.color.a < 0) {
  60642. particle.color.a = 0;
  60643. }
  60644. }
  60645. // Angular speed
  60646. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  60647. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  60648. if (currentGradient !== particle._currentAngularSpeedGradient) {
  60649. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  60650. particle._currentAngularSpeed2 = nextGradient.getFactor();
  60651. particle._currentAngularSpeedGradient = currentGradient;
  60652. }
  60653. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  60654. });
  60655. }
  60656. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  60657. // Direction
  60658. var directionScale = scaledUpdateSpeed;
  60659. /// Velocity
  60660. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  60661. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  60662. if (currentGradient !== particle._currentVelocityGradient) {
  60663. particle._currentVelocity1 = particle._currentVelocity2;
  60664. particle._currentVelocity2 = nextGradient.getFactor();
  60665. particle._currentVelocityGradient = currentGradient;
  60666. }
  60667. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  60668. });
  60669. }
  60670. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  60671. /// Limit velocity
  60672. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  60673. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  60674. if (currentGradient !== particle._currentLimitVelocityGradient) {
  60675. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  60676. particle._currentLimitVelocity2 = nextGradient.getFactor();
  60677. particle._currentLimitVelocityGradient = currentGradient;
  60678. }
  60679. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  60680. var currentVelocity = particle.direction.length();
  60681. if (currentVelocity > limitVelocity) {
  60682. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  60683. }
  60684. });
  60685. }
  60686. /// Drag
  60687. if (_this._dragGradients && _this._dragGradients.length > 0) {
  60688. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  60689. if (currentGradient !== particle._currentDragGradient) {
  60690. particle._currentDrag1 = particle._currentDrag2;
  60691. particle._currentDrag2 = nextGradient.getFactor();
  60692. particle._currentDragGradient = currentGradient;
  60693. }
  60694. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  60695. _this._scaledDirection.scaleInPlace(1.0 - drag);
  60696. });
  60697. }
  60698. particle.position.addInPlace(_this._scaledDirection);
  60699. // Noise
  60700. if (noiseTextureData && noiseTextureSize) {
  60701. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  60702. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  60703. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  60704. var force = BABYLON.Tmp.Vector3[0];
  60705. var scaledForce = BABYLON.Tmp.Vector3[1];
  60706. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  60707. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  60708. particle.direction.addInPlace(scaledForce);
  60709. }
  60710. // Gravity
  60711. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  60712. particle.direction.addInPlace(_this._scaledGravity);
  60713. // Size
  60714. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  60715. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  60716. if (currentGradient !== particle._currentSizeGradient) {
  60717. particle._currentSize1 = particle._currentSize2;
  60718. particle._currentSize2 = nextGradient.getFactor();
  60719. particle._currentSizeGradient = currentGradient;
  60720. }
  60721. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  60722. });
  60723. }
  60724. // Remap data
  60725. if (_this._useRampGradients) {
  60726. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  60727. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  60728. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  60729. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  60730. particle.remapData.x = min;
  60731. particle.remapData.y = max - min;
  60732. });
  60733. }
  60734. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  60735. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  60736. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  60737. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  60738. particle.remapData.z = min;
  60739. particle.remapData.w = max - min;
  60740. });
  60741. }
  60742. }
  60743. if (_this._isAnimationSheetEnabled) {
  60744. particle.updateCellIndex();
  60745. }
  60746. // Update the position of the attached sub-emitters to match their attached particle
  60747. particle._inheritParticleInfoToSubEmitters();
  60748. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  60749. _this._emitFromParticle(particle);
  60750. if (particle._attachedSubEmitters) {
  60751. particle._attachedSubEmitters.forEach(function (subEmitter) {
  60752. subEmitter.particleSystem.disposeOnStop = true;
  60753. subEmitter.particleSystem.stop();
  60754. });
  60755. particle._attachedSubEmitters = null;
  60756. }
  60757. _this.recycleParticle(particle);
  60758. index--;
  60759. return "continue";
  60760. }
  60761. };
  60762. var particle;
  60763. for (var index = 0; index < particles.length; index++) {
  60764. _loop_1();
  60765. }
  60766. };
  60767. return _this;
  60768. }
  60769. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  60770. /**
  60771. * Sets a callback that will be triggered when the system is disposed
  60772. */
  60773. set: function (callback) {
  60774. if (this._onDisposeObserver) {
  60775. this.onDisposeObservable.remove(this._onDisposeObserver);
  60776. }
  60777. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  60778. },
  60779. enumerable: true,
  60780. configurable: true
  60781. });
  60782. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  60783. /** Gets or sets a boolean indicating that ramp gradients must be used
  60784. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  60785. */
  60786. get: function () {
  60787. return this._useRampGradients;
  60788. },
  60789. set: function (value) {
  60790. if (this._useRampGradients === value) {
  60791. return;
  60792. }
  60793. this._useRampGradients = value;
  60794. this._resetEffect();
  60795. },
  60796. enumerable: true,
  60797. configurable: true
  60798. });
  60799. Object.defineProperty(ParticleSystem.prototype, "particles", {
  60800. //end of Sub-emitter
  60801. /**
  60802. * Gets the current list of active particles
  60803. */
  60804. get: function () {
  60805. return this._particles;
  60806. },
  60807. enumerable: true,
  60808. configurable: true
  60809. });
  60810. /**
  60811. * Returns the string "ParticleSystem"
  60812. * @returns a string containing the class name
  60813. */
  60814. ParticleSystem.prototype.getClassName = function () {
  60815. return "ParticleSystem";
  60816. };
  60817. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  60818. var newGradient = new BABYLON.FactorGradient();
  60819. newGradient.gradient = gradient;
  60820. newGradient.factor1 = factor;
  60821. newGradient.factor2 = factor2;
  60822. factorGradients.push(newGradient);
  60823. factorGradients.sort(function (a, b) {
  60824. if (a.gradient < b.gradient) {
  60825. return -1;
  60826. }
  60827. else if (a.gradient > b.gradient) {
  60828. return 1;
  60829. }
  60830. return 0;
  60831. });
  60832. };
  60833. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  60834. if (!factorGradients) {
  60835. return;
  60836. }
  60837. var index = 0;
  60838. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  60839. var factorGradient = factorGradients_1[_i];
  60840. if (factorGradient.gradient === gradient) {
  60841. factorGradients.splice(index, 1);
  60842. break;
  60843. }
  60844. index++;
  60845. }
  60846. };
  60847. /**
  60848. * Adds a new life time gradient
  60849. * @param gradient defines the gradient to use (between 0 and 1)
  60850. * @param factor defines the life time factor to affect to the specified gradient
  60851. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60852. * @returns the current particle system
  60853. */
  60854. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  60855. if (!this._lifeTimeGradients) {
  60856. this._lifeTimeGradients = [];
  60857. }
  60858. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  60859. return this;
  60860. };
  60861. /**
  60862. * Remove a specific life time gradient
  60863. * @param gradient defines the gradient to remove
  60864. * @returns the current particle system
  60865. */
  60866. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  60867. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  60868. return this;
  60869. };
  60870. /**
  60871. * Adds a new size gradient
  60872. * @param gradient defines the gradient to use (between 0 and 1)
  60873. * @param factor defines the size factor to affect to the specified gradient
  60874. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60875. * @returns the current particle system
  60876. */
  60877. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  60878. if (!this._sizeGradients) {
  60879. this._sizeGradients = [];
  60880. }
  60881. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  60882. return this;
  60883. };
  60884. /**
  60885. * Remove a specific size gradient
  60886. * @param gradient defines the gradient to remove
  60887. * @returns the current particle system
  60888. */
  60889. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  60890. this._removeFactorGradient(this._sizeGradients, gradient);
  60891. return this;
  60892. };
  60893. /**
  60894. * Adds a new color remap gradient
  60895. * @param gradient defines the gradient to use (between 0 and 1)
  60896. * @param min defines the color remap minimal range
  60897. * @param max defines the color remap maximal range
  60898. * @returns the current particle system
  60899. */
  60900. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  60901. if (!this._colorRemapGradients) {
  60902. this._colorRemapGradients = [];
  60903. }
  60904. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  60905. return this;
  60906. };
  60907. /**
  60908. * Remove a specific color remap gradient
  60909. * @param gradient defines the gradient to remove
  60910. * @returns the current particle system
  60911. */
  60912. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  60913. this._removeFactorGradient(this._colorRemapGradients, gradient);
  60914. return this;
  60915. };
  60916. /**
  60917. * Adds a new alpha remap gradient
  60918. * @param gradient defines the gradient to use (between 0 and 1)
  60919. * @param min defines the alpha remap minimal range
  60920. * @param max defines the alpha remap maximal range
  60921. * @returns the current particle system
  60922. */
  60923. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  60924. if (!this._alphaRemapGradients) {
  60925. this._alphaRemapGradients = [];
  60926. }
  60927. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  60928. return this;
  60929. };
  60930. /**
  60931. * Remove a specific alpha remap gradient
  60932. * @param gradient defines the gradient to remove
  60933. * @returns the current particle system
  60934. */
  60935. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  60936. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  60937. return this;
  60938. };
  60939. /**
  60940. * Adds a new angular speed gradient
  60941. * @param gradient defines the gradient to use (between 0 and 1)
  60942. * @param factor defines the angular speed to affect to the specified gradient
  60943. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60944. * @returns the current particle system
  60945. */
  60946. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  60947. if (!this._angularSpeedGradients) {
  60948. this._angularSpeedGradients = [];
  60949. }
  60950. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  60951. return this;
  60952. };
  60953. /**
  60954. * Remove a specific angular speed gradient
  60955. * @param gradient defines the gradient to remove
  60956. * @returns the current particle system
  60957. */
  60958. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  60959. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  60960. return this;
  60961. };
  60962. /**
  60963. * Adds a new velocity gradient
  60964. * @param gradient defines the gradient to use (between 0 and 1)
  60965. * @param factor defines the velocity to affect to the specified gradient
  60966. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60967. * @returns the current particle system
  60968. */
  60969. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  60970. if (!this._velocityGradients) {
  60971. this._velocityGradients = [];
  60972. }
  60973. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  60974. return this;
  60975. };
  60976. /**
  60977. * Remove a specific velocity gradient
  60978. * @param gradient defines the gradient to remove
  60979. * @returns the current particle system
  60980. */
  60981. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  60982. this._removeFactorGradient(this._velocityGradients, gradient);
  60983. return this;
  60984. };
  60985. /**
  60986. * Adds a new limit velocity gradient
  60987. * @param gradient defines the gradient to use (between 0 and 1)
  60988. * @param factor defines the limit velocity value to affect to the specified gradient
  60989. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  60990. * @returns the current particle system
  60991. */
  60992. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  60993. if (!this._limitVelocityGradients) {
  60994. this._limitVelocityGradients = [];
  60995. }
  60996. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  60997. return this;
  60998. };
  60999. /**
  61000. * Remove a specific limit velocity gradient
  61001. * @param gradient defines the gradient to remove
  61002. * @returns the current particle system
  61003. */
  61004. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  61005. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  61006. return this;
  61007. };
  61008. /**
  61009. * Adds a new drag gradient
  61010. * @param gradient defines the gradient to use (between 0 and 1)
  61011. * @param factor defines the drag value to affect to the specified gradient
  61012. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61013. * @returns the current particle system
  61014. */
  61015. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  61016. if (!this._dragGradients) {
  61017. this._dragGradients = [];
  61018. }
  61019. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  61020. return this;
  61021. };
  61022. /**
  61023. * Remove a specific drag gradient
  61024. * @param gradient defines the gradient to remove
  61025. * @returns the current particle system
  61026. */
  61027. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  61028. this._removeFactorGradient(this._dragGradients, gradient);
  61029. return this;
  61030. };
  61031. /**
  61032. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  61033. * @param gradient defines the gradient to use (between 0 and 1)
  61034. * @param factor defines the emit rate value to affect to the specified gradient
  61035. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61036. * @returns the current particle system
  61037. */
  61038. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  61039. if (!this._emitRateGradients) {
  61040. this._emitRateGradients = [];
  61041. }
  61042. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  61043. return this;
  61044. };
  61045. /**
  61046. * Remove a specific emit rate gradient
  61047. * @param gradient defines the gradient to remove
  61048. * @returns the current particle system
  61049. */
  61050. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  61051. this._removeFactorGradient(this._emitRateGradients, gradient);
  61052. return this;
  61053. };
  61054. /**
  61055. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  61056. * @param gradient defines the gradient to use (between 0 and 1)
  61057. * @param factor defines the start size value to affect to the specified gradient
  61058. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61059. * @returns the current particle system
  61060. */
  61061. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  61062. if (!this._startSizeGradients) {
  61063. this._startSizeGradients = [];
  61064. }
  61065. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  61066. return this;
  61067. };
  61068. /**
  61069. * Remove a specific start size gradient
  61070. * @param gradient defines the gradient to remove
  61071. * @returns the current particle system
  61072. */
  61073. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  61074. this._removeFactorGradient(this._emitRateGradients, gradient);
  61075. return this;
  61076. };
  61077. ParticleSystem.prototype._createRampGradientTexture = function () {
  61078. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  61079. return;
  61080. }
  61081. var data = new Uint8Array(this._rawTextureWidth * 4);
  61082. var tmpColor = BABYLON.Tmp.Color3[0];
  61083. for (var x = 0; x < this._rawTextureWidth; x++) {
  61084. var ratio = x / this._rawTextureWidth;
  61085. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  61086. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  61087. data[x * 4] = tmpColor.r * 255;
  61088. data[x * 4 + 1] = tmpColor.g * 255;
  61089. data[x * 4 + 2] = tmpColor.b * 255;
  61090. data[x * 4 + 3] = 255;
  61091. });
  61092. }
  61093. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61094. };
  61095. /**
  61096. * Gets the current list of ramp gradients.
  61097. * You must use addRampGradient and removeRampGradient to udpate this list
  61098. * @returns the list of ramp gradients
  61099. */
  61100. ParticleSystem.prototype.getRampGradients = function () {
  61101. return this._rampGradients;
  61102. };
  61103. /**
  61104. * Adds a new ramp gradient used to remap particle colors
  61105. * @param gradient defines the gradient to use (between 0 and 1)
  61106. * @param color defines the color to affect to the specified gradient
  61107. * @returns the current particle system
  61108. */
  61109. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  61110. if (!this._rampGradients) {
  61111. this._rampGradients = [];
  61112. }
  61113. var rampGradient = new BABYLON.Color3Gradient();
  61114. rampGradient.gradient = gradient;
  61115. rampGradient.color = color;
  61116. this._rampGradients.push(rampGradient);
  61117. this._rampGradients.sort(function (a, b) {
  61118. if (a.gradient < b.gradient) {
  61119. return -1;
  61120. }
  61121. else if (a.gradient > b.gradient) {
  61122. return 1;
  61123. }
  61124. return 0;
  61125. });
  61126. if (this._rampGradientsTexture) {
  61127. this._rampGradientsTexture.dispose();
  61128. this._rampGradientsTexture = null;
  61129. }
  61130. this._createRampGradientTexture();
  61131. return this;
  61132. };
  61133. /**
  61134. * Remove a specific ramp gradient
  61135. * @param gradient defines the gradient to remove
  61136. * @returns the current particle system
  61137. */
  61138. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  61139. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  61140. this._rampGradientsTexture = null;
  61141. if (this._rampGradients && this._rampGradients.length > 0) {
  61142. this._createRampGradientTexture();
  61143. }
  61144. return this;
  61145. };
  61146. /**
  61147. * Adds a new color gradient
  61148. * @param gradient defines the gradient to use (between 0 and 1)
  61149. * @param color1 defines the color to affect to the specified gradient
  61150. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  61151. * @returns this particle system
  61152. */
  61153. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  61154. if (!this._colorGradients) {
  61155. this._colorGradients = [];
  61156. }
  61157. var colorGradient = new BABYLON.ColorGradient();
  61158. colorGradient.gradient = gradient;
  61159. colorGradient.color1 = color1;
  61160. colorGradient.color2 = color2;
  61161. this._colorGradients.push(colorGradient);
  61162. this._colorGradients.sort(function (a, b) {
  61163. if (a.gradient < b.gradient) {
  61164. return -1;
  61165. }
  61166. else if (a.gradient > b.gradient) {
  61167. return 1;
  61168. }
  61169. return 0;
  61170. });
  61171. return this;
  61172. };
  61173. /**
  61174. * Remove a specific color gradient
  61175. * @param gradient defines the gradient to remove
  61176. * @returns this particle system
  61177. */
  61178. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  61179. if (!this._colorGradients) {
  61180. return this;
  61181. }
  61182. var index = 0;
  61183. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  61184. var colorGradient = _a[_i];
  61185. if (colorGradient.gradient === gradient) {
  61186. this._colorGradients.splice(index, 1);
  61187. break;
  61188. }
  61189. index++;
  61190. }
  61191. return this;
  61192. };
  61193. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  61194. u = Math.abs(u) * 0.5 + 0.5;
  61195. v = Math.abs(v) * 0.5 + 0.5;
  61196. var wrappedU = ((u * width) % width) | 0;
  61197. var wrappedV = ((v * height) % height) | 0;
  61198. var position = (wrappedU + wrappedV * width) * 4;
  61199. return pixels[position] / 255;
  61200. };
  61201. ParticleSystem.prototype._reset = function () {
  61202. this._resetEffect();
  61203. };
  61204. ParticleSystem.prototype._resetEffect = function () {
  61205. if (this._vertexBuffer) {
  61206. this._vertexBuffer.dispose();
  61207. this._vertexBuffer = null;
  61208. }
  61209. if (this._spriteBuffer) {
  61210. this._spriteBuffer.dispose();
  61211. this._spriteBuffer = null;
  61212. }
  61213. this._createVertexBuffers();
  61214. };
  61215. ParticleSystem.prototype._createVertexBuffers = function () {
  61216. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  61217. if (this._isAnimationSheetEnabled) {
  61218. this._vertexBufferSize += 1;
  61219. }
  61220. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  61221. this._vertexBufferSize += 3;
  61222. }
  61223. if (this._useRampGradients) {
  61224. this._vertexBufferSize += 4;
  61225. }
  61226. var engine = this._scene.getEngine();
  61227. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  61228. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  61229. var dataOffset = 0;
  61230. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  61231. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  61232. dataOffset += 3;
  61233. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  61234. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  61235. dataOffset += 4;
  61236. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  61237. this._vertexBuffers["angle"] = options;
  61238. dataOffset += 1;
  61239. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  61240. this._vertexBuffers["size"] = size;
  61241. dataOffset += 2;
  61242. if (this._isAnimationSheetEnabled) {
  61243. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  61244. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  61245. dataOffset += 1;
  61246. }
  61247. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  61248. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  61249. this._vertexBuffers["direction"] = directionBuffer;
  61250. dataOffset += 3;
  61251. }
  61252. if (this._useRampGradients) {
  61253. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  61254. this._vertexBuffers["remapData"] = rampDataBuffer;
  61255. dataOffset += 4;
  61256. }
  61257. var offsets;
  61258. if (this._useInstancing) {
  61259. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  61260. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  61261. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  61262. }
  61263. else {
  61264. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  61265. dataOffset += 2;
  61266. }
  61267. this._vertexBuffers["offset"] = offsets;
  61268. };
  61269. ParticleSystem.prototype._createIndexBuffer = function () {
  61270. if (this._useInstancing) {
  61271. return;
  61272. }
  61273. var indices = [];
  61274. var index = 0;
  61275. for (var count = 0; count < this._capacity; count++) {
  61276. indices.push(index);
  61277. indices.push(index + 1);
  61278. indices.push(index + 2);
  61279. indices.push(index);
  61280. indices.push(index + 2);
  61281. indices.push(index + 3);
  61282. index += 4;
  61283. }
  61284. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  61285. };
  61286. /**
  61287. * Gets the maximum number of particles active at the same time.
  61288. * @returns The max number of active particles.
  61289. */
  61290. ParticleSystem.prototype.getCapacity = function () {
  61291. return this._capacity;
  61292. };
  61293. /**
  61294. * Gets whether there are still active particles in the system.
  61295. * @returns True if it is alive, otherwise false.
  61296. */
  61297. ParticleSystem.prototype.isAlive = function () {
  61298. return this._alive;
  61299. };
  61300. /**
  61301. * Gets if the system has been started. (Note: this will still be true after stop is called)
  61302. * @returns True if it has been started, otherwise false.
  61303. */
  61304. ParticleSystem.prototype.isStarted = function () {
  61305. return this._started;
  61306. };
  61307. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  61308. var _this = this;
  61309. this._subEmitters = new Array();
  61310. if (this.subEmitters) {
  61311. this.subEmitters.forEach(function (subEmitter) {
  61312. if (subEmitter instanceof ParticleSystem) {
  61313. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  61314. }
  61315. else if (subEmitter instanceof BABYLON.SubEmitter) {
  61316. _this._subEmitters.push([subEmitter]);
  61317. }
  61318. else if (subEmitter instanceof Array) {
  61319. _this._subEmitters.push(subEmitter);
  61320. }
  61321. });
  61322. }
  61323. };
  61324. /**
  61325. * Starts the particle system and begins to emit
  61326. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  61327. */
  61328. ParticleSystem.prototype.start = function (delay) {
  61329. var _this = this;
  61330. if (delay === void 0) { delay = this.startDelay; }
  61331. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  61332. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  61333. }
  61334. if (delay) {
  61335. setTimeout(function () {
  61336. _this.start(0);
  61337. }, delay);
  61338. return;
  61339. }
  61340. // Convert the subEmitters field to the constant type field _subEmitters
  61341. this._prepareSubEmitterInternalArray();
  61342. this._started = true;
  61343. this._stopped = false;
  61344. this._actualFrame = 0;
  61345. if (this._subEmitters && this._subEmitters.length != 0) {
  61346. this.activeSubSystems = new Array();
  61347. }
  61348. // Reset emit gradient so it acts the same on every start
  61349. if (this._emitRateGradients) {
  61350. if (this._emitRateGradients.length > 0) {
  61351. this._currentEmitRateGradient = this._emitRateGradients[0];
  61352. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  61353. this._currentEmitRate2 = this._currentEmitRate1;
  61354. }
  61355. if (this._emitRateGradients.length > 1) {
  61356. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  61357. }
  61358. }
  61359. // Reset start size gradient so it acts the same on every start
  61360. if (this._startSizeGradients) {
  61361. if (this._startSizeGradients.length > 0) {
  61362. this._currentStartSizeGradient = this._startSizeGradients[0];
  61363. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  61364. this._currentStartSize2 = this._currentStartSize1;
  61365. }
  61366. if (this._startSizeGradients.length > 1) {
  61367. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  61368. }
  61369. }
  61370. if (this.preWarmCycles) {
  61371. if (this.emitter instanceof BABYLON.AbstractMesh) {
  61372. this.emitter.computeWorldMatrix(true);
  61373. }
  61374. var noiseTextureAsProcedural_1 = this.noiseTexture;
  61375. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  61376. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  61377. setTimeout(function () {
  61378. for (var index = 0; index < _this.preWarmCycles; index++) {
  61379. _this.animate(true);
  61380. noiseTextureAsProcedural_1.render();
  61381. }
  61382. });
  61383. });
  61384. }
  61385. else {
  61386. for (var index = 0; index < this.preWarmCycles; index++) {
  61387. this.animate(true);
  61388. }
  61389. }
  61390. }
  61391. // Animations
  61392. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  61393. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  61394. }
  61395. };
  61396. /**
  61397. * Stops the particle system.
  61398. * @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.
  61399. */
  61400. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  61401. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  61402. this._stopped = true;
  61403. if (stopSubEmitters) {
  61404. this._stopSubEmitters();
  61405. }
  61406. };
  61407. // animation sheet
  61408. /**
  61409. * Remove all active particles
  61410. */
  61411. ParticleSystem.prototype.reset = function () {
  61412. this._stockParticles = [];
  61413. this._particles = [];
  61414. };
  61415. /**
  61416. * @hidden (for internal use only)
  61417. */
  61418. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  61419. var offset = index * this._vertexBufferSize;
  61420. this._vertexData[offset++] = particle.position.x;
  61421. this._vertexData[offset++] = particle.position.y;
  61422. this._vertexData[offset++] = particle.position.z;
  61423. this._vertexData[offset++] = particle.color.r;
  61424. this._vertexData[offset++] = particle.color.g;
  61425. this._vertexData[offset++] = particle.color.b;
  61426. this._vertexData[offset++] = particle.color.a;
  61427. this._vertexData[offset++] = particle.angle;
  61428. this._vertexData[offset++] = particle.scale.x * particle.size;
  61429. this._vertexData[offset++] = particle.scale.y * particle.size;
  61430. if (this._isAnimationSheetEnabled) {
  61431. this._vertexData[offset++] = particle.cellIndex;
  61432. }
  61433. if (!this._isBillboardBased) {
  61434. if (particle._initialDirection) {
  61435. this._vertexData[offset++] = particle._initialDirection.x;
  61436. this._vertexData[offset++] = particle._initialDirection.y;
  61437. this._vertexData[offset++] = particle._initialDirection.z;
  61438. }
  61439. else {
  61440. this._vertexData[offset++] = particle.direction.x;
  61441. this._vertexData[offset++] = particle.direction.y;
  61442. this._vertexData[offset++] = particle.direction.z;
  61443. }
  61444. }
  61445. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  61446. this._vertexData[offset++] = particle.direction.x;
  61447. this._vertexData[offset++] = particle.direction.y;
  61448. this._vertexData[offset++] = particle.direction.z;
  61449. }
  61450. if (this._useRampGradients) {
  61451. this._vertexData[offset++] = particle.remapData.x;
  61452. this._vertexData[offset++] = particle.remapData.y;
  61453. this._vertexData[offset++] = particle.remapData.z;
  61454. this._vertexData[offset++] = particle.remapData.w;
  61455. }
  61456. if (!this._useInstancing) {
  61457. if (this._isAnimationSheetEnabled) {
  61458. if (offsetX === 0) {
  61459. offsetX = this._epsilon;
  61460. }
  61461. else if (offsetX === 1) {
  61462. offsetX = 1 - this._epsilon;
  61463. }
  61464. if (offsetY === 0) {
  61465. offsetY = this._epsilon;
  61466. }
  61467. else if (offsetY === 1) {
  61468. offsetY = 1 - this._epsilon;
  61469. }
  61470. }
  61471. this._vertexData[offset++] = offsetX;
  61472. this._vertexData[offset++] = offsetY;
  61473. }
  61474. };
  61475. ParticleSystem.prototype._stopSubEmitters = function () {
  61476. if (!this.activeSubSystems) {
  61477. return;
  61478. }
  61479. this.activeSubSystems.forEach(function (subSystem) {
  61480. subSystem.stop(true);
  61481. });
  61482. this.activeSubSystems = new Array();
  61483. };
  61484. ParticleSystem.prototype._removeFromRoot = function () {
  61485. if (!this._rootParticleSystem) {
  61486. return;
  61487. }
  61488. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  61489. if (index !== -1) {
  61490. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  61491. }
  61492. this._rootParticleSystem = null;
  61493. };
  61494. // End of sub system methods
  61495. ParticleSystem.prototype._update = function (newParticles) {
  61496. var _this = this;
  61497. // Update current
  61498. this._alive = this._particles.length > 0;
  61499. if (this.emitter.position) {
  61500. var emitterMesh = this.emitter;
  61501. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  61502. }
  61503. else {
  61504. var emitterPosition = this.emitter;
  61505. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  61506. }
  61507. this.updateFunction(this._particles);
  61508. // Add new ones
  61509. var particle;
  61510. var _loop_2 = function () {
  61511. if (this_1._particles.length === this_1._capacity) {
  61512. return "break";
  61513. }
  61514. particle = this_1._createParticle();
  61515. this_1._particles.push(particle);
  61516. // Emitter
  61517. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  61518. if (this_1.startPositionFunction) {
  61519. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  61520. }
  61521. else {
  61522. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  61523. }
  61524. if (this_1.startDirectionFunction) {
  61525. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  61526. }
  61527. else {
  61528. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  61529. }
  61530. if (emitPower === 0) {
  61531. if (!particle._initialDirection) {
  61532. particle._initialDirection = particle.direction.clone();
  61533. }
  61534. else {
  61535. particle._initialDirection.copyFrom(particle.direction);
  61536. }
  61537. }
  61538. else {
  61539. particle._initialDirection = null;
  61540. }
  61541. particle.direction.scaleInPlace(emitPower);
  61542. // Life time
  61543. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  61544. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  61545. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  61546. var factorGradient1 = currentGradient;
  61547. var factorGradient2 = nextGradient;
  61548. var lifeTime1 = factorGradient1.getFactor();
  61549. var lifeTime2 = factorGradient2.getFactor();
  61550. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  61551. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  61552. });
  61553. }
  61554. else {
  61555. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  61556. }
  61557. // Size
  61558. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  61559. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  61560. }
  61561. else {
  61562. particle._currentSizeGradient = this_1._sizeGradients[0];
  61563. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  61564. particle.size = particle._currentSize1;
  61565. if (this_1._sizeGradients.length > 1) {
  61566. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  61567. }
  61568. else {
  61569. particle._currentSize2 = particle._currentSize1;
  61570. }
  61571. }
  61572. // Size and scale
  61573. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  61574. // Adjust scale by start size
  61575. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  61576. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  61577. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  61578. if (currentGradient !== _this._currentStartSizeGradient) {
  61579. _this._currentStartSize1 = _this._currentStartSize2;
  61580. _this._currentStartSize2 = nextGradient.getFactor();
  61581. _this._currentStartSizeGradient = currentGradient;
  61582. }
  61583. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  61584. particle.scale.scaleInPlace(value);
  61585. });
  61586. }
  61587. // Angle
  61588. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  61589. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  61590. }
  61591. else {
  61592. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  61593. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  61594. particle._currentAngularSpeed1 = particle.angularSpeed;
  61595. if (this_1._angularSpeedGradients.length > 1) {
  61596. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  61597. }
  61598. else {
  61599. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  61600. }
  61601. }
  61602. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  61603. // Velocity
  61604. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  61605. particle._currentVelocityGradient = this_1._velocityGradients[0];
  61606. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  61607. if (this_1._velocityGradients.length > 1) {
  61608. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  61609. }
  61610. else {
  61611. particle._currentVelocity2 = particle._currentVelocity1;
  61612. }
  61613. }
  61614. // Limit velocity
  61615. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  61616. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  61617. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  61618. if (this_1._limitVelocityGradients.length > 1) {
  61619. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  61620. }
  61621. else {
  61622. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  61623. }
  61624. }
  61625. // Drag
  61626. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  61627. particle._currentDragGradient = this_1._dragGradients[0];
  61628. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  61629. if (this_1._dragGradients.length > 1) {
  61630. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  61631. }
  61632. else {
  61633. particle._currentDrag2 = particle._currentDrag1;
  61634. }
  61635. }
  61636. // Color
  61637. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  61638. step = BABYLON.Scalar.RandomRange(0, 1.0);
  61639. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  61640. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  61641. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  61642. }
  61643. else {
  61644. particle._currentColorGradient = this_1._colorGradients[0];
  61645. particle._currentColorGradient.getColorToRef(particle.color);
  61646. particle._currentColor1.copyFrom(particle.color);
  61647. if (this_1._colorGradients.length > 1) {
  61648. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  61649. }
  61650. else {
  61651. particle._currentColor2.copyFrom(particle.color);
  61652. }
  61653. }
  61654. // Sheet
  61655. if (this_1._isAnimationSheetEnabled) {
  61656. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  61657. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  61658. }
  61659. // Inherited Velocity
  61660. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  61661. // Ramp
  61662. if (this_1._useRampGradients) {
  61663. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  61664. }
  61665. // Noise texture coordinates
  61666. if (this_1.noiseTexture) {
  61667. if (particle._randomNoiseCoordinates1) {
  61668. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  61669. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  61670. }
  61671. else {
  61672. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  61673. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  61674. }
  61675. }
  61676. // Update the position of the attached sub-emitters to match their attached particle
  61677. particle._inheritParticleInfoToSubEmitters();
  61678. };
  61679. var this_1 = this, step;
  61680. for (var index = 0; index < newParticles; index++) {
  61681. var state_1 = _loop_2();
  61682. if (state_1 === "break")
  61683. break;
  61684. }
  61685. };
  61686. /** @hidden */
  61687. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  61688. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  61689. if (isBillboardBased === void 0) { isBillboardBased = false; }
  61690. if (useRampGradients === void 0) { useRampGradients = false; }
  61691. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  61692. if (isAnimationSheetEnabled) {
  61693. attributeNamesOrOptions.push("cellIndex");
  61694. }
  61695. if (!isBillboardBased) {
  61696. attributeNamesOrOptions.push("direction");
  61697. }
  61698. if (useRampGradients) {
  61699. attributeNamesOrOptions.push("remapData");
  61700. }
  61701. return attributeNamesOrOptions;
  61702. };
  61703. /** @hidden */
  61704. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  61705. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  61706. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  61707. if (isAnimationSheetEnabled) {
  61708. effectCreationOption.push("particlesInfos");
  61709. }
  61710. return effectCreationOption;
  61711. };
  61712. /** @hidden */
  61713. ParticleSystem.prototype._getEffect = function (blendMode) {
  61714. if (this._customEffect) {
  61715. return this._customEffect;
  61716. }
  61717. var defines = [];
  61718. if (this._scene.clipPlane) {
  61719. defines.push("#define CLIPPLANE");
  61720. }
  61721. if (this._scene.clipPlane2) {
  61722. defines.push("#define CLIPPLANE2");
  61723. }
  61724. if (this._scene.clipPlane3) {
  61725. defines.push("#define CLIPPLANE3");
  61726. }
  61727. if (this._scene.clipPlane4) {
  61728. defines.push("#define CLIPPLANE4");
  61729. }
  61730. if (this._isAnimationSheetEnabled) {
  61731. defines.push("#define ANIMATESHEET");
  61732. }
  61733. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  61734. defines.push("#define BLENDMULTIPLYMODE");
  61735. }
  61736. if (this._useRampGradients) {
  61737. defines.push("#define RAMPGRADIENT");
  61738. }
  61739. if (this._isBillboardBased) {
  61740. defines.push("#define BILLBOARD");
  61741. switch (this.billboardMode) {
  61742. case ParticleSystem.BILLBOARDMODE_Y:
  61743. defines.push("#define BILLBOARDY");
  61744. break;
  61745. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  61746. defines.push("#define BILLBOARDSTRETCHED");
  61747. break;
  61748. case ParticleSystem.BILLBOARDMODE_ALL:
  61749. default:
  61750. break;
  61751. }
  61752. }
  61753. if (this._imageProcessingConfiguration) {
  61754. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  61755. defines.push(this._imageProcessingConfigurationDefines.toString());
  61756. }
  61757. // Effect
  61758. var join = defines.join("\n");
  61759. if (this._cachedDefines !== join) {
  61760. this._cachedDefines = join;
  61761. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  61762. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  61763. var samplers = ["diffuseSampler", "rampSampler"];
  61764. if (BABYLON.ImageProcessingConfiguration) {
  61765. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  61766. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  61767. }
  61768. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  61769. }
  61770. return this._effect;
  61771. };
  61772. /**
  61773. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  61774. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  61775. */
  61776. ParticleSystem.prototype.animate = function (preWarmOnly) {
  61777. var _this = this;
  61778. if (preWarmOnly === void 0) { preWarmOnly = false; }
  61779. if (!this._started) {
  61780. return;
  61781. }
  61782. if (!preWarmOnly) {
  61783. // Check
  61784. if (!this.isReady()) {
  61785. return;
  61786. }
  61787. if (this._currentRenderId === this._scene.getFrameId()) {
  61788. return;
  61789. }
  61790. this._currentRenderId = this._scene.getFrameId();
  61791. }
  61792. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  61793. // Determine the number of particles we need to create
  61794. var newParticles;
  61795. if (this.manualEmitCount > -1) {
  61796. newParticles = this.manualEmitCount;
  61797. this._newPartsExcess = 0;
  61798. this.manualEmitCount = 0;
  61799. }
  61800. else {
  61801. var rate_1 = this.emitRate;
  61802. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  61803. var ratio = this._actualFrame / this.targetStopDuration;
  61804. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  61805. if (currentGradient !== _this._currentEmitRateGradient) {
  61806. _this._currentEmitRate1 = _this._currentEmitRate2;
  61807. _this._currentEmitRate2 = nextGradient.getFactor();
  61808. _this._currentEmitRateGradient = currentGradient;
  61809. }
  61810. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  61811. });
  61812. }
  61813. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  61814. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  61815. }
  61816. if (this._newPartsExcess > 1.0) {
  61817. newParticles += this._newPartsExcess >> 0;
  61818. this._newPartsExcess -= this._newPartsExcess >> 0;
  61819. }
  61820. this._alive = false;
  61821. if (!this._stopped) {
  61822. this._actualFrame += this._scaledUpdateSpeed;
  61823. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  61824. this.stop();
  61825. }
  61826. }
  61827. else {
  61828. newParticles = 0;
  61829. }
  61830. this._update(newParticles);
  61831. // Stopped?
  61832. if (this._stopped) {
  61833. if (!this._alive) {
  61834. this._started = false;
  61835. if (this.onAnimationEnd) {
  61836. this.onAnimationEnd();
  61837. }
  61838. if (this.disposeOnStop) {
  61839. this._scene._toBeDisposed.push(this);
  61840. }
  61841. }
  61842. }
  61843. if (!preWarmOnly) {
  61844. // Update VBO
  61845. var offset = 0;
  61846. for (var index = 0; index < this._particles.length; index++) {
  61847. var particle = this._particles[index];
  61848. this._appendParticleVertices(offset, particle);
  61849. offset += this._useInstancing ? 1 : 4;
  61850. }
  61851. if (this._vertexBuffer) {
  61852. this._vertexBuffer.update(this._vertexData);
  61853. }
  61854. }
  61855. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  61856. this.stop();
  61857. }
  61858. };
  61859. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  61860. this._appendParticleVertex(offset++, particle, 0, 0);
  61861. if (!this._useInstancing) {
  61862. this._appendParticleVertex(offset++, particle, 1, 0);
  61863. this._appendParticleVertex(offset++, particle, 1, 1);
  61864. this._appendParticleVertex(offset++, particle, 0, 1);
  61865. }
  61866. };
  61867. /**
  61868. * Rebuilds the particle system.
  61869. */
  61870. ParticleSystem.prototype.rebuild = function () {
  61871. this._createIndexBuffer();
  61872. if (this._vertexBuffer) {
  61873. this._vertexBuffer._rebuild();
  61874. }
  61875. };
  61876. /**
  61877. * Is this system ready to be used/rendered
  61878. * @return true if the system is ready
  61879. */
  61880. ParticleSystem.prototype.isReady = function () {
  61881. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  61882. return false;
  61883. }
  61884. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  61885. if (!this._getEffect(this.blendMode).isReady()) {
  61886. return false;
  61887. }
  61888. }
  61889. else {
  61890. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  61891. return false;
  61892. }
  61893. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  61894. return false;
  61895. }
  61896. }
  61897. return true;
  61898. };
  61899. ParticleSystem.prototype._render = function (blendMode) {
  61900. var effect = this._getEffect(blendMode);
  61901. var engine = this._scene.getEngine();
  61902. // Render
  61903. engine.enableEffect(effect);
  61904. var viewMatrix = this._scene.getViewMatrix();
  61905. effect.setTexture("diffuseSampler", this.particleTexture);
  61906. effect.setMatrix("view", viewMatrix);
  61907. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  61908. if (this._isAnimationSheetEnabled && this.particleTexture) {
  61909. var baseSize = this.particleTexture.getBaseSize();
  61910. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  61911. }
  61912. effect.setVector2("translationPivot", this.translationPivot);
  61913. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  61914. if (this._isBillboardBased) {
  61915. var camera = this._scene.activeCamera;
  61916. effect.setVector3("eyePosition", camera.globalPosition);
  61917. }
  61918. if (this._rampGradientsTexture) {
  61919. effect.setTexture("rampSampler", this._rampGradientsTexture);
  61920. }
  61921. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  61922. var invView = viewMatrix.clone();
  61923. invView.invert();
  61924. effect.setMatrix("invView", invView);
  61925. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  61926. }
  61927. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  61928. // image processing
  61929. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  61930. this._imageProcessingConfiguration.bind(effect);
  61931. }
  61932. // Draw order
  61933. switch (blendMode) {
  61934. case ParticleSystem.BLENDMODE_ADD:
  61935. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  61936. break;
  61937. case ParticleSystem.BLENDMODE_ONEONE:
  61938. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  61939. break;
  61940. case ParticleSystem.BLENDMODE_STANDARD:
  61941. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  61942. break;
  61943. case ParticleSystem.BLENDMODE_MULTIPLY:
  61944. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  61945. break;
  61946. }
  61947. if (this._useInstancing) {
  61948. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  61949. }
  61950. else {
  61951. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  61952. }
  61953. return this._particles.length;
  61954. };
  61955. /**
  61956. * Renders the particle system in its current state.
  61957. * @returns the current number of particles
  61958. */
  61959. ParticleSystem.prototype.render = function () {
  61960. // Check
  61961. if (!this.isReady() || !this._particles.length) {
  61962. return 0;
  61963. }
  61964. var engine = this._scene.getEngine();
  61965. engine.setState(false);
  61966. if (this.forceDepthWrite) {
  61967. engine.setDepthWrite(true);
  61968. }
  61969. var outparticles = 0;
  61970. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  61971. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  61972. }
  61973. outparticles = this._render(this.blendMode);
  61974. engine.unbindInstanceAttributes();
  61975. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  61976. return outparticles;
  61977. };
  61978. /**
  61979. * Disposes the particle system and free the associated resources
  61980. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  61981. */
  61982. ParticleSystem.prototype.dispose = function (disposeTexture) {
  61983. if (disposeTexture === void 0) { disposeTexture = true; }
  61984. if (this._vertexBuffer) {
  61985. this._vertexBuffer.dispose();
  61986. this._vertexBuffer = null;
  61987. }
  61988. if (this._spriteBuffer) {
  61989. this._spriteBuffer.dispose();
  61990. this._spriteBuffer = null;
  61991. }
  61992. if (this._indexBuffer) {
  61993. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  61994. this._indexBuffer = null;
  61995. }
  61996. if (disposeTexture && this.particleTexture) {
  61997. this.particleTexture.dispose();
  61998. this.particleTexture = null;
  61999. }
  62000. if (disposeTexture && this.noiseTexture) {
  62001. this.noiseTexture.dispose();
  62002. this.noiseTexture = null;
  62003. }
  62004. if (this._rampGradientsTexture) {
  62005. this._rampGradientsTexture.dispose();
  62006. this._rampGradientsTexture = null;
  62007. }
  62008. this._removeFromRoot();
  62009. if (this._subEmitters && this._subEmitters.length) {
  62010. for (var index = 0; index < this._subEmitters.length; index++) {
  62011. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  62012. var subEmitter = _a[_i];
  62013. subEmitter.dispose();
  62014. }
  62015. }
  62016. this._subEmitters = [];
  62017. this.subEmitters = [];
  62018. }
  62019. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  62020. this.emitter.dispose(true);
  62021. }
  62022. // Remove from scene
  62023. var index = this._scene.particleSystems.indexOf(this);
  62024. if (index > -1) {
  62025. this._scene.particleSystems.splice(index, 1);
  62026. }
  62027. this._scene._activeParticleSystems.dispose();
  62028. // Callback
  62029. this.onDisposeObservable.notifyObservers(this);
  62030. this.onDisposeObservable.clear();
  62031. this.reset();
  62032. };
  62033. // Clone
  62034. /**
  62035. * Clones the particle system.
  62036. * @param name The name of the cloned object
  62037. * @param newEmitter The new emitter to use
  62038. * @returns the cloned particle system
  62039. */
  62040. ParticleSystem.prototype.clone = function (name, newEmitter) {
  62041. var custom = null;
  62042. var program = null;
  62043. if (this.customShader != null) {
  62044. program = this.customShader;
  62045. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  62046. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  62047. }
  62048. else if (this._customEffect) {
  62049. custom = this._customEffect;
  62050. }
  62051. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  62052. result.customShader = program;
  62053. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  62054. if (newEmitter === undefined) {
  62055. newEmitter = this.emitter;
  62056. }
  62057. result.noiseTexture = this.noiseTexture;
  62058. result.emitter = newEmitter;
  62059. if (this.particleTexture) {
  62060. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  62061. }
  62062. // Clone gradients
  62063. if (this._colorGradients) {
  62064. this._colorGradients.forEach(function (v) {
  62065. result.addColorGradient(v.gradient, v.color1, v.color2);
  62066. });
  62067. }
  62068. if (this._dragGradients) {
  62069. this._dragGradients.forEach(function (v) {
  62070. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  62071. });
  62072. }
  62073. if (this._angularSpeedGradients) {
  62074. this._angularSpeedGradients.forEach(function (v) {
  62075. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  62076. });
  62077. }
  62078. if (this._emitRateGradients) {
  62079. this._emitRateGradients.forEach(function (v) {
  62080. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  62081. });
  62082. }
  62083. if (this._lifeTimeGradients) {
  62084. this._lifeTimeGradients.forEach(function (v) {
  62085. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  62086. });
  62087. }
  62088. if (this._limitVelocityGradients) {
  62089. this._limitVelocityGradients.forEach(function (v) {
  62090. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  62091. });
  62092. }
  62093. if (this._sizeGradients) {
  62094. this._sizeGradients.forEach(function (v) {
  62095. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  62096. });
  62097. }
  62098. if (this._startSizeGradients) {
  62099. this._startSizeGradients.forEach(function (v) {
  62100. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  62101. });
  62102. }
  62103. if (this._velocityGradients) {
  62104. this._velocityGradients.forEach(function (v) {
  62105. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  62106. });
  62107. }
  62108. if (this._rampGradients) {
  62109. this._rampGradients.forEach(function (v) {
  62110. result.addRampGradient(v.gradient, v.color);
  62111. });
  62112. }
  62113. if (this._colorRemapGradients) {
  62114. this._colorRemapGradients.forEach(function (v) {
  62115. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  62116. });
  62117. }
  62118. if (this._alphaRemapGradients) {
  62119. this._alphaRemapGradients.forEach(function (v) {
  62120. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  62121. });
  62122. }
  62123. if (!this.preventAutoStart) {
  62124. result.start();
  62125. }
  62126. return result;
  62127. };
  62128. /**
  62129. * Serializes the particle system to a JSON object.
  62130. * @returns the JSON object
  62131. */
  62132. ParticleSystem.prototype.serialize = function () {
  62133. var serializationObject = {};
  62134. ParticleSystem._Serialize(serializationObject, this);
  62135. serializationObject.textureMask = this.textureMask.asArray();
  62136. serializationObject.customShader = this.customShader;
  62137. serializationObject.preventAutoStart = this.preventAutoStart;
  62138. // SubEmitters
  62139. if (this.subEmitters) {
  62140. serializationObject.subEmitters = [];
  62141. if (!this._subEmitters) {
  62142. this._prepareSubEmitterInternalArray();
  62143. }
  62144. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  62145. var subs = _a[_i];
  62146. var cell = [];
  62147. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  62148. var sub = subs_1[_b];
  62149. cell.push(sub.serialize());
  62150. }
  62151. serializationObject.subEmitters.push(cell);
  62152. }
  62153. }
  62154. return serializationObject;
  62155. };
  62156. /** @hidden */
  62157. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  62158. serializationObject.name = particleSystem.name;
  62159. serializationObject.id = particleSystem.id;
  62160. serializationObject.capacity = particleSystem.getCapacity();
  62161. // Emitter
  62162. if (particleSystem.emitter.position) {
  62163. var emitterMesh = particleSystem.emitter;
  62164. serializationObject.emitterId = emitterMesh.id;
  62165. }
  62166. else {
  62167. var emitterPosition = particleSystem.emitter;
  62168. serializationObject.emitter = emitterPosition.asArray();
  62169. }
  62170. // Emitter
  62171. if (particleSystem.particleEmitterType) {
  62172. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  62173. }
  62174. if (particleSystem.particleTexture) {
  62175. serializationObject.textureName = particleSystem.particleTexture.name;
  62176. serializationObject.invertY = particleSystem.particleTexture._invertY;
  62177. }
  62178. // Animations
  62179. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  62180. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  62181. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  62182. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  62183. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  62184. // Particle system
  62185. serializationObject.startDelay = particleSystem.startDelay;
  62186. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  62187. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  62188. serializationObject.billboardMode = particleSystem.billboardMode;
  62189. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  62190. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  62191. serializationObject.minSize = particleSystem.minSize;
  62192. serializationObject.maxSize = particleSystem.maxSize;
  62193. serializationObject.minScaleX = particleSystem.minScaleX;
  62194. serializationObject.maxScaleX = particleSystem.maxScaleX;
  62195. serializationObject.minScaleY = particleSystem.minScaleY;
  62196. serializationObject.maxScaleY = particleSystem.maxScaleY;
  62197. serializationObject.minEmitPower = particleSystem.minEmitPower;
  62198. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  62199. serializationObject.minLifeTime = particleSystem.minLifeTime;
  62200. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  62201. serializationObject.emitRate = particleSystem.emitRate;
  62202. serializationObject.gravity = particleSystem.gravity.asArray();
  62203. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  62204. serializationObject.color1 = particleSystem.color1.asArray();
  62205. serializationObject.color2 = particleSystem.color2.asArray();
  62206. serializationObject.colorDead = particleSystem.colorDead.asArray();
  62207. serializationObject.updateSpeed = particleSystem.updateSpeed;
  62208. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  62209. serializationObject.blendMode = particleSystem.blendMode;
  62210. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  62211. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  62212. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  62213. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  62214. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  62215. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  62216. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  62217. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  62218. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  62219. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  62220. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  62221. var colorGradients = particleSystem.getColorGradients();
  62222. if (colorGradients) {
  62223. serializationObject.colorGradients = [];
  62224. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  62225. var colorGradient = colorGradients_1[_i];
  62226. var serializedGradient = {
  62227. gradient: colorGradient.gradient,
  62228. color1: colorGradient.color1.asArray()
  62229. };
  62230. if (colorGradient.color2) {
  62231. serializedGradient.color2 = colorGradient.color2.asArray();
  62232. }
  62233. serializationObject.colorGradients.push(serializedGradient);
  62234. }
  62235. }
  62236. var rampGradients = particleSystem.getRampGradients();
  62237. if (rampGradients) {
  62238. serializationObject.rampGradients = [];
  62239. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  62240. var rampGradient = rampGradients_1[_a];
  62241. var serializedGradient = {
  62242. gradient: rampGradient.gradient,
  62243. color: rampGradient.color.asArray()
  62244. };
  62245. serializationObject.rampGradients.push(serializedGradient);
  62246. }
  62247. serializationObject.useRampGradients = particleSystem.useRampGradients;
  62248. }
  62249. var colorRemapGradients = particleSystem.getColorRemapGradients();
  62250. if (colorRemapGradients) {
  62251. serializationObject.colorRemapGradients = [];
  62252. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  62253. var colorRemapGradient = colorRemapGradients_1[_b];
  62254. var serializedGradient = {
  62255. gradient: colorRemapGradient.gradient,
  62256. factor1: colorRemapGradient.factor1
  62257. };
  62258. if (colorRemapGradient.factor2 !== undefined) {
  62259. serializedGradient.factor2 = colorRemapGradient.factor2;
  62260. }
  62261. serializationObject.colorRemapGradients.push(serializedGradient);
  62262. }
  62263. }
  62264. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  62265. if (alphaRemapGradients) {
  62266. serializationObject.alphaRemapGradients = [];
  62267. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  62268. var alphaRemapGradient = alphaRemapGradients_1[_c];
  62269. var serializedGradient = {
  62270. gradient: alphaRemapGradient.gradient,
  62271. factor1: alphaRemapGradient.factor1
  62272. };
  62273. if (alphaRemapGradient.factor2 !== undefined) {
  62274. serializedGradient.factor2 = alphaRemapGradient.factor2;
  62275. }
  62276. serializationObject.alphaRemapGradients.push(serializedGradient);
  62277. }
  62278. }
  62279. var sizeGradients = particleSystem.getSizeGradients();
  62280. if (sizeGradients) {
  62281. serializationObject.sizeGradients = [];
  62282. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  62283. var sizeGradient = sizeGradients_1[_d];
  62284. var serializedGradient = {
  62285. gradient: sizeGradient.gradient,
  62286. factor1: sizeGradient.factor1
  62287. };
  62288. if (sizeGradient.factor2 !== undefined) {
  62289. serializedGradient.factor2 = sizeGradient.factor2;
  62290. }
  62291. serializationObject.sizeGradients.push(serializedGradient);
  62292. }
  62293. }
  62294. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  62295. if (angularSpeedGradients) {
  62296. serializationObject.angularSpeedGradients = [];
  62297. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  62298. var angularSpeedGradient = angularSpeedGradients_1[_e];
  62299. var serializedGradient = {
  62300. gradient: angularSpeedGradient.gradient,
  62301. factor1: angularSpeedGradient.factor1
  62302. };
  62303. if (angularSpeedGradient.factor2 !== undefined) {
  62304. serializedGradient.factor2 = angularSpeedGradient.factor2;
  62305. }
  62306. serializationObject.angularSpeedGradients.push(serializedGradient);
  62307. }
  62308. }
  62309. var velocityGradients = particleSystem.getVelocityGradients();
  62310. if (velocityGradients) {
  62311. serializationObject.velocityGradients = [];
  62312. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  62313. var velocityGradient = velocityGradients_1[_f];
  62314. var serializedGradient = {
  62315. gradient: velocityGradient.gradient,
  62316. factor1: velocityGradient.factor1
  62317. };
  62318. if (velocityGradient.factor2 !== undefined) {
  62319. serializedGradient.factor2 = velocityGradient.factor2;
  62320. }
  62321. serializationObject.velocityGradients.push(serializedGradient);
  62322. }
  62323. }
  62324. var dragGradients = particleSystem.getDragGradients();
  62325. if (dragGradients) {
  62326. serializationObject.dragyGradients = [];
  62327. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  62328. var dragGradient = dragGradients_1[_g];
  62329. var serializedGradient = {
  62330. gradient: dragGradient.gradient,
  62331. factor1: dragGradient.factor1
  62332. };
  62333. if (dragGradient.factor2 !== undefined) {
  62334. serializedGradient.factor2 = dragGradient.factor2;
  62335. }
  62336. serializationObject.dragGradients.push(serializedGradient);
  62337. }
  62338. }
  62339. var emitRateGradients = particleSystem.getEmitRateGradients();
  62340. if (emitRateGradients) {
  62341. serializationObject.emitRateGradients = [];
  62342. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  62343. var emitRateGradient = emitRateGradients_1[_h];
  62344. var serializedGradient = {
  62345. gradient: emitRateGradient.gradient,
  62346. factor1: emitRateGradient.factor1
  62347. };
  62348. if (emitRateGradient.factor2 !== undefined) {
  62349. serializedGradient.factor2 = emitRateGradient.factor2;
  62350. }
  62351. serializationObject.emitRateGradients.push(serializedGradient);
  62352. }
  62353. }
  62354. var startSizeGradients = particleSystem.getStartSizeGradients();
  62355. if (startSizeGradients) {
  62356. serializationObject.startSizeGradients = [];
  62357. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  62358. var startSizeGradient = startSizeGradients_1[_j];
  62359. var serializedGradient = {
  62360. gradient: startSizeGradient.gradient,
  62361. factor1: startSizeGradient.factor1
  62362. };
  62363. if (startSizeGradient.factor2 !== undefined) {
  62364. serializedGradient.factor2 = startSizeGradient.factor2;
  62365. }
  62366. serializationObject.startSizeGradients.push(serializedGradient);
  62367. }
  62368. }
  62369. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  62370. if (lifeTimeGradients) {
  62371. serializationObject.lifeTimeGradients = [];
  62372. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  62373. var lifeTimeGradient = lifeTimeGradients_1[_k];
  62374. var serializedGradient = {
  62375. gradient: lifeTimeGradient.gradient,
  62376. factor1: lifeTimeGradient.factor1
  62377. };
  62378. if (lifeTimeGradient.factor2 !== undefined) {
  62379. serializedGradient.factor2 = lifeTimeGradient.factor2;
  62380. }
  62381. serializationObject.lifeTimeGradients.push(serializedGradient);
  62382. }
  62383. }
  62384. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  62385. if (limitVelocityGradients) {
  62386. serializationObject.limitVelocityGradients = [];
  62387. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  62388. var limitVelocityGradient = limitVelocityGradients_1[_l];
  62389. var serializedGradient = {
  62390. gradient: limitVelocityGradient.gradient,
  62391. factor1: limitVelocityGradient.factor1
  62392. };
  62393. if (limitVelocityGradient.factor2 !== undefined) {
  62394. serializedGradient.factor2 = limitVelocityGradient.factor2;
  62395. }
  62396. serializationObject.limitVelocityGradients.push(serializedGradient);
  62397. }
  62398. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  62399. }
  62400. if (particleSystem.noiseTexture) {
  62401. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  62402. }
  62403. };
  62404. /** @hidden */
  62405. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  62406. // Texture
  62407. if (parsedParticleSystem.textureName) {
  62408. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  62409. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  62410. }
  62411. // Emitter
  62412. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  62413. particleSystem.emitter = BABYLON.Vector3.Zero();
  62414. }
  62415. else if (parsedParticleSystem.emitterId) {
  62416. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  62417. }
  62418. else {
  62419. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  62420. }
  62421. // Misc.
  62422. if (parsedParticleSystem.renderingGroupId !== undefined) {
  62423. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  62424. }
  62425. if (parsedParticleSystem.isBillboardBased !== undefined) {
  62426. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  62427. }
  62428. if (parsedParticleSystem.billboardMode !== undefined) {
  62429. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  62430. }
  62431. // Animations
  62432. if (parsedParticleSystem.animations) {
  62433. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  62434. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  62435. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  62436. }
  62437. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  62438. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  62439. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  62440. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  62441. }
  62442. if (parsedParticleSystem.autoAnimate) {
  62443. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  62444. }
  62445. // Particle system
  62446. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  62447. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  62448. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  62449. particleSystem.minSize = parsedParticleSystem.minSize;
  62450. particleSystem.maxSize = parsedParticleSystem.maxSize;
  62451. if (parsedParticleSystem.minScaleX) {
  62452. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  62453. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  62454. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  62455. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  62456. }
  62457. if (parsedParticleSystem.preWarmCycles !== undefined) {
  62458. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  62459. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  62460. }
  62461. if (parsedParticleSystem.minInitialRotation !== undefined) {
  62462. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  62463. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  62464. }
  62465. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  62466. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  62467. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  62468. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  62469. particleSystem.emitRate = parsedParticleSystem.emitRate;
  62470. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  62471. if (parsedParticleSystem.noiseStrength) {
  62472. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  62473. }
  62474. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  62475. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  62476. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  62477. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  62478. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  62479. particleSystem.blendMode = parsedParticleSystem.blendMode;
  62480. if (parsedParticleSystem.colorGradients) {
  62481. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  62482. var colorGradient = _a[_i];
  62483. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  62484. }
  62485. }
  62486. if (parsedParticleSystem.rampGradients) {
  62487. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  62488. var rampGradient = _c[_b];
  62489. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  62490. }
  62491. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  62492. }
  62493. if (parsedParticleSystem.colorRemapGradients) {
  62494. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  62495. var colorRemapGradient = _e[_d];
  62496. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  62497. }
  62498. }
  62499. if (parsedParticleSystem.alphaRemapGradients) {
  62500. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  62501. var alphaRemapGradient = _g[_f];
  62502. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  62503. }
  62504. }
  62505. if (parsedParticleSystem.sizeGradients) {
  62506. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  62507. var sizeGradient = _j[_h];
  62508. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  62509. }
  62510. }
  62511. if (parsedParticleSystem.sizeGradients) {
  62512. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  62513. var sizeGradient = _l[_k];
  62514. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  62515. }
  62516. }
  62517. if (parsedParticleSystem.angularSpeedGradients) {
  62518. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  62519. var angularSpeedGradient = _o[_m];
  62520. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  62521. }
  62522. }
  62523. if (parsedParticleSystem.velocityGradients) {
  62524. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  62525. var velocityGradient = _q[_p];
  62526. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  62527. }
  62528. }
  62529. if (parsedParticleSystem.dragGradients) {
  62530. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  62531. var dragGradient = _s[_r];
  62532. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  62533. }
  62534. }
  62535. if (parsedParticleSystem.emitRateGradients) {
  62536. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  62537. var emitRateGradient = _u[_t];
  62538. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  62539. }
  62540. }
  62541. if (parsedParticleSystem.startSizeGradients) {
  62542. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  62543. var startSizeGradient = _w[_v];
  62544. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  62545. }
  62546. }
  62547. if (parsedParticleSystem.lifeTimeGradients) {
  62548. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  62549. var lifeTimeGradient = _y[_x];
  62550. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  62551. }
  62552. }
  62553. if (parsedParticleSystem.limitVelocityGradients) {
  62554. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  62555. var limitVelocityGradient = _0[_z];
  62556. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  62557. }
  62558. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  62559. }
  62560. if (parsedParticleSystem.noiseTexture) {
  62561. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  62562. }
  62563. // Emitter
  62564. var emitterType;
  62565. if (parsedParticleSystem.particleEmitterType) {
  62566. switch (parsedParticleSystem.particleEmitterType.type) {
  62567. case "SphereParticleEmitter":
  62568. emitterType = new BABYLON.SphereParticleEmitter();
  62569. break;
  62570. case "SphereDirectedParticleEmitter":
  62571. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  62572. break;
  62573. case "ConeEmitter":
  62574. case "ConeParticleEmitter":
  62575. emitterType = new BABYLON.ConeParticleEmitter();
  62576. break;
  62577. case "CylinderParticleEmitter":
  62578. emitterType = new BABYLON.CylinderParticleEmitter();
  62579. break;
  62580. case "HemisphericParticleEmitter":
  62581. emitterType = new BABYLON.HemisphericParticleEmitter();
  62582. break;
  62583. case "BoxEmitter":
  62584. case "BoxParticleEmitter":
  62585. default:
  62586. emitterType = new BABYLON.BoxParticleEmitter();
  62587. break;
  62588. }
  62589. emitterType.parse(parsedParticleSystem.particleEmitterType);
  62590. }
  62591. else {
  62592. emitterType = new BABYLON.BoxParticleEmitter();
  62593. emitterType.parse(parsedParticleSystem);
  62594. }
  62595. particleSystem.particleEmitterType = emitterType;
  62596. // Animation sheet
  62597. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  62598. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  62599. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  62600. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  62601. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  62602. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  62603. };
  62604. /**
  62605. * Parses a JSON object to create a particle system.
  62606. * @param parsedParticleSystem The JSON object to parse
  62607. * @param scene The scene to create the particle system in
  62608. * @param rootUrl The root url to use to load external dependencies like texture
  62609. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  62610. * @returns the Parsed particle system
  62611. */
  62612. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  62613. if (doNotStart === void 0) { doNotStart = false; }
  62614. var name = parsedParticleSystem.name;
  62615. var custom = null;
  62616. var program = null;
  62617. if (parsedParticleSystem.customShader) {
  62618. program = parsedParticleSystem.customShader;
  62619. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  62620. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  62621. }
  62622. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  62623. particleSystem.customShader = program;
  62624. if (parsedParticleSystem.id) {
  62625. particleSystem.id = parsedParticleSystem.id;
  62626. }
  62627. // SubEmitters
  62628. if (parsedParticleSystem.subEmitters) {
  62629. particleSystem.subEmitters = [];
  62630. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  62631. var cell = _a[_i];
  62632. var cellArray = [];
  62633. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  62634. var sub = cell_1[_b];
  62635. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  62636. }
  62637. particleSystem.subEmitters.push(cellArray);
  62638. }
  62639. }
  62640. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  62641. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  62642. // Auto start
  62643. if (parsedParticleSystem.preventAutoStart) {
  62644. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  62645. }
  62646. if (!doNotStart && !particleSystem.preventAutoStart) {
  62647. particleSystem.start();
  62648. }
  62649. return particleSystem;
  62650. };
  62651. /**
  62652. * Billboard mode will only apply to Y axis
  62653. */
  62654. ParticleSystem.BILLBOARDMODE_Y = 2;
  62655. /**
  62656. * Billboard mode will apply to all axes
  62657. */
  62658. ParticleSystem.BILLBOARDMODE_ALL = 7;
  62659. /**
  62660. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  62661. */
  62662. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  62663. return ParticleSystem;
  62664. }(BABYLON.BaseParticleSystem));
  62665. BABYLON.ParticleSystem = ParticleSystem;
  62666. })(BABYLON || (BABYLON = {}));
  62667. //# sourceMappingURL=particleSystem.js.map
  62668. var BABYLON;
  62669. (function (BABYLON) {
  62670. /**
  62671. * Particle emitter emitting particles from the inside of a box.
  62672. * It emits the particles randomly between 2 given directions.
  62673. */
  62674. var BoxParticleEmitter = /** @class */ (function () {
  62675. /**
  62676. * Creates a new instance BoxParticleEmitter
  62677. */
  62678. function BoxParticleEmitter() {
  62679. /**
  62680. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  62681. */
  62682. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  62683. /**
  62684. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  62685. */
  62686. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  62687. /**
  62688. * 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.
  62689. */
  62690. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  62691. /**
  62692. * 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.
  62693. */
  62694. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  62695. }
  62696. /**
  62697. * Called by the particle System when the direction is computed for the created particle.
  62698. * @param worldMatrix is the world matrix of the particle system
  62699. * @param directionToUpdate is the direction vector to update with the result
  62700. * @param particle is the particle we are computed the direction for
  62701. */
  62702. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62703. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  62704. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  62705. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  62706. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  62707. };
  62708. /**
  62709. * Called by the particle System when the position is computed for the created particle.
  62710. * @param worldMatrix is the world matrix of the particle system
  62711. * @param positionToUpdate is the position vector to update with the result
  62712. * @param particle is the particle we are computed the position for
  62713. */
  62714. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  62715. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  62716. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  62717. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  62718. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  62719. };
  62720. /**
  62721. * Clones the current emitter and returns a copy of it
  62722. * @returns the new emitter
  62723. */
  62724. BoxParticleEmitter.prototype.clone = function () {
  62725. var newOne = new BoxParticleEmitter();
  62726. BABYLON.Tools.DeepCopy(this, newOne);
  62727. return newOne;
  62728. };
  62729. /**
  62730. * Called by the GPUParticleSystem to setup the update shader
  62731. * @param effect defines the update shader
  62732. */
  62733. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  62734. effect.setVector3("direction1", this.direction1);
  62735. effect.setVector3("direction2", this.direction2);
  62736. effect.setVector3("minEmitBox", this.minEmitBox);
  62737. effect.setVector3("maxEmitBox", this.maxEmitBox);
  62738. };
  62739. /**
  62740. * Returns a string to use to update the GPU particles update shader
  62741. * @returns a string containng the defines string
  62742. */
  62743. BoxParticleEmitter.prototype.getEffectDefines = function () {
  62744. return "#define BOXEMITTER";
  62745. };
  62746. /**
  62747. * Returns the string "BoxParticleEmitter"
  62748. * @returns a string containing the class name
  62749. */
  62750. BoxParticleEmitter.prototype.getClassName = function () {
  62751. return "BoxParticleEmitter";
  62752. };
  62753. /**
  62754. * Serializes the particle system to a JSON object.
  62755. * @returns the JSON object
  62756. */
  62757. BoxParticleEmitter.prototype.serialize = function () {
  62758. var serializationObject = {};
  62759. serializationObject.type = this.getClassName();
  62760. serializationObject.direction1 = this.direction1.asArray();
  62761. serializationObject.direction2 = this.direction2.asArray();
  62762. serializationObject.minEmitBox = this.minEmitBox.asArray();
  62763. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  62764. return serializationObject;
  62765. };
  62766. /**
  62767. * Parse properties from a JSON object
  62768. * @param serializationObject defines the JSON object
  62769. */
  62770. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  62771. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  62772. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  62773. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  62774. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  62775. };
  62776. return BoxParticleEmitter;
  62777. }());
  62778. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  62779. })(BABYLON || (BABYLON = {}));
  62780. //# sourceMappingURL=boxParticleEmitter.js.map
  62781. var BABYLON;
  62782. (function (BABYLON) {
  62783. /**
  62784. * Particle emitter emitting particles from the inside of a cylinder.
  62785. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  62786. */
  62787. var CylinderParticleEmitter = /** @class */ (function () {
  62788. /**
  62789. * Creates a new instance CylinderParticleEmitter
  62790. * @param radius the radius of the emission cylinder (1 by default)
  62791. * @param height the height of the emission cylinder (1 by default)
  62792. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  62793. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  62794. */
  62795. function CylinderParticleEmitter(
  62796. /**
  62797. * The radius of the emission cylinder.
  62798. */
  62799. radius,
  62800. /**
  62801. * The height of the emission cylinder.
  62802. */
  62803. height,
  62804. /**
  62805. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  62806. */
  62807. radiusRange,
  62808. /**
  62809. * How much to randomize the particle direction [0-1].
  62810. */
  62811. directionRandomizer) {
  62812. if (radius === void 0) { radius = 1; }
  62813. if (height === void 0) { height = 1; }
  62814. if (radiusRange === void 0) { radiusRange = 1; }
  62815. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  62816. this.radius = radius;
  62817. this.height = height;
  62818. this.radiusRange = radiusRange;
  62819. this.directionRandomizer = directionRandomizer;
  62820. }
  62821. /**
  62822. * Called by the particle System when the direction is computed for the created particle.
  62823. * @param worldMatrix is the world matrix of the particle system
  62824. * @param directionToUpdate is the direction vector to update with the result
  62825. * @param particle is the particle we are computed the direction for
  62826. */
  62827. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62828. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  62829. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  62830. var angle = Math.atan2(direction.x, direction.z);
  62831. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  62832. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  62833. direction.x = Math.sin(angle);
  62834. direction.z = Math.cos(angle);
  62835. direction.normalize();
  62836. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  62837. };
  62838. /**
  62839. * Called by the particle System when the position is computed for the created particle.
  62840. * @param worldMatrix is the world matrix of the particle system
  62841. * @param positionToUpdate is the position vector to update with the result
  62842. * @param particle is the particle we are computed the position for
  62843. */
  62844. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  62845. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  62846. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  62847. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  62848. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  62849. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  62850. var xPos = positionRadius * Math.cos(angle);
  62851. var zPos = positionRadius * Math.sin(angle);
  62852. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  62853. };
  62854. /**
  62855. * Clones the current emitter and returns a copy of it
  62856. * @returns the new emitter
  62857. */
  62858. CylinderParticleEmitter.prototype.clone = function () {
  62859. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  62860. BABYLON.Tools.DeepCopy(this, newOne);
  62861. return newOne;
  62862. };
  62863. /**
  62864. * Called by the GPUParticleSystem to setup the update shader
  62865. * @param effect defines the update shader
  62866. */
  62867. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  62868. effect.setFloat("radius", this.radius);
  62869. effect.setFloat("height", this.height);
  62870. effect.setFloat("radiusRange", this.radiusRange);
  62871. effect.setFloat("directionRandomizer", this.directionRandomizer);
  62872. };
  62873. /**
  62874. * Returns a string to use to update the GPU particles update shader
  62875. * @returns a string containng the defines string
  62876. */
  62877. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  62878. return "#define CYLINDEREMITTER";
  62879. };
  62880. /**
  62881. * Returns the string "CylinderParticleEmitter"
  62882. * @returns a string containing the class name
  62883. */
  62884. CylinderParticleEmitter.prototype.getClassName = function () {
  62885. return "CylinderParticleEmitter";
  62886. };
  62887. /**
  62888. * Serializes the particle system to a JSON object.
  62889. * @returns the JSON object
  62890. */
  62891. CylinderParticleEmitter.prototype.serialize = function () {
  62892. var serializationObject = {};
  62893. serializationObject.type = this.getClassName();
  62894. serializationObject.radius = this.radius;
  62895. serializationObject.height = this.height;
  62896. serializationObject.radiusRange = this.radiusRange;
  62897. serializationObject.directionRandomizer = this.directionRandomizer;
  62898. return serializationObject;
  62899. };
  62900. /**
  62901. * Parse properties from a JSON object
  62902. * @param serializationObject defines the JSON object
  62903. */
  62904. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  62905. this.radius = serializationObject.radius;
  62906. this.height = serializationObject.height;
  62907. this.radiusRange = serializationObject.radiusRange;
  62908. this.directionRandomizer = serializationObject.directionRandomizer;
  62909. };
  62910. return CylinderParticleEmitter;
  62911. }());
  62912. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  62913. /**
  62914. * Particle emitter emitting particles from the inside of a cylinder.
  62915. * It emits the particles randomly between two vectors.
  62916. */
  62917. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  62918. __extends(CylinderDirectedParticleEmitter, _super);
  62919. /**
  62920. * Creates a new instance CylinderDirectedParticleEmitter
  62921. * @param radius the radius of the emission cylinder (1 by default)
  62922. * @param height the height of the emission cylinder (1 by default)
  62923. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  62924. * @param direction1 the min limit of the emission direction (up vector by default)
  62925. * @param direction2 the max limit of the emission direction (up vector by default)
  62926. */
  62927. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  62928. /**
  62929. * The min limit of the emission direction.
  62930. */
  62931. direction1,
  62932. /**
  62933. * The max limit of the emission direction.
  62934. */
  62935. direction2) {
  62936. if (radius === void 0) { radius = 1; }
  62937. if (height === void 0) { height = 1; }
  62938. if (radiusRange === void 0) { radiusRange = 1; }
  62939. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  62940. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  62941. var _this = _super.call(this, radius, height, radiusRange) || this;
  62942. _this.direction1 = direction1;
  62943. _this.direction2 = direction2;
  62944. return _this;
  62945. }
  62946. /**
  62947. * Called by the particle System when the direction is computed for the created particle.
  62948. * @param worldMatrix is the world matrix of the particle system
  62949. * @param directionToUpdate is the direction vector to update with the result
  62950. * @param particle is the particle we are computed the direction for
  62951. */
  62952. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62953. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  62954. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  62955. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  62956. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  62957. };
  62958. /**
  62959. * Clones the current emitter and returns a copy of it
  62960. * @returns the new emitter
  62961. */
  62962. CylinderDirectedParticleEmitter.prototype.clone = function () {
  62963. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  62964. BABYLON.Tools.DeepCopy(this, newOne);
  62965. return newOne;
  62966. };
  62967. /**
  62968. * Called by the GPUParticleSystem to setup the update shader
  62969. * @param effect defines the update shader
  62970. */
  62971. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  62972. effect.setFloat("radius", this.radius);
  62973. effect.setFloat("height", this.height);
  62974. effect.setFloat("radiusRange", this.radiusRange);
  62975. effect.setVector3("direction1", this.direction1);
  62976. effect.setVector3("direction2", this.direction2);
  62977. };
  62978. /**
  62979. * Returns a string to use to update the GPU particles update shader
  62980. * @returns a string containng the defines string
  62981. */
  62982. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  62983. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  62984. };
  62985. /**
  62986. * Returns the string "CylinderDirectedParticleEmitter"
  62987. * @returns a string containing the class name
  62988. */
  62989. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  62990. return "CylinderDirectedParticleEmitter";
  62991. };
  62992. /**
  62993. * Serializes the particle system to a JSON object.
  62994. * @returns the JSON object
  62995. */
  62996. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  62997. var serializationObject = _super.prototype.serialize.call(this);
  62998. serializationObject.direction1 = this.direction1.asArray();
  62999. serializationObject.direction2 = this.direction2.asArray();
  63000. return serializationObject;
  63001. };
  63002. /**
  63003. * Parse properties from a JSON object
  63004. * @param serializationObject defines the JSON object
  63005. */
  63006. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  63007. _super.prototype.parse.call(this, serializationObject);
  63008. this.direction1.copyFrom(serializationObject.direction1);
  63009. this.direction2.copyFrom(serializationObject.direction2);
  63010. };
  63011. return CylinderDirectedParticleEmitter;
  63012. }(CylinderParticleEmitter));
  63013. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  63014. })(BABYLON || (BABYLON = {}));
  63015. //# sourceMappingURL=cylinderParticleEmitter.js.map
  63016. var BABYLON;
  63017. (function (BABYLON) {
  63018. /**
  63019. * Particle emitter emitting particles from the inside of a cone.
  63020. * It emits the particles alongside the cone volume from the base to the particle.
  63021. * The emission direction might be randomized.
  63022. */
  63023. var ConeParticleEmitter = /** @class */ (function () {
  63024. /**
  63025. * Creates a new instance ConeParticleEmitter
  63026. * @param radius the radius of the emission cone (1 by default)
  63027. * @param angles the cone base angle (PI by default)
  63028. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  63029. */
  63030. function ConeParticleEmitter(radius, angle,
  63031. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  63032. directionRandomizer) {
  63033. if (radius === void 0) { radius = 1; }
  63034. if (angle === void 0) { angle = Math.PI; }
  63035. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  63036. this.directionRandomizer = directionRandomizer;
  63037. /**
  63038. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  63039. */
  63040. this.radiusRange = 1;
  63041. /**
  63042. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  63043. */
  63044. this.heightRange = 1;
  63045. /**
  63046. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  63047. */
  63048. this.emitFromSpawnPointOnly = false;
  63049. this.angle = angle;
  63050. this.radius = radius;
  63051. }
  63052. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  63053. /**
  63054. * Gets or sets the radius of the emission cone
  63055. */
  63056. get: function () {
  63057. return this._radius;
  63058. },
  63059. set: function (value) {
  63060. this._radius = value;
  63061. this._buildHeight();
  63062. },
  63063. enumerable: true,
  63064. configurable: true
  63065. });
  63066. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  63067. /**
  63068. * Gets or sets the angle of the emission cone
  63069. */
  63070. get: function () {
  63071. return this._angle;
  63072. },
  63073. set: function (value) {
  63074. this._angle = value;
  63075. this._buildHeight();
  63076. },
  63077. enumerable: true,
  63078. configurable: true
  63079. });
  63080. ConeParticleEmitter.prototype._buildHeight = function () {
  63081. if (this._angle !== 0) {
  63082. this._height = this._radius / Math.tan(this._angle / 2);
  63083. }
  63084. else {
  63085. this._height = 1;
  63086. }
  63087. };
  63088. /**
  63089. * Called by the particle System when the direction is computed for the created particle.
  63090. * @param worldMatrix is the world matrix of the particle system
  63091. * @param directionToUpdate is the direction vector to update with the result
  63092. * @param particle is the particle we are computed the direction for
  63093. */
  63094. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63095. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  63096. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  63097. }
  63098. else {
  63099. // measure the direction Vector from the emitter to the particle.
  63100. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  63101. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63102. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63103. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63104. direction.x += randX;
  63105. direction.y += randY;
  63106. direction.z += randZ;
  63107. direction.normalize();
  63108. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  63109. }
  63110. };
  63111. /**
  63112. * Called by the particle System when the position is computed for the created particle.
  63113. * @param worldMatrix is the world matrix of the particle system
  63114. * @param positionToUpdate is the position vector to update with the result
  63115. * @param particle is the particle we are computed the position for
  63116. */
  63117. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63118. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  63119. var h;
  63120. if (!this.emitFromSpawnPointOnly) {
  63121. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  63122. // Better distribution in a cone at normal angles.
  63123. h = 1 - h * h;
  63124. }
  63125. else {
  63126. h = 0.0001;
  63127. }
  63128. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  63129. radius = radius * h;
  63130. var randX = radius * Math.sin(s);
  63131. var randZ = radius * Math.cos(s);
  63132. var randY = h * this._height;
  63133. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  63134. };
  63135. /**
  63136. * Clones the current emitter and returns a copy of it
  63137. * @returns the new emitter
  63138. */
  63139. ConeParticleEmitter.prototype.clone = function () {
  63140. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  63141. BABYLON.Tools.DeepCopy(this, newOne);
  63142. return newOne;
  63143. };
  63144. /**
  63145. * Called by the GPUParticleSystem to setup the update shader
  63146. * @param effect defines the update shader
  63147. */
  63148. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  63149. effect.setFloat2("radius", this._radius, this.radiusRange);
  63150. effect.setFloat("coneAngle", this._angle);
  63151. effect.setFloat2("height", this._height, this.heightRange);
  63152. effect.setFloat("directionRandomizer", this.directionRandomizer);
  63153. };
  63154. /**
  63155. * Returns a string to use to update the GPU particles update shader
  63156. * @returns a string containng the defines string
  63157. */
  63158. ConeParticleEmitter.prototype.getEffectDefines = function () {
  63159. var defines = "#define CONEEMITTER";
  63160. if (this.emitFromSpawnPointOnly) {
  63161. defines += "\n#define CONEEMITTERSPAWNPOINT";
  63162. }
  63163. return defines;
  63164. };
  63165. /**
  63166. * Returns the string "ConeParticleEmitter"
  63167. * @returns a string containing the class name
  63168. */
  63169. ConeParticleEmitter.prototype.getClassName = function () {
  63170. return "ConeParticleEmitter";
  63171. };
  63172. /**
  63173. * Serializes the particle system to a JSON object.
  63174. * @returns the JSON object
  63175. */
  63176. ConeParticleEmitter.prototype.serialize = function () {
  63177. var serializationObject = {};
  63178. serializationObject.type = this.getClassName();
  63179. serializationObject.radius = this._radius;
  63180. serializationObject.angle = this._angle;
  63181. serializationObject.directionRandomizer = this.directionRandomizer;
  63182. return serializationObject;
  63183. };
  63184. /**
  63185. * Parse properties from a JSON object
  63186. * @param serializationObject defines the JSON object
  63187. */
  63188. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  63189. this.radius = serializationObject.radius;
  63190. this.angle = serializationObject.angle;
  63191. this.directionRandomizer = serializationObject.directionRandomizer;
  63192. };
  63193. return ConeParticleEmitter;
  63194. }());
  63195. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  63196. })(BABYLON || (BABYLON = {}));
  63197. //# sourceMappingURL=coneParticleEmitter.js.map
  63198. var BABYLON;
  63199. (function (BABYLON) {
  63200. /**
  63201. * Particle emitter emitting particles from the inside of a sphere.
  63202. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  63203. */
  63204. var SphereParticleEmitter = /** @class */ (function () {
  63205. /**
  63206. * Creates a new instance SphereParticleEmitter
  63207. * @param radius the radius of the emission sphere (1 by default)
  63208. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  63209. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  63210. */
  63211. function SphereParticleEmitter(
  63212. /**
  63213. * The radius of the emission sphere.
  63214. */
  63215. radius,
  63216. /**
  63217. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  63218. */
  63219. radiusRange,
  63220. /**
  63221. * How much to randomize the particle direction [0-1].
  63222. */
  63223. directionRandomizer) {
  63224. if (radius === void 0) { radius = 1; }
  63225. if (radiusRange === void 0) { radiusRange = 1; }
  63226. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  63227. this.radius = radius;
  63228. this.radiusRange = radiusRange;
  63229. this.directionRandomizer = directionRandomizer;
  63230. }
  63231. /**
  63232. * Called by the particle System when the direction is computed for the created particle.
  63233. * @param worldMatrix is the world matrix of the particle system
  63234. * @param directionToUpdate is the direction vector to update with the result
  63235. * @param particle is the particle we are computed the direction for
  63236. */
  63237. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63238. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  63239. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63240. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63241. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63242. direction.x += randX;
  63243. direction.y += randY;
  63244. direction.z += randZ;
  63245. direction.normalize();
  63246. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  63247. };
  63248. /**
  63249. * Called by the particle System when the position is computed for the created particle.
  63250. * @param worldMatrix is the world matrix of the particle system
  63251. * @param positionToUpdate is the position vector to update with the result
  63252. * @param particle is the particle we are computed the position for
  63253. */
  63254. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63255. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  63256. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  63257. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  63258. var theta = Math.acos(2 * v - 1);
  63259. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  63260. var randY = randRadius * Math.cos(theta);
  63261. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  63262. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  63263. };
  63264. /**
  63265. * Clones the current emitter and returns a copy of it
  63266. * @returns the new emitter
  63267. */
  63268. SphereParticleEmitter.prototype.clone = function () {
  63269. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  63270. BABYLON.Tools.DeepCopy(this, newOne);
  63271. return newOne;
  63272. };
  63273. /**
  63274. * Called by the GPUParticleSystem to setup the update shader
  63275. * @param effect defines the update shader
  63276. */
  63277. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  63278. effect.setFloat("radius", this.radius);
  63279. effect.setFloat("radiusRange", this.radiusRange);
  63280. effect.setFloat("directionRandomizer", this.directionRandomizer);
  63281. };
  63282. /**
  63283. * Returns a string to use to update the GPU particles update shader
  63284. * @returns a string containng the defines string
  63285. */
  63286. SphereParticleEmitter.prototype.getEffectDefines = function () {
  63287. return "#define SPHEREEMITTER";
  63288. };
  63289. /**
  63290. * Returns the string "SphereParticleEmitter"
  63291. * @returns a string containing the class name
  63292. */
  63293. SphereParticleEmitter.prototype.getClassName = function () {
  63294. return "SphereParticleEmitter";
  63295. };
  63296. /**
  63297. * Serializes the particle system to a JSON object.
  63298. * @returns the JSON object
  63299. */
  63300. SphereParticleEmitter.prototype.serialize = function () {
  63301. var serializationObject = {};
  63302. serializationObject.type = this.getClassName();
  63303. serializationObject.radius = this.radius;
  63304. serializationObject.radiusRange = this.radiusRange;
  63305. serializationObject.directionRandomizer = this.directionRandomizer;
  63306. return serializationObject;
  63307. };
  63308. /**
  63309. * Parse properties from a JSON object
  63310. * @param serializationObject defines the JSON object
  63311. */
  63312. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  63313. this.radius = serializationObject.radius;
  63314. this.radiusRange = serializationObject.radiusRange;
  63315. this.directionRandomizer = serializationObject.directionRandomizer;
  63316. };
  63317. return SphereParticleEmitter;
  63318. }());
  63319. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  63320. /**
  63321. * Particle emitter emitting particles from the inside of a sphere.
  63322. * It emits the particles randomly between two vectors.
  63323. */
  63324. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  63325. __extends(SphereDirectedParticleEmitter, _super);
  63326. /**
  63327. * Creates a new instance SphereDirectedParticleEmitter
  63328. * @param radius the radius of the emission sphere (1 by default)
  63329. * @param direction1 the min limit of the emission direction (up vector by default)
  63330. * @param direction2 the max limit of the emission direction (up vector by default)
  63331. */
  63332. function SphereDirectedParticleEmitter(radius,
  63333. /**
  63334. * The min limit of the emission direction.
  63335. */
  63336. direction1,
  63337. /**
  63338. * The max limit of the emission direction.
  63339. */
  63340. direction2) {
  63341. if (radius === void 0) { radius = 1; }
  63342. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  63343. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  63344. var _this = _super.call(this, radius) || this;
  63345. _this.direction1 = direction1;
  63346. _this.direction2 = direction2;
  63347. return _this;
  63348. }
  63349. /**
  63350. * Called by the particle System when the direction is computed for the created particle.
  63351. * @param worldMatrix is the world matrix of the particle system
  63352. * @param directionToUpdate is the direction vector to update with the result
  63353. * @param particle is the particle we are computed the direction for
  63354. */
  63355. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63356. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  63357. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  63358. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  63359. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  63360. };
  63361. /**
  63362. * Clones the current emitter and returns a copy of it
  63363. * @returns the new emitter
  63364. */
  63365. SphereDirectedParticleEmitter.prototype.clone = function () {
  63366. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  63367. BABYLON.Tools.DeepCopy(this, newOne);
  63368. return newOne;
  63369. };
  63370. /**
  63371. * Called by the GPUParticleSystem to setup the update shader
  63372. * @param effect defines the update shader
  63373. */
  63374. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  63375. effect.setFloat("radius", this.radius);
  63376. effect.setFloat("radiusRange", this.radiusRange);
  63377. effect.setVector3("direction1", this.direction1);
  63378. effect.setVector3("direction2", this.direction2);
  63379. };
  63380. /**
  63381. * Returns a string to use to update the GPU particles update shader
  63382. * @returns a string containng the defines string
  63383. */
  63384. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  63385. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  63386. };
  63387. /**
  63388. * Returns the string "SphereDirectedParticleEmitter"
  63389. * @returns a string containing the class name
  63390. */
  63391. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  63392. return "SphereDirectedParticleEmitter";
  63393. };
  63394. /**
  63395. * Serializes the particle system to a JSON object.
  63396. * @returns the JSON object
  63397. */
  63398. SphereDirectedParticleEmitter.prototype.serialize = function () {
  63399. var serializationObject = _super.prototype.serialize.call(this);
  63400. serializationObject.direction1 = this.direction1.asArray();
  63401. serializationObject.direction2 = this.direction2.asArray();
  63402. return serializationObject;
  63403. };
  63404. /**
  63405. * Parse properties from a JSON object
  63406. * @param serializationObject defines the JSON object
  63407. */
  63408. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  63409. _super.prototype.parse.call(this, serializationObject);
  63410. this.direction1.copyFrom(serializationObject.direction1);
  63411. this.direction2.copyFrom(serializationObject.direction2);
  63412. };
  63413. return SphereDirectedParticleEmitter;
  63414. }(SphereParticleEmitter));
  63415. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  63416. })(BABYLON || (BABYLON = {}));
  63417. //# sourceMappingURL=sphereParticleEmitter.js.map
  63418. var BABYLON;
  63419. (function (BABYLON) {
  63420. /**
  63421. * Particle emitter emitting particles from the inside of a hemisphere.
  63422. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  63423. */
  63424. var HemisphericParticleEmitter = /** @class */ (function () {
  63425. /**
  63426. * Creates a new instance HemisphericParticleEmitter
  63427. * @param radius the radius of the emission hemisphere (1 by default)
  63428. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  63429. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  63430. */
  63431. function HemisphericParticleEmitter(
  63432. /**
  63433. * The radius of the emission hemisphere.
  63434. */
  63435. radius,
  63436. /**
  63437. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  63438. */
  63439. radiusRange,
  63440. /**
  63441. * How much to randomize the particle direction [0-1].
  63442. */
  63443. directionRandomizer) {
  63444. if (radius === void 0) { radius = 1; }
  63445. if (radiusRange === void 0) { radiusRange = 1; }
  63446. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  63447. this.radius = radius;
  63448. this.radiusRange = radiusRange;
  63449. this.directionRandomizer = directionRandomizer;
  63450. }
  63451. /**
  63452. * Called by the particle System when the direction is computed for the created particle.
  63453. * @param worldMatrix is the world matrix of the particle system
  63454. * @param directionToUpdate is the direction vector to update with the result
  63455. * @param particle is the particle we are computed the direction for
  63456. */
  63457. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63458. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  63459. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63460. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63461. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  63462. direction.x += randX;
  63463. direction.y += randY;
  63464. direction.z += randZ;
  63465. direction.normalize();
  63466. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  63467. };
  63468. /**
  63469. * Called by the particle System when the position is computed for the created particle.
  63470. * @param worldMatrix is the world matrix of the particle system
  63471. * @param positionToUpdate is the position vector to update with the result
  63472. * @param particle is the particle we are computed the position for
  63473. */
  63474. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63475. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  63476. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  63477. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  63478. var theta = Math.acos(2 * v - 1);
  63479. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  63480. var randY = randRadius * Math.cos(theta);
  63481. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  63482. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  63483. };
  63484. /**
  63485. * Clones the current emitter and returns a copy of it
  63486. * @returns the new emitter
  63487. */
  63488. HemisphericParticleEmitter.prototype.clone = function () {
  63489. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  63490. BABYLON.Tools.DeepCopy(this, newOne);
  63491. return newOne;
  63492. };
  63493. /**
  63494. * Called by the GPUParticleSystem to setup the update shader
  63495. * @param effect defines the update shader
  63496. */
  63497. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  63498. effect.setFloat("radius", this.radius);
  63499. effect.setFloat("radiusRange", this.radiusRange);
  63500. effect.setFloat("directionRandomizer", this.directionRandomizer);
  63501. };
  63502. /**
  63503. * Returns a string to use to update the GPU particles update shader
  63504. * @returns a string containng the defines string
  63505. */
  63506. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  63507. return "#define HEMISPHERICEMITTER";
  63508. };
  63509. /**
  63510. * Returns the string "HemisphericParticleEmitter"
  63511. * @returns a string containing the class name
  63512. */
  63513. HemisphericParticleEmitter.prototype.getClassName = function () {
  63514. return "HemisphericParticleEmitter";
  63515. };
  63516. /**
  63517. * Serializes the particle system to a JSON object.
  63518. * @returns the JSON object
  63519. */
  63520. HemisphericParticleEmitter.prototype.serialize = function () {
  63521. var serializationObject = {};
  63522. serializationObject.type = this.getClassName();
  63523. serializationObject.radius = this.radius;
  63524. serializationObject.radiusRange = this.radiusRange;
  63525. serializationObject.directionRandomizer = this.directionRandomizer;
  63526. return serializationObject;
  63527. };
  63528. /**
  63529. * Parse properties from a JSON object
  63530. * @param serializationObject defines the JSON object
  63531. */
  63532. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  63533. this.radius = serializationObject.radius;
  63534. this.radiusRange = serializationObject.radiusRange;
  63535. this.directionRandomizer = serializationObject.directionRandomizer;
  63536. };
  63537. return HemisphericParticleEmitter;
  63538. }());
  63539. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  63540. })(BABYLON || (BABYLON = {}));
  63541. //# sourceMappingURL=hemisphericParticleEmitter.js.map
  63542. var BABYLON;
  63543. (function (BABYLON) {
  63544. /**
  63545. * Particle emitter emitting particles from a point.
  63546. * It emits the particles randomly between 2 given directions.
  63547. */
  63548. var PointParticleEmitter = /** @class */ (function () {
  63549. /**
  63550. * Creates a new instance PointParticleEmitter
  63551. */
  63552. function PointParticleEmitter() {
  63553. /**
  63554. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  63555. */
  63556. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  63557. /**
  63558. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  63559. */
  63560. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  63561. }
  63562. /**
  63563. * Called by the particle System when the direction is computed for the created particle.
  63564. * @param worldMatrix is the world matrix of the particle system
  63565. * @param directionToUpdate is the direction vector to update with the result
  63566. * @param particle is the particle we are computed the direction for
  63567. */
  63568. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  63569. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  63570. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  63571. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  63572. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  63573. };
  63574. /**
  63575. * Called by the particle System when the position is computed for the created particle.
  63576. * @param worldMatrix is the world matrix of the particle system
  63577. * @param positionToUpdate is the position vector to update with the result
  63578. * @param particle is the particle we are computed the position for
  63579. */
  63580. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  63581. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  63582. };
  63583. /**
  63584. * Clones the current emitter and returns a copy of it
  63585. * @returns the new emitter
  63586. */
  63587. PointParticleEmitter.prototype.clone = function () {
  63588. var newOne = new PointParticleEmitter();
  63589. BABYLON.Tools.DeepCopy(this, newOne);
  63590. return newOne;
  63591. };
  63592. /**
  63593. * Called by the GPUParticleSystem to setup the update shader
  63594. * @param effect defines the update shader
  63595. */
  63596. PointParticleEmitter.prototype.applyToShader = function (effect) {
  63597. effect.setVector3("direction1", this.direction1);
  63598. effect.setVector3("direction2", this.direction2);
  63599. };
  63600. /**
  63601. * Returns a string to use to update the GPU particles update shader
  63602. * @returns a string containng the defines string
  63603. */
  63604. PointParticleEmitter.prototype.getEffectDefines = function () {
  63605. return "#define POINTEMITTER";
  63606. };
  63607. /**
  63608. * Returns the string "PointParticleEmitter"
  63609. * @returns a string containing the class name
  63610. */
  63611. PointParticleEmitter.prototype.getClassName = function () {
  63612. return "PointParticleEmitter";
  63613. };
  63614. /**
  63615. * Serializes the particle system to a JSON object.
  63616. * @returns the JSON object
  63617. */
  63618. PointParticleEmitter.prototype.serialize = function () {
  63619. var serializationObject = {};
  63620. serializationObject.type = this.getClassName();
  63621. serializationObject.direction1 = this.direction1.asArray();
  63622. serializationObject.direction2 = this.direction2.asArray();
  63623. return serializationObject;
  63624. };
  63625. /**
  63626. * Parse properties from a JSON object
  63627. * @param serializationObject defines the JSON object
  63628. */
  63629. PointParticleEmitter.prototype.parse = function (serializationObject) {
  63630. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  63631. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  63632. };
  63633. return PointParticleEmitter;
  63634. }());
  63635. BABYLON.PointParticleEmitter = PointParticleEmitter;
  63636. })(BABYLON || (BABYLON = {}));
  63637. //# sourceMappingURL=pointParticleEmitter.js.map
  63638. var BABYLON;
  63639. (function (BABYLON) {
  63640. // Adds the parsers to the scene parsers.
  63641. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  63642. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  63643. if (!individualParser) {
  63644. return;
  63645. }
  63646. // Particles Systems
  63647. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63648. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63649. var parsedParticleSystem = parsedData.particleSystems[index];
  63650. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  63651. }
  63652. }
  63653. });
  63654. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  63655. if (parsedParticleSystem.activeParticleCount) {
  63656. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63657. return ps;
  63658. }
  63659. else {
  63660. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63661. return ps;
  63662. }
  63663. });
  63664. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  63665. if (uniformsNames === void 0) { uniformsNames = []; }
  63666. if (samplers === void 0) { samplers = []; }
  63667. if (defines === void 0) { defines = ""; }
  63668. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  63669. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  63670. if (defines.indexOf(" BILLBOARD") === -1) {
  63671. defines += "\n#define BILLBOARD\n";
  63672. }
  63673. if (samplers.indexOf("diffuseSampler") === -1) {
  63674. samplers.push("diffuseSampler");
  63675. }
  63676. return this.createEffect({
  63677. vertex: "particles",
  63678. fragmentElement: fragmentName
  63679. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  63680. };
  63681. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  63682. var results = new Array();
  63683. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  63684. var particleSystem = this.getScene().particleSystems[index];
  63685. if (particleSystem.emitter === this) {
  63686. results.push(particleSystem);
  63687. }
  63688. }
  63689. return results;
  63690. };
  63691. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  63692. var results = new Array();
  63693. var descendants = this.getDescendants();
  63694. descendants.push(this);
  63695. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  63696. var particleSystem = this.getScene().particleSystems[index];
  63697. var emitter = particleSystem.emitter;
  63698. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  63699. results.push(particleSystem);
  63700. }
  63701. }
  63702. return results;
  63703. };
  63704. })(BABYLON || (BABYLON = {}));
  63705. //# sourceMappingURL=particleSystemComponent.js.map
  63706. var BABYLON;
  63707. (function (BABYLON) {
  63708. /**
  63709. * Type of sub emitter
  63710. */
  63711. var SubEmitterType;
  63712. (function (SubEmitterType) {
  63713. /**
  63714. * Attached to the particle over it's lifetime
  63715. */
  63716. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  63717. /**
  63718. * Created when the particle dies
  63719. */
  63720. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  63721. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  63722. /**
  63723. * Sub emitter class used to emit particles from an existing particle
  63724. */
  63725. var SubEmitter = /** @class */ (function () {
  63726. /**
  63727. * Creates a sub emitter
  63728. * @param particleSystem the particle system to be used by the sub emitter
  63729. */
  63730. function SubEmitter(
  63731. /**
  63732. * the particle system to be used by the sub emitter
  63733. */
  63734. particleSystem) {
  63735. this.particleSystem = particleSystem;
  63736. /**
  63737. * Type of the submitter (Default: END)
  63738. */
  63739. this.type = SubEmitterType.END;
  63740. /**
  63741. * 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)
  63742. * Note: This only is supported when using an emitter of type Mesh
  63743. */
  63744. this.inheritDirection = false;
  63745. /**
  63746. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  63747. */
  63748. this.inheritedVelocityAmount = 0;
  63749. // Create mesh as emitter to support rotation
  63750. if (!particleSystem.emitter || !particleSystem.emitter.dispose) {
  63751. particleSystem.emitter = new BABYLON.AbstractMesh("SubemitterSystemEmitter", particleSystem.getScene());
  63752. }
  63753. // Automatically dispose of subemitter when system is disposed
  63754. particleSystem.onDisposeObservable.add(function () {
  63755. if (particleSystem.emitter && particleSystem.emitter.dispose) {
  63756. particleSystem.emitter.dispose();
  63757. }
  63758. });
  63759. }
  63760. /**
  63761. * Clones the sub emitter
  63762. * @returns the cloned sub emitter
  63763. */
  63764. SubEmitter.prototype.clone = function () {
  63765. // Clone particle system
  63766. var emitter = this.particleSystem.emitter;
  63767. if (!emitter) {
  63768. emitter = new BABYLON.Vector3();
  63769. }
  63770. else if (emitter instanceof BABYLON.Vector3) {
  63771. emitter = emitter.clone();
  63772. }
  63773. else if (emitter instanceof BABYLON.AbstractMesh) {
  63774. emitter = new BABYLON.Mesh("", emitter.getScene());
  63775. emitter.isVisible = false;
  63776. }
  63777. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  63778. // Clone properties
  63779. clone.type = this.type;
  63780. clone.inheritDirection = this.inheritDirection;
  63781. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  63782. clone.particleSystem._disposeEmitterOnDispose = true;
  63783. clone.particleSystem.disposeOnStop = true;
  63784. return clone;
  63785. };
  63786. /**
  63787. * Serialize current object to a JSON object
  63788. * @returns the serialized object
  63789. */
  63790. SubEmitter.prototype.serialize = function () {
  63791. var serializationObject = {};
  63792. serializationObject.type = this.type;
  63793. serializationObject.inheritDirection = this.inheritDirection;
  63794. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  63795. serializationObject.particleSystem = this.particleSystem.serialize();
  63796. return serializationObject;
  63797. };
  63798. /**
  63799. * Creates a new SubEmitter from a serialized JSON version
  63800. * @param serializationObject defines the JSON object to read from
  63801. * @param scene defines the hosting scene
  63802. * @param rootUrl defines the rootUrl for data loading
  63803. * @returns a new SubEmitter
  63804. */
  63805. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  63806. var system = serializationObject.particleSystem;
  63807. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  63808. subEmitter.type = serializationObject.type;
  63809. subEmitter.inheritDirection = serializationObject.inheritDirection;
  63810. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  63811. subEmitter.particleSystem._isSubEmitter = true;
  63812. return subEmitter;
  63813. };
  63814. /** Release associated resources */
  63815. SubEmitter.prototype.dispose = function () {
  63816. this.particleSystem.dispose();
  63817. };
  63818. return SubEmitter;
  63819. }());
  63820. BABYLON.SubEmitter = SubEmitter;
  63821. })(BABYLON || (BABYLON = {}));
  63822. //# sourceMappingURL=subEmitter.js.map
  63823. var BABYLON;
  63824. (function (BABYLON) {
  63825. /**
  63826. * 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.
  63827. *
  63828. * This returned material effects how the mesh will look based on the code in the shaders.
  63829. *
  63830. * @see http://doc.babylonjs.com/how_to/shader_material
  63831. */
  63832. var ShaderMaterial = /** @class */ (function (_super) {
  63833. __extends(ShaderMaterial, _super);
  63834. /**
  63835. * Instantiate a new shader material.
  63836. * 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.
  63837. * This returned material effects how the mesh will look based on the code in the shaders.
  63838. * @see http://doc.babylonjs.com/how_to/shader_material
  63839. * @param name Define the name of the material in the scene
  63840. * @param scene Define the scene the material belongs to
  63841. * @param shaderPath Defines the route to the shader code in one of three ways:
  63842. * - object - { vertex: "custom", fragment: "custom" }, used with BABYLON.Effect.ShadersStore["customVertexShader"] and BABYLON.Effect.ShadersStore["customFragmentShader"]
  63843. * - object - { vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" }, used with shader code in <script> tags
  63844. * - string - "./COMMON_NAME", used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder.
  63845. * @param options Define the options used to create the shader
  63846. */
  63847. function ShaderMaterial(name, scene, shaderPath, options) {
  63848. if (options === void 0) { options = {}; }
  63849. var _this = _super.call(this, name, scene) || this;
  63850. _this._textures = {};
  63851. _this._textureArrays = {};
  63852. _this._floats = {};
  63853. _this._ints = {};
  63854. _this._floatsArrays = {};
  63855. _this._colors3 = {};
  63856. _this._colors3Arrays = {};
  63857. _this._colors4 = {};
  63858. _this._vectors2 = {};
  63859. _this._vectors3 = {};
  63860. _this._vectors4 = {};
  63861. _this._matrices = {};
  63862. _this._matrices3x3 = {};
  63863. _this._matrices2x2 = {};
  63864. _this._vectors2Arrays = {};
  63865. _this._vectors3Arrays = {};
  63866. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  63867. _this._shaderPath = shaderPath;
  63868. _this._options = __assign({ needAlphaBlending: false, needAlphaTesting: false, attributes: ["position", "normal", "uv"], uniforms: ["worldViewProjection"], uniformBuffers: [], samplers: [], defines: [] }, options);
  63869. return _this;
  63870. }
  63871. /**
  63872. * Gets the current class name of the material e.g. "ShaderMaterial"
  63873. * Mainly use in serialization.
  63874. * @returns the class name
  63875. */
  63876. ShaderMaterial.prototype.getClassName = function () {
  63877. return "ShaderMaterial";
  63878. };
  63879. /**
  63880. * Specifies if the material will require alpha blending
  63881. * @returns a boolean specifying if alpha blending is needed
  63882. */
  63883. ShaderMaterial.prototype.needAlphaBlending = function () {
  63884. return (this.alpha < 1.0) || this._options.needAlphaBlending;
  63885. };
  63886. /**
  63887. * Specifies if this material should be rendered in alpha test mode
  63888. * @returns a boolean specifying if an alpha test is needed.
  63889. */
  63890. ShaderMaterial.prototype.needAlphaTesting = function () {
  63891. return this._options.needAlphaTesting;
  63892. };
  63893. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  63894. if (this._options.uniforms.indexOf(uniformName) === -1) {
  63895. this._options.uniforms.push(uniformName);
  63896. }
  63897. };
  63898. /**
  63899. * Set a texture in the shader.
  63900. * @param name Define the name of the uniform samplers as defined in the shader
  63901. * @param texture Define the texture to bind to this sampler
  63902. * @return the material itself allowing "fluent" like uniform updates
  63903. */
  63904. ShaderMaterial.prototype.setTexture = function (name, texture) {
  63905. if (this._options.samplers.indexOf(name) === -1) {
  63906. this._options.samplers.push(name);
  63907. }
  63908. this._textures[name] = texture;
  63909. return this;
  63910. };
  63911. /**
  63912. * Set a texture array in the shader.
  63913. * @param name Define the name of the uniform sampler array as defined in the shader
  63914. * @param textures Define the list of textures to bind to this sampler
  63915. * @return the material itself allowing "fluent" like uniform updates
  63916. */
  63917. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  63918. if (this._options.samplers.indexOf(name) === -1) {
  63919. this._options.samplers.push(name);
  63920. }
  63921. this._checkUniform(name);
  63922. this._textureArrays[name] = textures;
  63923. return this;
  63924. };
  63925. /**
  63926. * Set a float in the shader.
  63927. * @param name Define the name of the uniform as defined in the shader
  63928. * @param value Define the value to give to the uniform
  63929. * @return the material itself allowing "fluent" like uniform updates
  63930. */
  63931. ShaderMaterial.prototype.setFloat = function (name, value) {
  63932. this._checkUniform(name);
  63933. this._floats[name] = value;
  63934. return this;
  63935. };
  63936. /**
  63937. * Set a int in the shader.
  63938. * @param name Define the name of the uniform as defined in the shader
  63939. * @param value Define the value to give to the uniform
  63940. * @return the material itself allowing "fluent" like uniform updates
  63941. */
  63942. ShaderMaterial.prototype.setInt = function (name, value) {
  63943. this._checkUniform(name);
  63944. this._ints[name] = value;
  63945. return this;
  63946. };
  63947. /**
  63948. * Set an array of floats in the shader.
  63949. * @param name Define the name of the uniform as defined in the shader
  63950. * @param value Define the value to give to the uniform
  63951. * @return the material itself allowing "fluent" like uniform updates
  63952. */
  63953. ShaderMaterial.prototype.setFloats = function (name, value) {
  63954. this._checkUniform(name);
  63955. this._floatsArrays[name] = value;
  63956. return this;
  63957. };
  63958. /**
  63959. * Set a vec3 in the shader from a Color3.
  63960. * @param name Define the name of the uniform as defined in the shader
  63961. * @param value Define the value to give to the uniform
  63962. * @return the material itself allowing "fluent" like uniform updates
  63963. */
  63964. ShaderMaterial.prototype.setColor3 = function (name, value) {
  63965. this._checkUniform(name);
  63966. this._colors3[name] = value;
  63967. return this;
  63968. };
  63969. /**
  63970. * Set a vec3 array in the shader from a Color3 array.
  63971. * @param name Define the name of the uniform as defined in the shader
  63972. * @param value Define the value to give to the uniform
  63973. * @return the material itself allowing "fluent" like uniform updates
  63974. */
  63975. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  63976. this._checkUniform(name);
  63977. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  63978. color.toArray(arr, arr.length);
  63979. return arr;
  63980. }, []);
  63981. return this;
  63982. };
  63983. /**
  63984. * Set a vec4 in the shader from a Color4.
  63985. * @param name Define the name of the uniform as defined in the shader
  63986. * @param value Define the value to give to the uniform
  63987. * @return the material itself allowing "fluent" like uniform updates
  63988. */
  63989. ShaderMaterial.prototype.setColor4 = function (name, value) {
  63990. this._checkUniform(name);
  63991. this._colors4[name] = value;
  63992. return this;
  63993. };
  63994. /**
  63995. * Set a vec2 in the shader from a Vector2.
  63996. * @param name Define the name of the uniform as defined in the shader
  63997. * @param value Define the value to give to the uniform
  63998. * @return the material itself allowing "fluent" like uniform updates
  63999. */
  64000. ShaderMaterial.prototype.setVector2 = function (name, value) {
  64001. this._checkUniform(name);
  64002. this._vectors2[name] = value;
  64003. return this;
  64004. };
  64005. /**
  64006. * Set a vec3 in the shader from a Vector3.
  64007. * @param name Define the name of the uniform as defined in the shader
  64008. * @param value Define the value to give to the uniform
  64009. * @return the material itself allowing "fluent" like uniform updates
  64010. */
  64011. ShaderMaterial.prototype.setVector3 = function (name, value) {
  64012. this._checkUniform(name);
  64013. this._vectors3[name] = value;
  64014. return this;
  64015. };
  64016. /**
  64017. * Set a vec4 in the shader from a Vector4.
  64018. * @param name Define the name of the uniform as defined in the shader
  64019. * @param value Define the value to give to the uniform
  64020. * @return the material itself allowing "fluent" like uniform updates
  64021. */
  64022. ShaderMaterial.prototype.setVector4 = function (name, value) {
  64023. this._checkUniform(name);
  64024. this._vectors4[name] = value;
  64025. return this;
  64026. };
  64027. /**
  64028. * Set a mat4 in the shader from a Matrix.
  64029. * @param name Define the name of the uniform as defined in the shader
  64030. * @param value Define the value to give to the uniform
  64031. * @return the material itself allowing "fluent" like uniform updates
  64032. */
  64033. ShaderMaterial.prototype.setMatrix = function (name, value) {
  64034. this._checkUniform(name);
  64035. this._matrices[name] = value;
  64036. return this;
  64037. };
  64038. /**
  64039. * Set a mat3 in the shader from a Float32Array.
  64040. * @param name Define the name of the uniform as defined in the shader
  64041. * @param value Define the value to give to the uniform
  64042. * @return the material itself allowing "fluent" like uniform updates
  64043. */
  64044. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  64045. this._checkUniform(name);
  64046. this._matrices3x3[name] = value;
  64047. return this;
  64048. };
  64049. /**
  64050. * Set a mat2 in the shader from a Float32Array.
  64051. * @param name Define the name of the uniform as defined in the shader
  64052. * @param value Define the value to give to the uniform
  64053. * @return the material itself allowing "fluent" like uniform updates
  64054. */
  64055. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  64056. this._checkUniform(name);
  64057. this._matrices2x2[name] = value;
  64058. return this;
  64059. };
  64060. /**
  64061. * Set a vec2 array in the shader from a number array.
  64062. * @param name Define the name of the uniform as defined in the shader
  64063. * @param value Define the value to give to the uniform
  64064. * @return the material itself allowing "fluent" like uniform updates
  64065. */
  64066. ShaderMaterial.prototype.setArray2 = function (name, value) {
  64067. this._checkUniform(name);
  64068. this._vectors2Arrays[name] = value;
  64069. return this;
  64070. };
  64071. /**
  64072. * Set a vec3 array in the shader from a number array.
  64073. * @param name Define the name of the uniform as defined in the shader
  64074. * @param value Define the value to give to the uniform
  64075. * @return the material itself allowing "fluent" like uniform updates
  64076. */
  64077. ShaderMaterial.prototype.setArray3 = function (name, value) {
  64078. this._checkUniform(name);
  64079. this._vectors3Arrays[name] = value;
  64080. return this;
  64081. };
  64082. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  64083. if (!mesh) {
  64084. return true;
  64085. }
  64086. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  64087. return false;
  64088. }
  64089. return false;
  64090. };
  64091. /**
  64092. * Checks if the material is ready to render the requested mesh
  64093. * @param mesh Define the mesh to render
  64094. * @param useInstances Define whether or not the material is used with instances
  64095. * @returns true if ready, otherwise false
  64096. */
  64097. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  64098. var scene = this.getScene();
  64099. var engine = scene.getEngine();
  64100. if (!this.checkReadyOnEveryCall) {
  64101. if (this._renderId === scene.getRenderId()) {
  64102. if (this._checkCache(scene, mesh, useInstances)) {
  64103. return true;
  64104. }
  64105. }
  64106. }
  64107. // Instances
  64108. var defines = [];
  64109. var attribs = [];
  64110. var fallbacks = new BABYLON.EffectFallbacks();
  64111. for (var index = 0; index < this._options.defines.length; index++) {
  64112. defines.push(this._options.defines[index]);
  64113. }
  64114. for (var index = 0; index < this._options.attributes.length; index++) {
  64115. attribs.push(this._options.attributes[index]);
  64116. }
  64117. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  64118. attribs.push(BABYLON.VertexBuffer.ColorKind);
  64119. defines.push("#define VERTEXCOLOR");
  64120. }
  64121. if (useInstances) {
  64122. defines.push("#define INSTANCES");
  64123. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  64124. }
  64125. // Bones
  64126. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64127. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64128. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64129. if (mesh.numBoneInfluencers > 4) {
  64130. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64131. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64132. }
  64133. var skeleton = mesh.skeleton;
  64134. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64135. fallbacks.addCPUSkinningFallback(0, mesh);
  64136. if (skeleton.isUsingTextureForMatrices) {
  64137. defines.push("#define BONETEXTURE");
  64138. if (this._options.uniforms.indexOf("boneTextureWidth") === -1) {
  64139. this._options.uniforms.push("boneTextureWidth");
  64140. }
  64141. if (this._options.samplers.indexOf("boneSampler") === -1) {
  64142. this._options.samplers.push("boneSampler");
  64143. }
  64144. }
  64145. else {
  64146. defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1));
  64147. if (this._options.uniforms.indexOf("mBones") === -1) {
  64148. this._options.uniforms.push("mBones");
  64149. }
  64150. }
  64151. }
  64152. else {
  64153. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64154. }
  64155. // Textures
  64156. for (var name in this._textures) {
  64157. if (!this._textures[name].isReady()) {
  64158. return false;
  64159. }
  64160. }
  64161. // Alpha test
  64162. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  64163. defines.push("#define ALPHATEST");
  64164. }
  64165. var previousEffect = this._effect;
  64166. var join = defines.join("\n");
  64167. this._effect = engine.createEffect(this._shaderPath, {
  64168. attributes: attribs,
  64169. uniformsNames: this._options.uniforms,
  64170. uniformBuffersNames: this._options.uniformBuffers,
  64171. samplers: this._options.samplers,
  64172. defines: join,
  64173. fallbacks: fallbacks,
  64174. onCompiled: this.onCompiled,
  64175. onError: this.onError
  64176. }, engine);
  64177. if (!this._effect.isReady()) {
  64178. return false;
  64179. }
  64180. if (previousEffect !== this._effect) {
  64181. scene.resetCachedMaterial();
  64182. }
  64183. this._renderId = scene.getRenderId();
  64184. return true;
  64185. };
  64186. /**
  64187. * Binds the world matrix to the material
  64188. * @param world defines the world transformation matrix
  64189. */
  64190. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  64191. var scene = this.getScene();
  64192. if (!this._effect) {
  64193. return;
  64194. }
  64195. if (this._options.uniforms.indexOf("world") !== -1) {
  64196. this._effect.setMatrix("world", world);
  64197. }
  64198. if (this._options.uniforms.indexOf("worldView") !== -1) {
  64199. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  64200. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  64201. }
  64202. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  64203. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  64204. }
  64205. };
  64206. /**
  64207. * Binds the material to the mesh
  64208. * @param world defines the world transformation matrix
  64209. * @param mesh defines the mesh to bind the material to
  64210. */
  64211. ShaderMaterial.prototype.bind = function (world, mesh) {
  64212. // Std values
  64213. this.bindOnlyWorldMatrix(world);
  64214. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  64215. if (this._options.uniforms.indexOf("view") !== -1) {
  64216. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  64217. }
  64218. if (this._options.uniforms.indexOf("projection") !== -1) {
  64219. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  64220. }
  64221. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  64222. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  64223. }
  64224. // Bones
  64225. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  64226. var name;
  64227. // Texture
  64228. for (name in this._textures) {
  64229. this._effect.setTexture(name, this._textures[name]);
  64230. }
  64231. // Texture arrays
  64232. for (name in this._textureArrays) {
  64233. this._effect.setTextureArray(name, this._textureArrays[name]);
  64234. }
  64235. // Int
  64236. for (name in this._ints) {
  64237. this._effect.setInt(name, this._ints[name]);
  64238. }
  64239. // Float
  64240. for (name in this._floats) {
  64241. this._effect.setFloat(name, this._floats[name]);
  64242. }
  64243. // Floats
  64244. for (name in this._floatsArrays) {
  64245. this._effect.setArray(name, this._floatsArrays[name]);
  64246. }
  64247. // Color3
  64248. for (name in this._colors3) {
  64249. this._effect.setColor3(name, this._colors3[name]);
  64250. }
  64251. for (name in this._colors3Arrays) {
  64252. this._effect.setArray3(name, this._colors3Arrays[name]);
  64253. }
  64254. // Color4
  64255. for (name in this._colors4) {
  64256. var color = this._colors4[name];
  64257. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  64258. }
  64259. // Vector2
  64260. for (name in this._vectors2) {
  64261. this._effect.setVector2(name, this._vectors2[name]);
  64262. }
  64263. // Vector3
  64264. for (name in this._vectors3) {
  64265. this._effect.setVector3(name, this._vectors3[name]);
  64266. }
  64267. // Vector4
  64268. for (name in this._vectors4) {
  64269. this._effect.setVector4(name, this._vectors4[name]);
  64270. }
  64271. // Matrix
  64272. for (name in this._matrices) {
  64273. this._effect.setMatrix(name, this._matrices[name]);
  64274. }
  64275. // Matrix 3x3
  64276. for (name in this._matrices3x3) {
  64277. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  64278. }
  64279. // Matrix 2x2
  64280. for (name in this._matrices2x2) {
  64281. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  64282. }
  64283. // Vector2Array
  64284. for (name in this._vectors2Arrays) {
  64285. this._effect.setArray2(name, this._vectors2Arrays[name]);
  64286. }
  64287. // Vector3Array
  64288. for (name in this._vectors3Arrays) {
  64289. this._effect.setArray3(name, this._vectors3Arrays[name]);
  64290. }
  64291. }
  64292. this._afterBind(mesh);
  64293. };
  64294. /**
  64295. * Gets the active textures from the material
  64296. * @returns an array of textures
  64297. */
  64298. ShaderMaterial.prototype.getActiveTextures = function () {
  64299. var activeTextures = _super.prototype.getActiveTextures.call(this);
  64300. for (var name in this._textures) {
  64301. activeTextures.push(this._textures[name]);
  64302. }
  64303. for (var name in this._textureArrays) {
  64304. var array = this._textureArrays[name];
  64305. for (var index = 0; index < array.length; index++) {
  64306. activeTextures.push(array[index]);
  64307. }
  64308. }
  64309. return activeTextures;
  64310. };
  64311. /**
  64312. * Specifies if the material uses a texture
  64313. * @param texture defines the texture to check against the material
  64314. * @returns a boolean specifying if the material uses the texture
  64315. */
  64316. ShaderMaterial.prototype.hasTexture = function (texture) {
  64317. if (_super.prototype.hasTexture.call(this, texture)) {
  64318. return true;
  64319. }
  64320. for (var name in this._textures) {
  64321. if (this._textures[name] === texture) {
  64322. return true;
  64323. }
  64324. }
  64325. for (var name in this._textureArrays) {
  64326. var array = this._textureArrays[name];
  64327. for (var index = 0; index < array.length; index++) {
  64328. if (array[index] === texture) {
  64329. return true;
  64330. }
  64331. }
  64332. }
  64333. return false;
  64334. };
  64335. /**
  64336. * Makes a duplicate of the material, and gives it a new name
  64337. * @param name defines the new name for the duplicated material
  64338. * @returns the cloned material
  64339. */
  64340. ShaderMaterial.prototype.clone = function (name) {
  64341. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  64342. return newShaderMaterial;
  64343. };
  64344. /**
  64345. * Disposes the material
  64346. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  64347. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  64348. * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh
  64349. */
  64350. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {
  64351. if (forceDisposeTextures) {
  64352. var name;
  64353. for (name in this._textures) {
  64354. this._textures[name].dispose();
  64355. }
  64356. for (name in this._textureArrays) {
  64357. var array = this._textureArrays[name];
  64358. for (var index = 0; index < array.length; index++) {
  64359. array[index].dispose();
  64360. }
  64361. }
  64362. }
  64363. this._textures = {};
  64364. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures, notBoundToMesh);
  64365. };
  64366. /**
  64367. * Serializes this material in a JSON representation
  64368. * @returns the serialized material object
  64369. */
  64370. ShaderMaterial.prototype.serialize = function () {
  64371. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  64372. serializationObject.customType = "BABYLON.ShaderMaterial";
  64373. serializationObject.options = this._options;
  64374. serializationObject.shaderPath = this._shaderPath;
  64375. var name;
  64376. // Texture
  64377. serializationObject.textures = {};
  64378. for (name in this._textures) {
  64379. serializationObject.textures[name] = this._textures[name].serialize();
  64380. }
  64381. // Texture arrays
  64382. serializationObject.textureArrays = {};
  64383. for (name in this._textureArrays) {
  64384. serializationObject.textureArrays[name] = [];
  64385. var array = this._textureArrays[name];
  64386. for (var index = 0; index < array.length; index++) {
  64387. serializationObject.textureArrays[name].push(array[index].serialize());
  64388. }
  64389. }
  64390. // Float
  64391. serializationObject.floats = {};
  64392. for (name in this._floats) {
  64393. serializationObject.floats[name] = this._floats[name];
  64394. }
  64395. // Float s
  64396. serializationObject.FloatArrays = {};
  64397. for (name in this._floatsArrays) {
  64398. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  64399. }
  64400. // Color3
  64401. serializationObject.colors3 = {};
  64402. for (name in this._colors3) {
  64403. serializationObject.colors3[name] = this._colors3[name].asArray();
  64404. }
  64405. // Color3 array
  64406. serializationObject.colors3Arrays = {};
  64407. for (name in this._colors3Arrays) {
  64408. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  64409. }
  64410. // Color4
  64411. serializationObject.colors4 = {};
  64412. for (name in this._colors4) {
  64413. serializationObject.colors4[name] = this._colors4[name].asArray();
  64414. }
  64415. // Vector2
  64416. serializationObject.vectors2 = {};
  64417. for (name in this._vectors2) {
  64418. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  64419. }
  64420. // Vector3
  64421. serializationObject.vectors3 = {};
  64422. for (name in this._vectors3) {
  64423. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  64424. }
  64425. // Vector4
  64426. serializationObject.vectors4 = {};
  64427. for (name in this._vectors4) {
  64428. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  64429. }
  64430. // Matrix
  64431. serializationObject.matrices = {};
  64432. for (name in this._matrices) {
  64433. serializationObject.matrices[name] = this._matrices[name].asArray();
  64434. }
  64435. // Matrix 3x3
  64436. serializationObject.matrices3x3 = {};
  64437. for (name in this._matrices3x3) {
  64438. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  64439. }
  64440. // Matrix 2x2
  64441. serializationObject.matrices2x2 = {};
  64442. for (name in this._matrices2x2) {
  64443. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  64444. }
  64445. // Vector2Array
  64446. serializationObject.vectors2Arrays = {};
  64447. for (name in this._vectors2Arrays) {
  64448. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  64449. }
  64450. // Vector3Array
  64451. serializationObject.vectors3Arrays = {};
  64452. for (name in this._vectors3Arrays) {
  64453. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  64454. }
  64455. return serializationObject;
  64456. };
  64457. /**
  64458. * Creates a shader material from parsed shader material data
  64459. * @param source defines the JSON represnetation of the material
  64460. * @param scene defines the hosting scene
  64461. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  64462. * @returns a new material
  64463. */
  64464. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  64465. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  64466. var name;
  64467. // Texture
  64468. for (name in source.textures) {
  64469. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  64470. }
  64471. // Texture arrays
  64472. for (name in source.textureArrays) {
  64473. var array = source.textureArrays[name];
  64474. var textureArray = new Array();
  64475. for (var index = 0; index < array.length; index++) {
  64476. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  64477. }
  64478. material.setTextureArray(name, textureArray);
  64479. }
  64480. // Float
  64481. for (name in source.floats) {
  64482. material.setFloat(name, source.floats[name]);
  64483. }
  64484. // Float s
  64485. for (name in source.floatsArrays) {
  64486. material.setFloats(name, source.floatsArrays[name]);
  64487. }
  64488. // Color3
  64489. for (name in source.colors3) {
  64490. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  64491. }
  64492. // Color3 arrays
  64493. for (name in source.colors3Arrays) {
  64494. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  64495. if (i % 3 === 0) {
  64496. arr.push([num]);
  64497. }
  64498. else {
  64499. arr[arr.length - 1].push(num);
  64500. }
  64501. return arr;
  64502. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  64503. material.setColor3Array(name, colors);
  64504. }
  64505. // Color4
  64506. for (name in source.colors4) {
  64507. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  64508. }
  64509. // Vector2
  64510. for (name in source.vectors2) {
  64511. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  64512. }
  64513. // Vector3
  64514. for (name in source.vectors3) {
  64515. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  64516. }
  64517. // Vector4
  64518. for (name in source.vectors4) {
  64519. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  64520. }
  64521. // Matrix
  64522. for (name in source.matrices) {
  64523. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  64524. }
  64525. // Matrix 3x3
  64526. for (name in source.matrices3x3) {
  64527. material.setMatrix3x3(name, source.matrices3x3[name]);
  64528. }
  64529. // Matrix 2x2
  64530. for (name in source.matrices2x2) {
  64531. material.setMatrix2x2(name, source.matrices2x2[name]);
  64532. }
  64533. // Vector2Array
  64534. for (name in source.vectors2Arrays) {
  64535. material.setArray2(name, source.vectors2Arrays[name]);
  64536. }
  64537. // Vector3Array
  64538. for (name in source.vectors3Arrays) {
  64539. material.setArray3(name, source.vectors3Arrays[name]);
  64540. }
  64541. return material;
  64542. };
  64543. return ShaderMaterial;
  64544. }(BABYLON.Material));
  64545. BABYLON.ShaderMaterial = ShaderMaterial;
  64546. })(BABYLON || (BABYLON = {}));
  64547. //# sourceMappingURL=shaderMaterial.js.map
  64548. var BABYLON;
  64549. (function (BABYLON) {
  64550. /**
  64551. * Mesh representing the gorund
  64552. */
  64553. var GroundMesh = /** @class */ (function (_super) {
  64554. __extends(GroundMesh, _super);
  64555. function GroundMesh(name, scene) {
  64556. var _this = _super.call(this, name, scene) || this;
  64557. /** If octree should be generated */
  64558. _this.generateOctree = false;
  64559. return _this;
  64560. }
  64561. /**
  64562. * "GroundMesh"
  64563. * @returns "GroundMesh"
  64564. */
  64565. GroundMesh.prototype.getClassName = function () {
  64566. return "GroundMesh";
  64567. };
  64568. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  64569. /**
  64570. * The minimum of x and y subdivisions
  64571. */
  64572. get: function () {
  64573. return Math.min(this._subdivisionsX, this._subdivisionsY);
  64574. },
  64575. enumerable: true,
  64576. configurable: true
  64577. });
  64578. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  64579. /**
  64580. * X subdivisions
  64581. */
  64582. get: function () {
  64583. return this._subdivisionsX;
  64584. },
  64585. enumerable: true,
  64586. configurable: true
  64587. });
  64588. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  64589. /**
  64590. * Y subdivisions
  64591. */
  64592. get: function () {
  64593. return this._subdivisionsY;
  64594. },
  64595. enumerable: true,
  64596. configurable: true
  64597. });
  64598. /**
  64599. * This function will update an octree to help to select the right submeshes for rendering, picking and collision computations.
  64600. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  64601. * @param chunksCount the number of subdivisions for x and y
  64602. * @param octreeBlocksSize (Default: 32)
  64603. */
  64604. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  64605. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  64606. this._subdivisionsX = chunksCount;
  64607. this._subdivisionsY = chunksCount;
  64608. this.subdivide(chunksCount);
  64609. // Call the octree system optimization if it is defined.
  64610. var thisAsAny = this;
  64611. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  64612. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  64613. }
  64614. };
  64615. /**
  64616. * Returns a height (y) value in the Worl system :
  64617. * the ground altitude at the coordinates (x, z) expressed in the World system.
  64618. * @param x x coordinate
  64619. * @param z z coordinate
  64620. * @returns the ground y position if (x, z) are outside the ground surface.
  64621. */
  64622. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  64623. var world = this.getWorldMatrix();
  64624. var invMat = BABYLON.Tmp.Matrix[5];
  64625. world.invertToRef(invMat);
  64626. var tmpVect = BABYLON.Tmp.Vector3[8];
  64627. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  64628. x = tmpVect.x;
  64629. z = tmpVect.z;
  64630. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  64631. return this.position.y;
  64632. }
  64633. if (!this._heightQuads || this._heightQuads.length == 0) {
  64634. this._initHeightQuads();
  64635. this._computeHeightQuads();
  64636. }
  64637. var facet = this._getFacetAt(x, z);
  64638. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  64639. // return y in the World system
  64640. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  64641. return tmpVect.y;
  64642. };
  64643. /**
  64644. * Returns a normalized vector (Vector3) orthogonal to the ground
  64645. * at the ground coordinates (x, z) expressed in the World system.
  64646. * @param x x coordinate
  64647. * @param z z coordinate
  64648. * @returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  64649. */
  64650. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  64651. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  64652. this.getNormalAtCoordinatesToRef(x, z, normal);
  64653. return normal;
  64654. };
  64655. /**
  64656. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  64657. * at the ground coordinates (x, z) expressed in the World system.
  64658. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  64659. * @param x x coordinate
  64660. * @param z z coordinate
  64661. * @param ref vector to store the result
  64662. * @returns the GroundMesh.
  64663. */
  64664. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  64665. var world = this.getWorldMatrix();
  64666. var tmpMat = BABYLON.Tmp.Matrix[5];
  64667. world.invertToRef(tmpMat);
  64668. var tmpVect = BABYLON.Tmp.Vector3[8];
  64669. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  64670. x = tmpVect.x;
  64671. z = tmpVect.z;
  64672. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  64673. return this;
  64674. }
  64675. if (!this._heightQuads || this._heightQuads.length == 0) {
  64676. this._initHeightQuads();
  64677. this._computeHeightQuads();
  64678. }
  64679. var facet = this._getFacetAt(x, z);
  64680. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  64681. return this;
  64682. };
  64683. /**
  64684. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  64685. * if the ground has been updated.
  64686. * This can be used in the render loop.
  64687. * @returns the GroundMesh.
  64688. */
  64689. GroundMesh.prototype.updateCoordinateHeights = function () {
  64690. if (!this._heightQuads || this._heightQuads.length == 0) {
  64691. this._initHeightQuads();
  64692. }
  64693. this._computeHeightQuads();
  64694. return this;
  64695. };
  64696. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  64697. GroundMesh.prototype._getFacetAt = function (x, z) {
  64698. // retrieve col and row from x, z coordinates in the ground local system
  64699. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  64700. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  64701. var quad = this._heightQuads[row * this._subdivisionsX + col];
  64702. var facet;
  64703. if (z < quad.slope.x * x + quad.slope.y) {
  64704. facet = quad.facet1;
  64705. }
  64706. else {
  64707. facet = quad.facet2;
  64708. }
  64709. return facet;
  64710. };
  64711. // Creates and populates the heightMap array with "facet" elements :
  64712. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  64713. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  64714. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  64715. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  64716. // Returns the GroundMesh.
  64717. GroundMesh.prototype._initHeightQuads = function () {
  64718. var subdivisionsX = this._subdivisionsX;
  64719. var subdivisionsY = this._subdivisionsY;
  64720. this._heightQuads = new Array();
  64721. for (var row = 0; row < subdivisionsY; row++) {
  64722. for (var col = 0; col < subdivisionsX; col++) {
  64723. 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) };
  64724. this._heightQuads[row * subdivisionsX + col] = quad;
  64725. }
  64726. }
  64727. return this;
  64728. };
  64729. // Compute each quad element values and update the the heightMap array :
  64730. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  64731. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  64732. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  64733. // Returns the GroundMesh.
  64734. GroundMesh.prototype._computeHeightQuads = function () {
  64735. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64736. if (!positions) {
  64737. return this;
  64738. }
  64739. var v1 = BABYLON.Tmp.Vector3[3];
  64740. var v2 = BABYLON.Tmp.Vector3[2];
  64741. var v3 = BABYLON.Tmp.Vector3[1];
  64742. var v4 = BABYLON.Tmp.Vector3[0];
  64743. var v1v2 = BABYLON.Tmp.Vector3[4];
  64744. var v1v3 = BABYLON.Tmp.Vector3[5];
  64745. var v1v4 = BABYLON.Tmp.Vector3[6];
  64746. var norm1 = BABYLON.Tmp.Vector3[7];
  64747. var norm2 = BABYLON.Tmp.Vector3[8];
  64748. var i = 0;
  64749. var j = 0;
  64750. var k = 0;
  64751. var cd = 0; // 2D slope coefficient : z = cd * x + h
  64752. var h = 0;
  64753. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  64754. var d2 = 0;
  64755. var subdivisionsX = this._subdivisionsX;
  64756. var subdivisionsY = this._subdivisionsY;
  64757. for (var row = 0; row < subdivisionsY; row++) {
  64758. for (var col = 0; col < subdivisionsX; col++) {
  64759. i = col * 3;
  64760. j = row * (subdivisionsX + 1) * 3;
  64761. k = (row + 1) * (subdivisionsX + 1) * 3;
  64762. v1.x = positions[j + i];
  64763. v1.y = positions[j + i + 1];
  64764. v1.z = positions[j + i + 2];
  64765. v2.x = positions[j + i + 3];
  64766. v2.y = positions[j + i + 4];
  64767. v2.z = positions[j + i + 5];
  64768. v3.x = positions[k + i];
  64769. v3.y = positions[k + i + 1];
  64770. v3.z = positions[k + i + 2];
  64771. v4.x = positions[k + i + 3];
  64772. v4.y = positions[k + i + 4];
  64773. v4.z = positions[k + i + 5];
  64774. // 2D slope V1V4
  64775. cd = (v4.z - v1.z) / (v4.x - v1.x);
  64776. h = v1.z - cd * v1.x; // v1 belongs to the slope
  64777. // facet equations :
  64778. // we compute each facet normal vector
  64779. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  64780. // we compute the value d by applying the equation to v1 which belongs to the plane
  64781. // then we store the facet equation in a Vector4
  64782. v2.subtractToRef(v1, v1v2);
  64783. v3.subtractToRef(v1, v1v3);
  64784. v4.subtractToRef(v1, v1v4);
  64785. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  64786. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  64787. norm1.normalize();
  64788. norm2.normalize();
  64789. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  64790. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  64791. var quad = this._heightQuads[row * subdivisionsX + col];
  64792. quad.slope.copyFromFloats(cd, h);
  64793. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  64794. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  64795. }
  64796. }
  64797. return this;
  64798. };
  64799. /**
  64800. * Serializes this ground mesh
  64801. * @param serializationObject object to write serialization to
  64802. */
  64803. GroundMesh.prototype.serialize = function (serializationObject) {
  64804. _super.prototype.serialize.call(this, serializationObject);
  64805. serializationObject.subdivisionsX = this._subdivisionsX;
  64806. serializationObject.subdivisionsY = this._subdivisionsY;
  64807. serializationObject.minX = this._minX;
  64808. serializationObject.maxX = this._maxX;
  64809. serializationObject.minZ = this._minZ;
  64810. serializationObject.maxZ = this._maxZ;
  64811. serializationObject.width = this._width;
  64812. serializationObject.height = this._height;
  64813. };
  64814. /**
  64815. * Parses a serialized ground mesh
  64816. * @param parsedMesh the serialized mesh
  64817. * @param scene the scene to create the ground mesh in
  64818. * @returns the created ground mesh
  64819. */
  64820. GroundMesh.Parse = function (parsedMesh, scene) {
  64821. var result = new GroundMesh(parsedMesh.name, scene);
  64822. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  64823. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  64824. result._minX = parsedMesh.minX;
  64825. result._maxX = parsedMesh.maxX;
  64826. result._minZ = parsedMesh.minZ;
  64827. result._maxZ = parsedMesh.maxZ;
  64828. result._width = parsedMesh.width;
  64829. result._height = parsedMesh.height;
  64830. return result;
  64831. };
  64832. return GroundMesh;
  64833. }(BABYLON.Mesh));
  64834. BABYLON.GroundMesh = GroundMesh;
  64835. })(BABYLON || (BABYLON = {}));
  64836. //# sourceMappingURL=groundMesh.js.map
  64837. var BABYLON;
  64838. (function (BABYLON) {
  64839. /**
  64840. * Creates an instance based on a source mesh.
  64841. */
  64842. var InstancedMesh = /** @class */ (function (_super) {
  64843. __extends(InstancedMesh, _super);
  64844. function InstancedMesh(name, source) {
  64845. var _this = _super.call(this, name, source.getScene()) || this;
  64846. /** @hidden */
  64847. _this._indexInSourceMeshInstanceArray = -1;
  64848. source.addInstance(_this);
  64849. _this._sourceMesh = source;
  64850. _this.position.copyFrom(source.position);
  64851. _this.rotation.copyFrom(source.rotation);
  64852. _this.scaling.copyFrom(source.scaling);
  64853. if (source.rotationQuaternion) {
  64854. _this.rotationQuaternion = source.rotationQuaternion.clone();
  64855. }
  64856. _this.infiniteDistance = source.infiniteDistance;
  64857. _this.setPivotMatrix(source.getPivotMatrix());
  64858. _this.refreshBoundingInfo();
  64859. _this._syncSubMeshes();
  64860. return _this;
  64861. }
  64862. /**
  64863. * Returns the string "InstancedMesh".
  64864. */
  64865. InstancedMesh.prototype.getClassName = function () {
  64866. return "InstancedMesh";
  64867. };
  64868. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  64869. // Methods
  64870. /**
  64871. * If the source mesh receives shadows
  64872. */
  64873. get: function () {
  64874. return this._sourceMesh.receiveShadows;
  64875. },
  64876. enumerable: true,
  64877. configurable: true
  64878. });
  64879. Object.defineProperty(InstancedMesh.prototype, "material", {
  64880. /**
  64881. * The material of the source mesh
  64882. */
  64883. get: function () {
  64884. return this._sourceMesh.material;
  64885. },
  64886. enumerable: true,
  64887. configurable: true
  64888. });
  64889. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  64890. /**
  64891. * Visibility of the source mesh
  64892. */
  64893. get: function () {
  64894. return this._sourceMesh.visibility;
  64895. },
  64896. enumerable: true,
  64897. configurable: true
  64898. });
  64899. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  64900. /**
  64901. * Skeleton of the source mesh
  64902. */
  64903. get: function () {
  64904. return this._sourceMesh.skeleton;
  64905. },
  64906. enumerable: true,
  64907. configurable: true
  64908. });
  64909. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  64910. /**
  64911. * Rendering ground id of the source mesh
  64912. */
  64913. get: function () {
  64914. return this._sourceMesh.renderingGroupId;
  64915. },
  64916. set: function (value) {
  64917. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  64918. return;
  64919. }
  64920. //no-op with warning
  64921. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  64922. },
  64923. enumerable: true,
  64924. configurable: true
  64925. });
  64926. /**
  64927. * Returns the total number of vertices (integer).
  64928. */
  64929. InstancedMesh.prototype.getTotalVertices = function () {
  64930. return this._sourceMesh.getTotalVertices();
  64931. };
  64932. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  64933. /**
  64934. * The source mesh of the instance
  64935. */
  64936. get: function () {
  64937. return this._sourceMesh;
  64938. },
  64939. enumerable: true,
  64940. configurable: true
  64941. });
  64942. /**
  64943. * Is this node ready to be used/rendered
  64944. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  64945. * @return {boolean} is it ready
  64946. */
  64947. InstancedMesh.prototype.isReady = function (completeCheck) {
  64948. if (completeCheck === void 0) { completeCheck = false; }
  64949. return this._sourceMesh.isReady(completeCheck, true);
  64950. };
  64951. /**
  64952. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  64953. * @param kind kind of verticies to retreive (eg. positons, normals, uvs, etc.)
  64954. * @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.
  64955. * @returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  64956. */
  64957. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  64958. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  64959. };
  64960. /**
  64961. * Sets the vertex data of the mesh geometry for the requested `kind`.
  64962. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  64963. * The `data` are either a numeric array either a Float32Array.
  64964. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  64965. * 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).
  64966. * Note that a new underlying VertexBuffer object is created each call.
  64967. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  64968. *
  64969. * Possible `kind` values :
  64970. * - BABYLON.VertexBuffer.PositionKind
  64971. * - BABYLON.VertexBuffer.UVKind
  64972. * - BABYLON.VertexBuffer.UV2Kind
  64973. * - BABYLON.VertexBuffer.UV3Kind
  64974. * - BABYLON.VertexBuffer.UV4Kind
  64975. * - BABYLON.VertexBuffer.UV5Kind
  64976. * - BABYLON.VertexBuffer.UV6Kind
  64977. * - BABYLON.VertexBuffer.ColorKind
  64978. * - BABYLON.VertexBuffer.MatricesIndicesKind
  64979. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  64980. * - BABYLON.VertexBuffer.MatricesWeightsKind
  64981. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  64982. *
  64983. * Returns the Mesh.
  64984. */
  64985. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  64986. if (this.sourceMesh) {
  64987. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  64988. }
  64989. return this.sourceMesh;
  64990. };
  64991. /**
  64992. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  64993. * If the mesh has no geometry, it is simply returned as it is.
  64994. * The `data` are either a numeric array either a Float32Array.
  64995. * No new underlying VertexBuffer object is created.
  64996. * 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.
  64997. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  64998. *
  64999. * Possible `kind` values :
  65000. * - BABYLON.VertexBuffer.PositionKind
  65001. * - BABYLON.VertexBuffer.UVKind
  65002. * - BABYLON.VertexBuffer.UV2Kind
  65003. * - BABYLON.VertexBuffer.UV3Kind
  65004. * - BABYLON.VertexBuffer.UV4Kind
  65005. * - BABYLON.VertexBuffer.UV5Kind
  65006. * - BABYLON.VertexBuffer.UV6Kind
  65007. * - BABYLON.VertexBuffer.ColorKind
  65008. * - BABYLON.VertexBuffer.MatricesIndicesKind
  65009. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  65010. * - BABYLON.VertexBuffer.MatricesWeightsKind
  65011. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  65012. *
  65013. * Returns the Mesh.
  65014. */
  65015. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  65016. if (this.sourceMesh) {
  65017. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  65018. }
  65019. return this.sourceMesh;
  65020. };
  65021. /**
  65022. * Sets the mesh indices.
  65023. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  65024. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  65025. * This method creates a new index buffer each call.
  65026. * Returns the Mesh.
  65027. */
  65028. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  65029. if (totalVertices === void 0) { totalVertices = null; }
  65030. if (this.sourceMesh) {
  65031. this.sourceMesh.setIndices(indices, totalVertices);
  65032. }
  65033. return this.sourceMesh;
  65034. };
  65035. /**
  65036. * Boolean : True if the mesh owns the requested kind of data.
  65037. */
  65038. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  65039. return this._sourceMesh.isVerticesDataPresent(kind);
  65040. };
  65041. /**
  65042. * Returns an array of indices (IndicesArray).
  65043. */
  65044. InstancedMesh.prototype.getIndices = function () {
  65045. return this._sourceMesh.getIndices();
  65046. };
  65047. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  65048. get: function () {
  65049. return this._sourceMesh._positions;
  65050. },
  65051. enumerable: true,
  65052. configurable: true
  65053. });
  65054. /**
  65055. * reconstructs and updates the BoundingInfo of the mesh.
  65056. * @returns the mesh.
  65057. */
  65058. InstancedMesh.prototype.refreshBoundingInfo = function () {
  65059. var meshBB = this._sourceMesh.getBoundingInfo();
  65060. if (this._boundingInfo) {
  65061. this._boundingInfo.reConstruct(meshBB.minimum, meshBB.maximum);
  65062. }
  65063. else {
  65064. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum, meshBB.maximum);
  65065. }
  65066. this._updateBoundingInfo();
  65067. return this;
  65068. };
  65069. /** @hidden */
  65070. InstancedMesh.prototype._preActivate = function () {
  65071. if (this._currentLOD) {
  65072. this._currentLOD._preActivate();
  65073. }
  65074. return this;
  65075. };
  65076. /** @hidden */
  65077. InstancedMesh.prototype._activate = function (renderId) {
  65078. if (this._currentLOD) {
  65079. this._currentLOD._registerInstanceForRenderId(this, renderId);
  65080. }
  65081. return this;
  65082. };
  65083. /**
  65084. * Returns the current associated LOD AbstractMesh.
  65085. */
  65086. InstancedMesh.prototype.getLOD = function (camera) {
  65087. if (!camera) {
  65088. return this;
  65089. }
  65090. var boundingInfo = this.getBoundingInfo();
  65091. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  65092. if (this._currentLOD === this.sourceMesh) {
  65093. return this;
  65094. }
  65095. return this._currentLOD;
  65096. };
  65097. /** @hidden */
  65098. InstancedMesh.prototype._syncSubMeshes = function () {
  65099. this.releaseSubMeshes();
  65100. if (this._sourceMesh.subMeshes) {
  65101. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  65102. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  65103. }
  65104. }
  65105. return this;
  65106. };
  65107. /** @hidden */
  65108. InstancedMesh.prototype._generatePointsArray = function () {
  65109. return this._sourceMesh._generatePointsArray();
  65110. };
  65111. /**
  65112. * Creates a new InstancedMesh from the current mesh.
  65113. * - name (string) : the cloned mesh name
  65114. * - newParent (optional Node) : the optional Node to parent the clone to.
  65115. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  65116. *
  65117. * Returns the clone.
  65118. */
  65119. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  65120. var result = this._sourceMesh.createInstance(name);
  65121. // Deep copy
  65122. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  65123. // Bounding info
  65124. this.refreshBoundingInfo();
  65125. // Parent
  65126. if (newParent) {
  65127. result.parent = newParent;
  65128. }
  65129. if (!doNotCloneChildren) {
  65130. // Children
  65131. for (var index = 0; index < this.getScene().meshes.length; index++) {
  65132. var mesh = this.getScene().meshes[index];
  65133. if (mesh.parent === this) {
  65134. mesh.clone(mesh.name, result);
  65135. }
  65136. }
  65137. }
  65138. result.computeWorldMatrix(true);
  65139. return result;
  65140. };
  65141. /**
  65142. * Disposes the InstancedMesh.
  65143. * Returns nothing.
  65144. */
  65145. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  65146. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  65147. // Remove from mesh
  65148. this._sourceMesh.removeInstance(this);
  65149. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  65150. };
  65151. return InstancedMesh;
  65152. }(BABYLON.AbstractMesh));
  65153. BABYLON.InstancedMesh = InstancedMesh;
  65154. })(BABYLON || (BABYLON = {}));
  65155. //# sourceMappingURL=instancedMesh.js.map
  65156. var BABYLON;
  65157. (function (BABYLON) {
  65158. /**
  65159. * Line mesh
  65160. * @see https://doc.babylonjs.com/babylon101/parametric_shapes
  65161. */
  65162. var LinesMesh = /** @class */ (function (_super) {
  65163. __extends(LinesMesh, _super);
  65164. /**
  65165. * Creates a new LinesMesh
  65166. * @param name defines the name
  65167. * @param scene defines the hosting scene
  65168. * @param parent defines the parent mesh if any
  65169. * @param source defines the optional source LinesMesh used to clone data from
  65170. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  65171. * When false, achieved by calling a clone(), also passing False.
  65172. * This will make creation of children, recursive.
  65173. * @param useVertexColor defines if this LinesMesh supports vertex color
  65174. * @param useVertexAlpha defines if this LinesMesh supports vertex alpha
  65175. */
  65176. function LinesMesh(name, scene, parent, source, doNotCloneChildren,
  65177. /**
  65178. * If vertex color should be applied to the mesh
  65179. */
  65180. useVertexColor,
  65181. /**
  65182. * If vertex alpha should be applied to the mesh
  65183. */
  65184. useVertexAlpha) {
  65185. if (scene === void 0) { scene = null; }
  65186. if (parent === void 0) { parent = null; }
  65187. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  65188. _this.useVertexColor = useVertexColor;
  65189. _this.useVertexAlpha = useVertexAlpha;
  65190. /**
  65191. * Color of the line (Default: White)
  65192. */
  65193. _this.color = new BABYLON.Color3(1, 1, 1);
  65194. /**
  65195. * Alpha of the line (Default: 1)
  65196. */
  65197. _this.alpha = 1;
  65198. if (source) {
  65199. _this.color = source.color.clone();
  65200. _this.alpha = source.alpha;
  65201. _this.useVertexColor = source.useVertexColor;
  65202. _this.useVertexAlpha = source.useVertexAlpha;
  65203. }
  65204. _this._intersectionThreshold = 0.1;
  65205. var defines = [];
  65206. var options = {
  65207. attributes: [BABYLON.VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"],
  65208. uniforms: ["world", "viewProjection"],
  65209. needAlphaBlending: true,
  65210. defines: defines
  65211. };
  65212. if (useVertexAlpha === false) {
  65213. options.needAlphaBlending = false;
  65214. }
  65215. if (!useVertexColor) {
  65216. options.uniforms.push("color");
  65217. }
  65218. else {
  65219. options.defines.push("#define VERTEXCOLOR");
  65220. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  65221. }
  65222. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  65223. return _this;
  65224. }
  65225. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  65226. /**
  65227. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  65228. * This margin is expressed in world space coordinates, so its value may vary.
  65229. * Default value is 0.1
  65230. * @returns the intersection Threshold value.
  65231. */
  65232. get: function () {
  65233. return this._intersectionThreshold;
  65234. },
  65235. /**
  65236. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  65237. * This margin is expressed in world space coordinates, so its value may vary.
  65238. */
  65239. set: function (value) {
  65240. if (this._intersectionThreshold === value) {
  65241. return;
  65242. }
  65243. this._intersectionThreshold = value;
  65244. },
  65245. enumerable: true,
  65246. configurable: true
  65247. });
  65248. /**
  65249. * Returns the string "LineMesh"
  65250. */
  65251. LinesMesh.prototype.getClassName = function () {
  65252. return "LinesMesh";
  65253. };
  65254. Object.defineProperty(LinesMesh.prototype, "material", {
  65255. /**
  65256. * @hidden
  65257. */
  65258. get: function () {
  65259. return this._colorShader;
  65260. },
  65261. /**
  65262. * @hidden
  65263. */
  65264. set: function (value) {
  65265. // Do nothing
  65266. },
  65267. enumerable: true,
  65268. configurable: true
  65269. });
  65270. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  65271. /**
  65272. * @hidden
  65273. */
  65274. get: function () {
  65275. return false;
  65276. },
  65277. enumerable: true,
  65278. configurable: true
  65279. });
  65280. /** @hidden */
  65281. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  65282. if (!this._geometry) {
  65283. return this;
  65284. }
  65285. // VBOs
  65286. this._geometry._bind(this._colorShader.getEffect());
  65287. // Color
  65288. if (!this.useVertexColor) {
  65289. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  65290. }
  65291. return this;
  65292. };
  65293. /** @hidden */
  65294. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  65295. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  65296. return this;
  65297. }
  65298. var engine = this.getScene().getEngine();
  65299. // Draw order
  65300. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  65301. return this;
  65302. };
  65303. /**
  65304. * Disposes of the line mesh
  65305. * @param doNotRecurse If children should be disposed
  65306. */
  65307. LinesMesh.prototype.dispose = function (doNotRecurse) {
  65308. this._colorShader.dispose(false, false, true);
  65309. _super.prototype.dispose.call(this, doNotRecurse);
  65310. };
  65311. /**
  65312. * Returns a new LineMesh object cloned from the current one.
  65313. */
  65314. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  65315. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  65316. };
  65317. return LinesMesh;
  65318. }(BABYLON.Mesh));
  65319. BABYLON.LinesMesh = LinesMesh;
  65320. })(BABYLON || (BABYLON = {}));
  65321. //# sourceMappingURL=linesMesh.js.map
  65322. var BABYLON;
  65323. (function (BABYLON) {
  65324. /**
  65325. * This class implement a typical dictionary using a string as key and the generic type T as value.
  65326. * The underlying implementation relies on an associative array to ensure the best performances.
  65327. * The value can be anything including 'null' but except 'undefined'
  65328. */
  65329. var StringDictionary = /** @class */ (function () {
  65330. function StringDictionary() {
  65331. this._count = 0;
  65332. this._data = {};
  65333. }
  65334. /**
  65335. * This will clear this dictionary and copy the content from the 'source' one.
  65336. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  65337. * @param source the dictionary to take the content from and copy to this dictionary
  65338. */
  65339. StringDictionary.prototype.copyFrom = function (source) {
  65340. var _this = this;
  65341. this.clear();
  65342. source.forEach(function (t, v) { return _this.add(t, v); });
  65343. };
  65344. /**
  65345. * Get a value based from its key
  65346. * @param key the given key to get the matching value from
  65347. * @return the value if found, otherwise undefined is returned
  65348. */
  65349. StringDictionary.prototype.get = function (key) {
  65350. var val = this._data[key];
  65351. if (val !== undefined) {
  65352. return val;
  65353. }
  65354. return undefined;
  65355. };
  65356. /**
  65357. * Get a value from its key or add it if it doesn't exist.
  65358. * This method will ensure you that a given key/data will be present in the dictionary.
  65359. * @param key the given key to get the matching value from
  65360. * @param factory the factory that will create the value if the key is not present in the dictionary.
  65361. * The factory will only be invoked if there's no data for the given key.
  65362. * @return the value corresponding to the key.
  65363. */
  65364. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  65365. var val = this.get(key);
  65366. if (val !== undefined) {
  65367. return val;
  65368. }
  65369. val = factory(key);
  65370. if (val) {
  65371. this.add(key, val);
  65372. }
  65373. return val;
  65374. };
  65375. /**
  65376. * Get a value from its key if present in the dictionary otherwise add it
  65377. * @param key the key to get the value from
  65378. * @param val if there's no such key/value pair in the dictionary add it with this value
  65379. * @return the value corresponding to the key
  65380. */
  65381. StringDictionary.prototype.getOrAdd = function (key, val) {
  65382. var curVal = this.get(key);
  65383. if (curVal !== undefined) {
  65384. return curVal;
  65385. }
  65386. this.add(key, val);
  65387. return val;
  65388. };
  65389. /**
  65390. * Check if there's a given key in the dictionary
  65391. * @param key the key to check for
  65392. * @return true if the key is present, false otherwise
  65393. */
  65394. StringDictionary.prototype.contains = function (key) {
  65395. return this._data[key] !== undefined;
  65396. };
  65397. /**
  65398. * Add a new key and its corresponding value
  65399. * @param key the key to add
  65400. * @param value the value corresponding to the key
  65401. * @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
  65402. */
  65403. StringDictionary.prototype.add = function (key, value) {
  65404. if (this._data[key] !== undefined) {
  65405. return false;
  65406. }
  65407. this._data[key] = value;
  65408. ++this._count;
  65409. return true;
  65410. };
  65411. /**
  65412. * Update a specific value associated to a key
  65413. * @param key defines the key to use
  65414. * @param value defines the value to store
  65415. * @returns true if the value was updated (or false if the key was not found)
  65416. */
  65417. StringDictionary.prototype.set = function (key, value) {
  65418. if (this._data[key] === undefined) {
  65419. return false;
  65420. }
  65421. this._data[key] = value;
  65422. return true;
  65423. };
  65424. /**
  65425. * Get the element of the given key and remove it from the dictionary
  65426. * @param key defines the key to search
  65427. * @returns the value associated with the key or null if not found
  65428. */
  65429. StringDictionary.prototype.getAndRemove = function (key) {
  65430. var val = this.get(key);
  65431. if (val !== undefined) {
  65432. delete this._data[key];
  65433. --this._count;
  65434. return val;
  65435. }
  65436. return null;
  65437. };
  65438. /**
  65439. * Remove a key/value from the dictionary.
  65440. * @param key the key to remove
  65441. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  65442. */
  65443. StringDictionary.prototype.remove = function (key) {
  65444. if (this.contains(key)) {
  65445. delete this._data[key];
  65446. --this._count;
  65447. return true;
  65448. }
  65449. return false;
  65450. };
  65451. /**
  65452. * Clear the whole content of the dictionary
  65453. */
  65454. StringDictionary.prototype.clear = function () {
  65455. this._data = {};
  65456. this._count = 0;
  65457. };
  65458. Object.defineProperty(StringDictionary.prototype, "count", {
  65459. /**
  65460. * Gets the current count
  65461. */
  65462. get: function () {
  65463. return this._count;
  65464. },
  65465. enumerable: true,
  65466. configurable: true
  65467. });
  65468. /**
  65469. * Execute a callback on each key/val of the dictionary.
  65470. * Note that you can remove any element in this dictionary in the callback implementation
  65471. * @param callback the callback to execute on a given key/value pair
  65472. */
  65473. StringDictionary.prototype.forEach = function (callback) {
  65474. for (var cur in this._data) {
  65475. var val = this._data[cur];
  65476. callback(cur, val);
  65477. }
  65478. };
  65479. /**
  65480. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  65481. * If the callback returns null or undefined the method will iterate to the next key/value pair
  65482. * Note that you can remove any element in this dictionary in the callback implementation
  65483. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  65484. * @returns the first item
  65485. */
  65486. StringDictionary.prototype.first = function (callback) {
  65487. for (var cur in this._data) {
  65488. var val = this._data[cur];
  65489. var res = callback(cur, val);
  65490. if (res) {
  65491. return res;
  65492. }
  65493. }
  65494. return null;
  65495. };
  65496. return StringDictionary;
  65497. }());
  65498. BABYLON.StringDictionary = StringDictionary;
  65499. })(BABYLON || (BABYLON = {}));
  65500. //# sourceMappingURL=stringDictionary.js.map
  65501. var BABYLON;
  65502. (function (BABYLON) {
  65503. var Debug;
  65504. (function (Debug) {
  65505. /**
  65506. * Class used to render a debug view of a given skeleton
  65507. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  65508. */
  65509. var SkeletonViewer = /** @class */ (function () {
  65510. /**
  65511. * Creates a new SkeletonViewer
  65512. * @param skeleton defines the skeleton to render
  65513. * @param mesh defines the mesh attached to the skeleton
  65514. * @param scene defines the hosting scene
  65515. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  65516. * @param renderingGroupId defines the rendering group id to use with the viewer
  65517. * @param utilityLayerRenderer defines an optional utility layer to render the helper on
  65518. */
  65519. function SkeletonViewer(
  65520. /** defines the skeleton to render */
  65521. skeleton,
  65522. /** defines the mesh attached to the skeleton */
  65523. mesh, scene,
  65524. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  65525. autoUpdateBonesMatrices,
  65526. /** defines the rendering group id to use with the viewer */
  65527. renderingGroupId,
  65528. /** defines an optional utility layer to render the helper on */
  65529. utilityLayerRenderer) {
  65530. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  65531. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  65532. this.skeleton = skeleton;
  65533. this.mesh = mesh;
  65534. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  65535. this.renderingGroupId = renderingGroupId;
  65536. this.utilityLayerRenderer = utilityLayerRenderer;
  65537. /** Gets or sets the color used to render the skeleton */
  65538. this.color = BABYLON.Color3.White();
  65539. this._debugLines = new Array();
  65540. this._isEnabled = false;
  65541. this._scene = scene;
  65542. this.update();
  65543. this._renderFunction = this.update.bind(this);
  65544. }
  65545. Object.defineProperty(SkeletonViewer.prototype, "debugMesh", {
  65546. /**
  65547. * Returns the mesh used to render the bones
  65548. */
  65549. get: function () {
  65550. return this._debugMesh;
  65551. },
  65552. enumerable: true,
  65553. configurable: true
  65554. });
  65555. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  65556. get: function () {
  65557. return this._isEnabled;
  65558. },
  65559. /** Gets or sets a boolean indicating if the viewer is enabled */
  65560. set: function (value) {
  65561. if (this._isEnabled === value) {
  65562. return;
  65563. }
  65564. this._isEnabled = value;
  65565. if (value) {
  65566. this._scene.registerBeforeRender(this._renderFunction);
  65567. }
  65568. else {
  65569. this._scene.unregisterBeforeRender(this._renderFunction);
  65570. }
  65571. },
  65572. enumerable: true,
  65573. configurable: true
  65574. });
  65575. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  65576. if (x === void 0) { x = 0; }
  65577. if (y === void 0) { y = 0; }
  65578. if (z === void 0) { z = 0; }
  65579. var tmat = BABYLON.Tmp.Matrix[0];
  65580. var parentBone = bone.getParent();
  65581. tmat.copyFrom(bone.getLocalMatrix());
  65582. if (x !== 0 || y !== 0 || z !== 0) {
  65583. var tmat2 = BABYLON.Tmp.Matrix[1];
  65584. BABYLON.Matrix.IdentityToRef(tmat2);
  65585. tmat2.setTranslationFromFloats(x, y, z);
  65586. tmat2.multiplyToRef(tmat, tmat);
  65587. }
  65588. if (parentBone) {
  65589. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  65590. }
  65591. tmat.multiplyToRef(meshMat, tmat);
  65592. position.x = tmat.m[12];
  65593. position.y = tmat.m[13];
  65594. position.z = tmat.m[14];
  65595. };
  65596. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  65597. var len = bones.length;
  65598. var meshPos = this.mesh.position;
  65599. for (var i = 0; i < len; i++) {
  65600. var bone = bones[i];
  65601. var points = this._debugLines[i];
  65602. if (!points) {
  65603. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65604. this._debugLines[i] = points;
  65605. }
  65606. this._getBonePosition(points[0], bone, meshMat);
  65607. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  65608. points[0].subtractInPlace(meshPos);
  65609. points[1].subtractInPlace(meshPos);
  65610. }
  65611. };
  65612. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  65613. var len = bones.length;
  65614. var boneNum = 0;
  65615. var meshPos = this.mesh.position;
  65616. for (var i = len - 1; i >= 0; i--) {
  65617. var childBone = bones[i];
  65618. var parentBone = childBone.getParent();
  65619. if (!parentBone) {
  65620. continue;
  65621. }
  65622. var points = this._debugLines[boneNum];
  65623. if (!points) {
  65624. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65625. this._debugLines[boneNum] = points;
  65626. }
  65627. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  65628. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  65629. points[0].subtractInPlace(meshPos);
  65630. points[1].subtractInPlace(meshPos);
  65631. boneNum++;
  65632. }
  65633. };
  65634. /** Update the viewer to sync with current skeleton state */
  65635. SkeletonViewer.prototype.update = function () {
  65636. if (this.autoUpdateBonesMatrices) {
  65637. this.skeleton.computeAbsoluteTransforms();
  65638. }
  65639. if (this.skeleton.bones[0].length === undefined) {
  65640. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  65641. }
  65642. else {
  65643. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  65644. }
  65645. var targetScene = this.utilityLayerRenderer ? this.utilityLayerRenderer.utilityLayerScene : this._scene;
  65646. if (!this._debugMesh) {
  65647. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, targetScene);
  65648. this._debugMesh.renderingGroupId = this.renderingGroupId;
  65649. }
  65650. else {
  65651. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, targetScene);
  65652. }
  65653. this._debugMesh.position.copyFrom(this.mesh.position);
  65654. this._debugMesh.color = this.color;
  65655. };
  65656. /** Release associated resources */
  65657. SkeletonViewer.prototype.dispose = function () {
  65658. if (this._debugMesh) {
  65659. this.isEnabled = false;
  65660. this._debugMesh.dispose();
  65661. this._debugMesh = null;
  65662. }
  65663. };
  65664. return SkeletonViewer;
  65665. }());
  65666. Debug.SkeletonViewer = SkeletonViewer;
  65667. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  65668. })(BABYLON || (BABYLON = {}));
  65669. //# sourceMappingURL=skeletonViewer.js.map
  65670. /**
  65671. * Module Debug contains the (visual) components to debug a scene correctly
  65672. */
  65673. var BABYLON;
  65674. (function (BABYLON) {
  65675. var Debug;
  65676. (function (Debug) {
  65677. /**
  65678. * The Axes viewer will show 3 axes in a specific point in space
  65679. */
  65680. var AxesViewer = /** @class */ (function () {
  65681. /**
  65682. * Creates a new AxesViewer
  65683. * @param scene defines the hosting scene
  65684. * @param scaleLines defines a number used to scale line length (1 by default)
  65685. */
  65686. function AxesViewer(scene, scaleLines) {
  65687. if (scaleLines === void 0) { scaleLines = 1; }
  65688. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65689. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65690. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65691. /**
  65692. * Gets or sets a number used to scale line length
  65693. */
  65694. this.scaleLines = 1;
  65695. this.scaleLines = scaleLines;
  65696. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  65697. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  65698. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  65699. this._xmesh.renderingGroupId = 2;
  65700. this._ymesh.renderingGroupId = 2;
  65701. this._zmesh.renderingGroupId = 2;
  65702. this._xmesh.material.checkReadyOnlyOnce = true;
  65703. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  65704. this._ymesh.material.checkReadyOnlyOnce = true;
  65705. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  65706. this._zmesh.material.checkReadyOnlyOnce = true;
  65707. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  65708. this.scene = scene;
  65709. }
  65710. /**
  65711. * Force the viewer to update
  65712. * @param position defines the position of the viewer
  65713. * @param xaxis defines the x axis of the viewer
  65714. * @param yaxis defines the y axis of the viewer
  65715. * @param zaxis defines the z axis of the viewer
  65716. */
  65717. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  65718. var scaleLines = this.scaleLines;
  65719. if (this._xmesh) {
  65720. this._xmesh.position.copyFrom(position);
  65721. }
  65722. if (this._ymesh) {
  65723. this._ymesh.position.copyFrom(position);
  65724. }
  65725. if (this._zmesh) {
  65726. this._zmesh.position.copyFrom(position);
  65727. }
  65728. var point2 = this._xline[1];
  65729. point2.x = xaxis.x * scaleLines;
  65730. point2.y = xaxis.y * scaleLines;
  65731. point2.z = xaxis.z * scaleLines;
  65732. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  65733. point2 = this._yline[1];
  65734. point2.x = yaxis.x * scaleLines;
  65735. point2.y = yaxis.y * scaleLines;
  65736. point2.z = yaxis.z * scaleLines;
  65737. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  65738. point2 = this._zline[1];
  65739. point2.x = zaxis.x * scaleLines;
  65740. point2.y = zaxis.y * scaleLines;
  65741. point2.z = zaxis.z * scaleLines;
  65742. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  65743. };
  65744. /** Releases resources */
  65745. AxesViewer.prototype.dispose = function () {
  65746. if (this._xmesh) {
  65747. this._xmesh.dispose();
  65748. }
  65749. if (this._ymesh) {
  65750. this._ymesh.dispose();
  65751. }
  65752. if (this._zmesh) {
  65753. this._zmesh.dispose();
  65754. }
  65755. this._xmesh = null;
  65756. this._ymesh = null;
  65757. this._zmesh = null;
  65758. this.scene = null;
  65759. };
  65760. return AxesViewer;
  65761. }());
  65762. Debug.AxesViewer = AxesViewer;
  65763. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  65764. })(BABYLON || (BABYLON = {}));
  65765. //# sourceMappingURL=axesViewer.js.map
  65766. var BABYLON;
  65767. (function (BABYLON) {
  65768. var Debug;
  65769. (function (Debug) {
  65770. /**
  65771. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  65772. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  65773. */
  65774. var BoneAxesViewer = /** @class */ (function (_super) {
  65775. __extends(BoneAxesViewer, _super);
  65776. /**
  65777. * Creates a new BoneAxesViewer
  65778. * @param scene defines the hosting scene
  65779. * @param bone defines the target bone
  65780. * @param mesh defines the target mesh
  65781. * @param scaleLines defines a scaling factor for line length (1 by default)
  65782. */
  65783. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  65784. if (scaleLines === void 0) { scaleLines = 1; }
  65785. var _this = _super.call(this, scene, scaleLines) || this;
  65786. /** Gets current position */
  65787. _this.pos = BABYLON.Vector3.Zero();
  65788. /** Gets direction of X axis */
  65789. _this.xaxis = BABYLON.Vector3.Zero();
  65790. /** Gets direction of Y axis */
  65791. _this.yaxis = BABYLON.Vector3.Zero();
  65792. /** Gets direction of Z axis */
  65793. _this.zaxis = BABYLON.Vector3.Zero();
  65794. _this.mesh = mesh;
  65795. _this.bone = bone;
  65796. return _this;
  65797. }
  65798. /**
  65799. * Force the viewer to update
  65800. */
  65801. BoneAxesViewer.prototype.update = function () {
  65802. if (!this.mesh || !this.bone) {
  65803. return;
  65804. }
  65805. var bone = this.bone;
  65806. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  65807. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  65808. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  65809. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  65810. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  65811. };
  65812. /** Releases resources */
  65813. BoneAxesViewer.prototype.dispose = function () {
  65814. if (this.mesh) {
  65815. this.mesh = null;
  65816. this.bone = null;
  65817. _super.prototype.dispose.call(this);
  65818. }
  65819. };
  65820. return BoneAxesViewer;
  65821. }(Debug.AxesViewer));
  65822. Debug.BoneAxesViewer = BoneAxesViewer;
  65823. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  65824. })(BABYLON || (BABYLON = {}));
  65825. //# sourceMappingURL=boneAxesViewer.js.map
  65826. var BABYLON;
  65827. (function (BABYLON) {
  65828. /**
  65829. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  65830. * in order to better appreciate the issue one might have.
  65831. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  65832. */
  65833. var RayHelper = /** @class */ (function () {
  65834. /**
  65835. * Instantiate a new ray helper.
  65836. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  65837. * in order to better appreciate the issue one might have.
  65838. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  65839. * @param ray Defines the ray we are currently tryin to visualize
  65840. */
  65841. function RayHelper(ray) {
  65842. this.ray = ray;
  65843. }
  65844. /**
  65845. * Helper function to create a colored helper in a scene in one line.
  65846. * @param ray Defines the ray we are currently tryin to visualize
  65847. * @param scene Defines the scene the ray is used in
  65848. * @param color Defines the color we want to see the ray in
  65849. * @returns The newly created ray helper.
  65850. */
  65851. RayHelper.CreateAndShow = function (ray, scene, color) {
  65852. var helper = new RayHelper(ray);
  65853. helper.show(scene, color);
  65854. return helper;
  65855. };
  65856. /**
  65857. * Shows the ray we are willing to debug.
  65858. * @param scene Defines the scene the ray needs to be rendered in
  65859. * @param color Defines the color the ray needs to be rendered in
  65860. */
  65861. RayHelper.prototype.show = function (scene, color) {
  65862. if (!this._renderFunction && this.ray) {
  65863. var ray = this.ray;
  65864. this._renderFunction = this._render.bind(this);
  65865. this._scene = scene;
  65866. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  65867. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  65868. if (this._renderFunction) {
  65869. this._scene.registerBeforeRender(this._renderFunction);
  65870. }
  65871. }
  65872. if (color && this._renderLine) {
  65873. this._renderLine.color.copyFrom(color);
  65874. }
  65875. };
  65876. /**
  65877. * Hides the ray we are debugging.
  65878. */
  65879. RayHelper.prototype.hide = function () {
  65880. if (this._renderFunction && this._scene) {
  65881. this._scene.unregisterBeforeRender(this._renderFunction);
  65882. this._scene = null;
  65883. this._renderFunction = null;
  65884. if (this._renderLine) {
  65885. this._renderLine.dispose();
  65886. this._renderLine = null;
  65887. }
  65888. this._renderPoints = [];
  65889. }
  65890. };
  65891. RayHelper.prototype._render = function () {
  65892. var ray = this.ray;
  65893. if (!ray) {
  65894. return;
  65895. }
  65896. var point = this._renderPoints[1];
  65897. var len = Math.min(ray.length, 1000000);
  65898. point.copyFrom(ray.direction);
  65899. point.scaleInPlace(len);
  65900. point.addInPlace(ray.origin);
  65901. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  65902. };
  65903. /**
  65904. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  65905. * @param mesh Defines the mesh we want the helper attached to
  65906. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  65907. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  65908. * @param length Defines the length of the ray
  65909. */
  65910. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  65911. this._attachedToMesh = mesh;
  65912. var ray = this.ray;
  65913. if (!ray) {
  65914. return;
  65915. }
  65916. if (!ray.direction) {
  65917. ray.direction = BABYLON.Vector3.Zero();
  65918. }
  65919. if (!ray.origin) {
  65920. ray.origin = BABYLON.Vector3.Zero();
  65921. }
  65922. if (length) {
  65923. ray.length = length;
  65924. }
  65925. if (!meshSpaceOrigin) {
  65926. meshSpaceOrigin = BABYLON.Vector3.Zero();
  65927. }
  65928. if (!meshSpaceDirection) {
  65929. // -1 so that this will work with Mesh.lookAt
  65930. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  65931. }
  65932. if (!this._meshSpaceDirection) {
  65933. this._meshSpaceDirection = meshSpaceDirection.clone();
  65934. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  65935. }
  65936. else {
  65937. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  65938. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  65939. }
  65940. if (!this._updateToMeshFunction) {
  65941. this._updateToMeshFunction = this._updateToMesh.bind(this);
  65942. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  65943. }
  65944. this._updateToMesh();
  65945. };
  65946. /**
  65947. * Detach the ray helper from the mesh it has previously been attached to.
  65948. */
  65949. RayHelper.prototype.detachFromMesh = function () {
  65950. if (this._attachedToMesh) {
  65951. if (this._updateToMeshFunction) {
  65952. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  65953. }
  65954. this._attachedToMesh = null;
  65955. this._updateToMeshFunction = null;
  65956. }
  65957. };
  65958. RayHelper.prototype._updateToMesh = function () {
  65959. var ray = this.ray;
  65960. if (!this._attachedToMesh || !ray) {
  65961. return;
  65962. }
  65963. if (this._attachedToMesh._isDisposed) {
  65964. this.detachFromMesh();
  65965. return;
  65966. }
  65967. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  65968. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  65969. };
  65970. /**
  65971. * Dispose the helper and release its associated resources.
  65972. */
  65973. RayHelper.prototype.dispose = function () {
  65974. this.hide();
  65975. this.detachFromMesh();
  65976. this.ray = null;
  65977. };
  65978. return RayHelper;
  65979. }());
  65980. BABYLON.RayHelper = RayHelper;
  65981. })(BABYLON || (BABYLON = {}));
  65982. //# sourceMappingURL=rayHelper.js.map
  65983. var BABYLON;
  65984. (function (BABYLON) {
  65985. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  65986. get: function () {
  65987. if (!this._debugLayer) {
  65988. this._debugLayer = new DebugLayer(this);
  65989. }
  65990. return this._debugLayer;
  65991. },
  65992. enumerable: true,
  65993. configurable: true
  65994. });
  65995. /**
  65996. * The debug layer (aka Inspector) is the go to tool in order to better understand
  65997. * what is happening in your scene
  65998. * @see http://doc.babylonjs.com/features/playground_debuglayer
  65999. */
  66000. var DebugLayer = /** @class */ (function () {
  66001. /**
  66002. * Instantiates a new debug layer.
  66003. * The debug layer (aka Inspector) is the go to tool in order to better understand
  66004. * what is happening in your scene
  66005. * @see http://doc.babylonjs.com/features/playground_debuglayer
  66006. * @param scene Defines the scene to inspect
  66007. */
  66008. function DebugLayer(scene) {
  66009. var _this = this;
  66010. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  66011. /**
  66012. * Observable triggered when a property is changed through the inspector.
  66013. */
  66014. this.onPropertyChangedObservable = new BABYLON.Observable();
  66015. this._scene = scene;
  66016. this._scene.onDisposeObservable.add(function () {
  66017. // Debug layer
  66018. if (_this._scene._debugLayer) {
  66019. _this._scene._debugLayer.hide();
  66020. }
  66021. });
  66022. }
  66023. /** Creates the inspector window. */
  66024. DebugLayer.prototype._createInspector = function (config) {
  66025. if (config === void 0) { config = {}; }
  66026. var popup = config.popup || false;
  66027. var initialTab = config.initialTab || 0;
  66028. var parentElement = config.parentElement || null;
  66029. if (!this._inspector) {
  66030. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  66031. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  66032. } // else nothing to do as instance is already created
  66033. };
  66034. /**
  66035. * Get if the inspector is visible or not.
  66036. * @returns true if visible otherwise, false
  66037. */
  66038. DebugLayer.prototype.isVisible = function () {
  66039. if (!this._inspector) {
  66040. return false;
  66041. }
  66042. return true;
  66043. };
  66044. /**
  66045. * Hide the inspector and close its window.
  66046. */
  66047. DebugLayer.prototype.hide = function () {
  66048. if (this._inspector) {
  66049. try {
  66050. this._inspector.dispose();
  66051. }
  66052. catch (e) {
  66053. // If the inspector has been removed directly from the inspector tool
  66054. }
  66055. this.onPropertyChangedObservable.clear();
  66056. this._inspector = null;
  66057. }
  66058. };
  66059. /**
  66060. *
  66061. * Launch the debugLayer.
  66062. *
  66063. * initialTab:
  66064. * | Value | Tab Name |
  66065. * | --- | --- |
  66066. * | 0 | Scene |
  66067. * | 1 | Console |
  66068. * | 2 | Stats |
  66069. * | 3 | Textures |
  66070. * | 4 | Mesh |
  66071. * | 5 | Light |
  66072. * | 6 | Material |
  66073. * | 7 | GLTF |
  66074. * | 8 | GUI |
  66075. * | 9 | Physics |
  66076. * | 10 | Camera |
  66077. * | 11 | Audio |
  66078. *
  66079. * @param config Define the configuration of the inspector
  66080. */
  66081. DebugLayer.prototype.show = function (config) {
  66082. if (config === void 0) { config = {}; }
  66083. if (typeof this.BJSINSPECTOR == 'undefined') {
  66084. // Load inspector and add it to the DOM
  66085. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  66086. }
  66087. else {
  66088. // Otherwise creates the inspector
  66089. this._createInspector(config);
  66090. }
  66091. };
  66092. /**
  66093. * Gets the active tab
  66094. * @return the index of the active tab or -1 if the inspector is hidden
  66095. */
  66096. DebugLayer.prototype.getActiveTab = function () {
  66097. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  66098. };
  66099. /**
  66100. * Define the url to get the inspector script from.
  66101. * By default it uses the babylonjs CDN.
  66102. * @ignoreNaming
  66103. */
  66104. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  66105. return DebugLayer;
  66106. }());
  66107. BABYLON.DebugLayer = DebugLayer;
  66108. })(BABYLON || (BABYLON = {}));
  66109. //# sourceMappingURL=debugLayer.js.map
  66110. var BABYLON;
  66111. (function (BABYLON) {
  66112. var Debug;
  66113. (function (Debug) {
  66114. /**
  66115. * Used to show the physics impostor around the specific mesh
  66116. */
  66117. var PhysicsViewer = /** @class */ (function () {
  66118. /**
  66119. * Creates a new PhysicsViewer
  66120. * @param scene defines the hosting scene
  66121. */
  66122. function PhysicsViewer(scene) {
  66123. /** @hidden */
  66124. this._impostors = [];
  66125. /** @hidden */
  66126. this._meshes = [];
  66127. /** @hidden */
  66128. this._numMeshes = 0;
  66129. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66130. var physicEngine = this._scene.getPhysicsEngine();
  66131. if (physicEngine) {
  66132. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  66133. }
  66134. }
  66135. /** @hidden */
  66136. PhysicsViewer.prototype._updateDebugMeshes = function () {
  66137. var plugin = this._physicsEnginePlugin;
  66138. for (var i = 0; i < this._numMeshes; i++) {
  66139. var impostor = this._impostors[i];
  66140. if (!impostor) {
  66141. continue;
  66142. }
  66143. if (impostor.isDisposed) {
  66144. this.hideImpostor(this._impostors[i--]);
  66145. }
  66146. else {
  66147. var mesh = this._meshes[i];
  66148. if (mesh && plugin) {
  66149. plugin.syncMeshWithImpostor(mesh, impostor);
  66150. }
  66151. }
  66152. }
  66153. };
  66154. /**
  66155. * Renders a specified physic impostor
  66156. * @param impostor defines the impostor to render
  66157. */
  66158. PhysicsViewer.prototype.showImpostor = function (impostor) {
  66159. if (!this._scene) {
  66160. return;
  66161. }
  66162. for (var i = 0; i < this._numMeshes; i++) {
  66163. if (this._impostors[i] == impostor) {
  66164. return;
  66165. }
  66166. }
  66167. var debugMesh = this._getDebugMesh(impostor, this._scene);
  66168. if (debugMesh) {
  66169. this._impostors[this._numMeshes] = impostor;
  66170. this._meshes[this._numMeshes] = debugMesh;
  66171. if (this._numMeshes === 0) {
  66172. this._renderFunction = this._updateDebugMeshes.bind(this);
  66173. this._scene.registerBeforeRender(this._renderFunction);
  66174. }
  66175. this._numMeshes++;
  66176. }
  66177. };
  66178. /**
  66179. * Hides a specified physic impostor
  66180. * @param impostor defines the impostor to hide
  66181. */
  66182. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  66183. if (!impostor || !this._scene) {
  66184. return;
  66185. }
  66186. var removed = false;
  66187. for (var i = 0; i < this._numMeshes; i++) {
  66188. if (this._impostors[i] == impostor) {
  66189. var mesh = this._meshes[i];
  66190. if (!mesh) {
  66191. continue;
  66192. }
  66193. this._scene.removeMesh(mesh);
  66194. mesh.dispose();
  66195. this._numMeshes--;
  66196. if (this._numMeshes > 0) {
  66197. this._meshes[i] = this._meshes[this._numMeshes];
  66198. this._impostors[i] = this._impostors[this._numMeshes];
  66199. this._meshes[this._numMeshes] = null;
  66200. this._impostors[this._numMeshes] = null;
  66201. }
  66202. else {
  66203. this._meshes[0] = null;
  66204. this._impostors[0] = null;
  66205. }
  66206. removed = true;
  66207. break;
  66208. }
  66209. }
  66210. if (removed && this._numMeshes === 0) {
  66211. this._scene.unregisterBeforeRender(this._renderFunction);
  66212. }
  66213. };
  66214. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  66215. if (!this._debugMaterial) {
  66216. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  66217. this._debugMaterial.wireframe = true;
  66218. }
  66219. return this._debugMaterial;
  66220. };
  66221. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  66222. if (!this._debugBoxMesh) {
  66223. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  66224. this._debugBoxMesh.renderingGroupId = 1;
  66225. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  66226. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  66227. scene.removeMesh(this._debugBoxMesh);
  66228. }
  66229. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  66230. };
  66231. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  66232. if (!this._debugSphereMesh) {
  66233. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  66234. this._debugSphereMesh.renderingGroupId = 1;
  66235. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  66236. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  66237. scene.removeMesh(this._debugSphereMesh);
  66238. }
  66239. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  66240. };
  66241. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  66242. var mesh = null;
  66243. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  66244. mesh = this._getDebugBoxMesh(scene);
  66245. impostor.getBoxSizeToRef(mesh.scaling);
  66246. }
  66247. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  66248. mesh = this._getDebugSphereMesh(scene);
  66249. var radius = impostor.getRadius();
  66250. mesh.scaling.x = radius * 2;
  66251. mesh.scaling.y = radius * 2;
  66252. mesh.scaling.z = radius * 2;
  66253. }
  66254. return mesh;
  66255. };
  66256. /** Releases all resources */
  66257. PhysicsViewer.prototype.dispose = function () {
  66258. for (var i = 0; i < this._numMeshes; i++) {
  66259. this.hideImpostor(this._impostors[i]);
  66260. }
  66261. if (this._debugBoxMesh) {
  66262. this._debugBoxMesh.dispose();
  66263. }
  66264. if (this._debugSphereMesh) {
  66265. this._debugSphereMesh.dispose();
  66266. }
  66267. if (this._debugMaterial) {
  66268. this._debugMaterial.dispose();
  66269. }
  66270. this._impostors.length = 0;
  66271. this._scene = null;
  66272. this._physicsEnginePlugin = null;
  66273. };
  66274. return PhysicsViewer;
  66275. }());
  66276. Debug.PhysicsViewer = PhysicsViewer;
  66277. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  66278. })(BABYLON || (BABYLON = {}));
  66279. //# sourceMappingURL=physicsViewer.js.map
  66280. var BABYLON;
  66281. (function (BABYLON) {
  66282. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  66283. get: function () {
  66284. return this._forceShowBoundingBoxes || false;
  66285. },
  66286. set: function (value) {
  66287. this._forceShowBoundingBoxes = value;
  66288. // Lazyly creates a BB renderer if needed.
  66289. if (value) {
  66290. this.getBoundingBoxRenderer();
  66291. }
  66292. },
  66293. enumerable: true,
  66294. configurable: true
  66295. });
  66296. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  66297. if (!this._boundingBoxRenderer) {
  66298. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  66299. }
  66300. return this._boundingBoxRenderer;
  66301. };
  66302. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  66303. get: function () {
  66304. return this._showBoundingBox || false;
  66305. },
  66306. set: function (value) {
  66307. this._showBoundingBox = value;
  66308. // Lazyly creates a BB renderer if needed.
  66309. if (value) {
  66310. this.getScene().getBoundingBoxRenderer();
  66311. }
  66312. },
  66313. enumerable: true,
  66314. configurable: true
  66315. });
  66316. /**
  66317. * Component responsible of rendering the bounding box of the meshes in a scene.
  66318. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  66319. */
  66320. var BoundingBoxRenderer = /** @class */ (function () {
  66321. /**
  66322. * Instantiates a new bounding box renderer in a scene.
  66323. * @param scene the scene the renderer renders in
  66324. */
  66325. function BoundingBoxRenderer(scene) {
  66326. /**
  66327. * The component name helpfull to identify the component in the list of scene components.
  66328. */
  66329. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  66330. /**
  66331. * Color of the bounding box lines placed in front of an object
  66332. */
  66333. this.frontColor = new BABYLON.Color3(1, 1, 1);
  66334. /**
  66335. * Color of the bounding box lines placed behind an object
  66336. */
  66337. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  66338. /**
  66339. * Defines if the renderer should show the back lines or not
  66340. */
  66341. this.showBackLines = true;
  66342. /**
  66343. * @hidden
  66344. */
  66345. this.renderList = new BABYLON.SmartArray(32);
  66346. this._vertexBuffers = {};
  66347. this.scene = scene;
  66348. scene._addComponent(this);
  66349. }
  66350. /**
  66351. * Registers the component in a given scene
  66352. */
  66353. BoundingBoxRenderer.prototype.register = function () {
  66354. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  66355. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  66356. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  66357. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  66358. };
  66359. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  66360. if (mesh.showSubMeshesBoundingBox) {
  66361. var boundingInfo = subMesh.getBoundingInfo();
  66362. if (boundingInfo !== null && boundingInfo !== undefined) {
  66363. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  66364. this.renderList.push(boundingInfo.boundingBox);
  66365. }
  66366. }
  66367. };
  66368. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  66369. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  66370. var boundingInfo = sourceMesh.getBoundingInfo();
  66371. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  66372. this.renderList.push(boundingInfo.boundingBox);
  66373. }
  66374. };
  66375. BoundingBoxRenderer.prototype._prepareRessources = function () {
  66376. if (this._colorShader) {
  66377. return;
  66378. }
  66379. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  66380. attributes: [BABYLON.VertexBuffer.PositionKind],
  66381. uniforms: ["world", "viewProjection", "color"]
  66382. });
  66383. var engine = this.scene.getEngine();
  66384. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  66385. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  66386. this._createIndexBuffer();
  66387. };
  66388. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  66389. var engine = this.scene.getEngine();
  66390. 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]);
  66391. };
  66392. /**
  66393. * Rebuilds the elements related to this component in case of
  66394. * context lost for instance.
  66395. */
  66396. BoundingBoxRenderer.prototype.rebuild = function () {
  66397. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66398. if (vb) {
  66399. vb._rebuild();
  66400. }
  66401. this._createIndexBuffer();
  66402. };
  66403. /**
  66404. * @hidden
  66405. */
  66406. BoundingBoxRenderer.prototype.reset = function () {
  66407. this.renderList.reset();
  66408. };
  66409. /**
  66410. * Render the bounding boxes of a specific rendering group
  66411. * @param renderingGroupId defines the rendering group to render
  66412. */
  66413. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  66414. if (this.renderList.length === 0) {
  66415. return;
  66416. }
  66417. this._prepareRessources();
  66418. if (!this._colorShader.isReady()) {
  66419. return;
  66420. }
  66421. var engine = this.scene.getEngine();
  66422. engine.setDepthWrite(false);
  66423. this._colorShader._preBind();
  66424. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  66425. var boundingBox = this.renderList.data[boundingBoxIndex];
  66426. if (boundingBox._tag !== renderingGroupId) {
  66427. continue;
  66428. }
  66429. var min = boundingBox.minimum;
  66430. var max = boundingBox.maximum;
  66431. var diff = max.subtract(min);
  66432. var median = min.add(diff.scale(0.5));
  66433. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  66434. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  66435. .multiply(boundingBox.getWorldMatrix());
  66436. // VBOs
  66437. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  66438. if (this.showBackLines) {
  66439. // Back
  66440. engine.setDepthFunctionToGreaterOrEqual();
  66441. this.scene.resetCachedMaterial();
  66442. this._colorShader.setColor4("color", this.backColor.toColor4());
  66443. this._colorShader.bind(worldMatrix);
  66444. // Draw order
  66445. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  66446. }
  66447. // Front
  66448. engine.setDepthFunctionToLess();
  66449. this.scene.resetCachedMaterial();
  66450. this._colorShader.setColor4("color", this.frontColor.toColor4());
  66451. this._colorShader.bind(worldMatrix);
  66452. // Draw order
  66453. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  66454. }
  66455. this._colorShader.unbind();
  66456. engine.setDepthFunctionToLessOrEqual();
  66457. engine.setDepthWrite(true);
  66458. };
  66459. /**
  66460. * In case of occlusion queries, we can render the occlusion bounding box through this method
  66461. * @param mesh Define the mesh to render the occlusion bounding box for
  66462. */
  66463. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  66464. this._prepareRessources();
  66465. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  66466. return;
  66467. }
  66468. var engine = this.scene.getEngine();
  66469. engine.setDepthWrite(false);
  66470. engine.setColorWrite(false);
  66471. this._colorShader._preBind();
  66472. var boundingBox = mesh._boundingInfo.boundingBox;
  66473. var min = boundingBox.minimum;
  66474. var max = boundingBox.maximum;
  66475. var diff = max.subtract(min);
  66476. var median = min.add(diff.scale(0.5));
  66477. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  66478. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  66479. .multiply(boundingBox.getWorldMatrix());
  66480. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  66481. engine.setDepthFunctionToLess();
  66482. this.scene.resetCachedMaterial();
  66483. this._colorShader.bind(worldMatrix);
  66484. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  66485. this._colorShader.unbind();
  66486. engine.setDepthFunctionToLessOrEqual();
  66487. engine.setDepthWrite(true);
  66488. engine.setColorWrite(true);
  66489. };
  66490. /**
  66491. * Dispose and release the resources attached to this renderer.
  66492. */
  66493. BoundingBoxRenderer.prototype.dispose = function () {
  66494. if (!this._colorShader) {
  66495. return;
  66496. }
  66497. this.renderList.dispose();
  66498. this._colorShader.dispose();
  66499. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66500. if (buffer) {
  66501. buffer.dispose();
  66502. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66503. }
  66504. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  66505. };
  66506. return BoundingBoxRenderer;
  66507. }());
  66508. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  66509. })(BABYLON || (BABYLON = {}));
  66510. //# sourceMappingURL=boundingBoxRenderer.js.map
  66511. var BABYLON;
  66512. (function (BABYLON) {
  66513. BABYLON.Engine.prototype.createTransformFeedback = function () {
  66514. return this._gl.createTransformFeedback();
  66515. };
  66516. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  66517. this._gl.deleteTransformFeedback(value);
  66518. };
  66519. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  66520. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  66521. };
  66522. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  66523. if (usePoints === void 0) { usePoints = true; }
  66524. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  66525. };
  66526. BABYLON.Engine.prototype.endTransformFeedback = function () {
  66527. this._gl.endTransformFeedback();
  66528. };
  66529. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  66530. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  66531. };
  66532. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  66533. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  66534. };
  66535. })(BABYLON || (BABYLON = {}));
  66536. //# sourceMappingURL=engine.transformFeedback.js.map
  66537. var BABYLON;
  66538. (function (BABYLON) {
  66539. /**
  66540. * This represents a GPU particle system in Babylon
  66541. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  66542. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  66543. */
  66544. var GPUParticleSystem = /** @class */ (function (_super) {
  66545. __extends(GPUParticleSystem, _super);
  66546. /**
  66547. * Instantiates a GPU particle system.
  66548. * 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.
  66549. * @param name The name of the particle system
  66550. * @param options The options used to create the system
  66551. * @param scene The scene the particle system belongs to
  66552. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  66553. */
  66554. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  66555. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  66556. var _this = _super.call(this, name) || this;
  66557. /**
  66558. * The layer mask we are rendering the particles through.
  66559. */
  66560. _this.layerMask = 0x0FFFFFFF;
  66561. _this._accumulatedCount = 0;
  66562. _this._targetIndex = 0;
  66563. _this._currentRenderId = -1;
  66564. _this._started = false;
  66565. _this._stopped = false;
  66566. _this._timeDelta = 0;
  66567. _this._actualFrame = 0;
  66568. _this._rawTextureWidth = 256;
  66569. /**
  66570. * An event triggered when the system is disposed.
  66571. */
  66572. _this.onDisposeObservable = new BABYLON.Observable();
  66573. /**
  66574. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  66575. * to override the particles.
  66576. */
  66577. _this.forceDepthWrite = false;
  66578. _this._preWarmDone = false;
  66579. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66580. // Setup the default processing configuration to the scene.
  66581. _this._attachImageProcessingConfiguration(null);
  66582. _this._engine = _this._scene.getEngine();
  66583. if (!options.randomTextureSize) {
  66584. delete options.randomTextureSize;
  66585. }
  66586. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  66587. var optionsAsNumber = options;
  66588. if (isFinite(optionsAsNumber)) {
  66589. fullOptions.capacity = optionsAsNumber;
  66590. }
  66591. _this._capacity = fullOptions.capacity;
  66592. _this._activeCount = fullOptions.capacity;
  66593. _this._currentActiveCount = 0;
  66594. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  66595. _this._scene.particleSystems.push(_this);
  66596. _this._updateEffectOptions = {
  66597. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  66598. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  66599. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  66600. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  66601. uniformBuffersNames: [],
  66602. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  66603. defines: "",
  66604. fallbacks: null,
  66605. onCompiled: null,
  66606. onError: null,
  66607. indexParameters: null,
  66608. maxSimultaneousLights: 0,
  66609. transformFeedbackVaryings: []
  66610. };
  66611. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  66612. // Random data
  66613. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  66614. var d = [];
  66615. for (var i = 0; i < maxTextureSize; ++i) {
  66616. d.push(Math.random());
  66617. d.push(Math.random());
  66618. d.push(Math.random());
  66619. d.push(Math.random());
  66620. }
  66621. _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);
  66622. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66623. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66624. d = [];
  66625. for (var i = 0; i < maxTextureSize; ++i) {
  66626. d.push(Math.random());
  66627. d.push(Math.random());
  66628. d.push(Math.random());
  66629. d.push(Math.random());
  66630. }
  66631. _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);
  66632. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66633. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66634. _this._randomTextureSize = maxTextureSize;
  66635. return _this;
  66636. }
  66637. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  66638. /**
  66639. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  66640. */
  66641. get: function () {
  66642. if (!BABYLON.Engine.LastCreatedEngine) {
  66643. return false;
  66644. }
  66645. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  66646. },
  66647. enumerable: true,
  66648. configurable: true
  66649. });
  66650. /**
  66651. * Gets the maximum number of particles active at the same time.
  66652. * @returns The max number of active particles.
  66653. */
  66654. GPUParticleSystem.prototype.getCapacity = function () {
  66655. return this._capacity;
  66656. };
  66657. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  66658. /**
  66659. * Gets or set the number of active particles
  66660. */
  66661. get: function () {
  66662. return this._activeCount;
  66663. },
  66664. set: function (value) {
  66665. this._activeCount = Math.min(value, this._capacity);
  66666. },
  66667. enumerable: true,
  66668. configurable: true
  66669. });
  66670. /**
  66671. * Is this system ready to be used/rendered
  66672. * @return true if the system is ready
  66673. */
  66674. GPUParticleSystem.prototype.isReady = function () {
  66675. if (!this._updateEffect) {
  66676. this._recreateUpdateEffect();
  66677. this._recreateRenderEffect();
  66678. return false;
  66679. }
  66680. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  66681. return false;
  66682. }
  66683. return true;
  66684. };
  66685. /**
  66686. * Gets if the system has been started. (Note: this will still be true after stop is called)
  66687. * @returns True if it has been started, otherwise false.
  66688. */
  66689. GPUParticleSystem.prototype.isStarted = function () {
  66690. return this._started;
  66691. };
  66692. /**
  66693. * Starts the particle system and begins to emit
  66694. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  66695. */
  66696. GPUParticleSystem.prototype.start = function (delay) {
  66697. var _this = this;
  66698. if (delay === void 0) { delay = this.startDelay; }
  66699. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  66700. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  66701. }
  66702. if (delay) {
  66703. setTimeout(function () {
  66704. _this.start(0);
  66705. }, delay);
  66706. return;
  66707. }
  66708. this._started = true;
  66709. this._stopped = false;
  66710. this._preWarmDone = false;
  66711. // Animations
  66712. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  66713. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  66714. }
  66715. };
  66716. /**
  66717. * Stops the particle system.
  66718. */
  66719. GPUParticleSystem.prototype.stop = function () {
  66720. this._stopped = true;
  66721. };
  66722. /**
  66723. * Remove all active particles
  66724. */
  66725. GPUParticleSystem.prototype.reset = function () {
  66726. this._releaseBuffers();
  66727. this._releaseVAOs();
  66728. this._currentActiveCount = 0;
  66729. this._targetIndex = 0;
  66730. };
  66731. /**
  66732. * Returns the string "GPUParticleSystem"
  66733. * @returns a string containing the class name
  66734. */
  66735. GPUParticleSystem.prototype.getClassName = function () {
  66736. return "GPUParticleSystem";
  66737. };
  66738. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  66739. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  66740. this._releaseBuffers();
  66741. return this;
  66742. };
  66743. /**
  66744. * Adds a new color gradient
  66745. * @param gradient defines the gradient to use (between 0 and 1)
  66746. * @param color1 defines the color to affect to the specified gradient
  66747. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  66748. * @returns the current particle system
  66749. */
  66750. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  66751. if (!this._colorGradients) {
  66752. this._colorGradients = [];
  66753. }
  66754. var colorGradient = new BABYLON.ColorGradient();
  66755. colorGradient.gradient = gradient;
  66756. colorGradient.color1 = color1;
  66757. this._colorGradients.push(colorGradient);
  66758. this._colorGradients.sort(function (a, b) {
  66759. if (a.gradient < b.gradient) {
  66760. return -1;
  66761. }
  66762. else if (a.gradient > b.gradient) {
  66763. return 1;
  66764. }
  66765. return 0;
  66766. });
  66767. if (this._colorGradientsTexture) {
  66768. this._colorGradientsTexture.dispose();
  66769. this._colorGradientsTexture = null;
  66770. }
  66771. this._releaseBuffers();
  66772. return this;
  66773. };
  66774. /**
  66775. * Remove a specific color gradient
  66776. * @param gradient defines the gradient to remove
  66777. * @returns the current particle system
  66778. */
  66779. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  66780. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  66781. this._colorGradientsTexture = null;
  66782. return this;
  66783. };
  66784. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  66785. var valueGradient = new BABYLON.FactorGradient();
  66786. valueGradient.gradient = gradient;
  66787. valueGradient.factor1 = factor;
  66788. factorGradients.push(valueGradient);
  66789. factorGradients.sort(function (a, b) {
  66790. if (a.gradient < b.gradient) {
  66791. return -1;
  66792. }
  66793. else if (a.gradient > b.gradient) {
  66794. return 1;
  66795. }
  66796. return 0;
  66797. });
  66798. this._releaseBuffers();
  66799. };
  66800. /**
  66801. * Adds a new size gradient
  66802. * @param gradient defines the gradient to use (between 0 and 1)
  66803. * @param factor defines the size factor to affect to the specified gradient
  66804. * @returns the current particle system
  66805. */
  66806. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  66807. if (!this._sizeGradients) {
  66808. this._sizeGradients = [];
  66809. }
  66810. this._addFactorGradient(this._sizeGradients, gradient, factor);
  66811. if (this._sizeGradientsTexture) {
  66812. this._sizeGradientsTexture.dispose();
  66813. this._sizeGradientsTexture = null;
  66814. }
  66815. this._releaseBuffers();
  66816. return this;
  66817. };
  66818. /**
  66819. * Remove a specific size gradient
  66820. * @param gradient defines the gradient to remove
  66821. * @returns the current particle system
  66822. */
  66823. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  66824. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  66825. this._sizeGradientsTexture = null;
  66826. return this;
  66827. };
  66828. /**
  66829. * Adds a new angular speed gradient
  66830. * @param gradient defines the gradient to use (between 0 and 1)
  66831. * @param factor defines the angular speed to affect to the specified gradient
  66832. * @returns the current particle system
  66833. */
  66834. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  66835. if (!this._angularSpeedGradients) {
  66836. this._angularSpeedGradients = [];
  66837. }
  66838. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  66839. if (this._angularSpeedGradientsTexture) {
  66840. this._angularSpeedGradientsTexture.dispose();
  66841. this._angularSpeedGradientsTexture = null;
  66842. }
  66843. this._releaseBuffers();
  66844. return this;
  66845. };
  66846. /**
  66847. * Remove a specific angular speed gradient
  66848. * @param gradient defines the gradient to remove
  66849. * @returns the current particle system
  66850. */
  66851. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  66852. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  66853. this._angularSpeedGradientsTexture = null;
  66854. return this;
  66855. };
  66856. /**
  66857. * Adds a new velocity gradient
  66858. * @param gradient defines the gradient to use (between 0 and 1)
  66859. * @param factor defines the velocity to affect to the specified gradient
  66860. * @returns the current particle system
  66861. */
  66862. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  66863. if (!this._velocityGradients) {
  66864. this._velocityGradients = [];
  66865. }
  66866. this._addFactorGradient(this._velocityGradients, gradient, factor);
  66867. if (this._velocityGradientsTexture) {
  66868. this._velocityGradientsTexture.dispose();
  66869. this._velocityGradientsTexture = null;
  66870. }
  66871. this._releaseBuffers();
  66872. return this;
  66873. };
  66874. /**
  66875. * Remove a specific velocity gradient
  66876. * @param gradient defines the gradient to remove
  66877. * @returns the current particle system
  66878. */
  66879. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  66880. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  66881. this._velocityGradientsTexture = null;
  66882. return this;
  66883. };
  66884. /**
  66885. * Adds a new limit velocity gradient
  66886. * @param gradient defines the gradient to use (between 0 and 1)
  66887. * @param factor defines the limit velocity value to affect to the specified gradient
  66888. * @returns the current particle system
  66889. */
  66890. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  66891. if (!this._limitVelocityGradients) {
  66892. this._limitVelocityGradients = [];
  66893. }
  66894. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  66895. if (this._limitVelocityGradientsTexture) {
  66896. this._limitVelocityGradientsTexture.dispose();
  66897. this._limitVelocityGradientsTexture = null;
  66898. }
  66899. this._releaseBuffers();
  66900. return this;
  66901. };
  66902. /**
  66903. * Remove a specific limit velocity gradient
  66904. * @param gradient defines the gradient to remove
  66905. * @returns the current particle system
  66906. */
  66907. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  66908. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  66909. this._limitVelocityGradientsTexture = null;
  66910. return this;
  66911. };
  66912. /**
  66913. * Adds a new drag gradient
  66914. * @param gradient defines the gradient to use (between 0 and 1)
  66915. * @param factor defines the drag value to affect to the specified gradient
  66916. * @returns the current particle system
  66917. */
  66918. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  66919. if (!this._dragGradients) {
  66920. this._dragGradients = [];
  66921. }
  66922. this._addFactorGradient(this._dragGradients, gradient, factor);
  66923. if (this._dragGradientsTexture) {
  66924. this._dragGradientsTexture.dispose();
  66925. this._dragGradientsTexture = null;
  66926. }
  66927. this._releaseBuffers();
  66928. return this;
  66929. };
  66930. /**
  66931. * Remove a specific drag gradient
  66932. * @param gradient defines the gradient to remove
  66933. * @returns the current particle system
  66934. */
  66935. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  66936. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  66937. this._dragGradientsTexture = null;
  66938. return this;
  66939. };
  66940. /**
  66941. * Not supported by GPUParticleSystem
  66942. * @param gradient defines the gradient to use (between 0 and 1)
  66943. * @param factor defines the emit rate value to affect to the specified gradient
  66944. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  66945. * @returns the current particle system
  66946. */
  66947. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  66948. // Do nothing as emit rate is not supported by GPUParticleSystem
  66949. return this;
  66950. };
  66951. /**
  66952. * Not supported by GPUParticleSystem
  66953. * @param gradient defines the gradient to remove
  66954. * @returns the current particle system
  66955. */
  66956. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  66957. // Do nothing as emit rate is not supported by GPUParticleSystem
  66958. return this;
  66959. };
  66960. /**
  66961. * Not supported by GPUParticleSystem
  66962. * @param gradient defines the gradient to use (between 0 and 1)
  66963. * @param factor defines the start size value to affect to the specified gradient
  66964. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  66965. * @returns the current particle system
  66966. */
  66967. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  66968. // Do nothing as start size is not supported by GPUParticleSystem
  66969. return this;
  66970. };
  66971. /**
  66972. * Not supported by GPUParticleSystem
  66973. * @param gradient defines the gradient to remove
  66974. * @returns the current particle system
  66975. */
  66976. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  66977. // Do nothing as start size is not supported by GPUParticleSystem
  66978. return this;
  66979. };
  66980. /**
  66981. * Not supported by GPUParticleSystem
  66982. * @param gradient defines the gradient to use (between 0 and 1)
  66983. * @param min defines the color remap minimal range
  66984. * @param max defines the color remap maximal range
  66985. * @returns the current particle system
  66986. */
  66987. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  66988. // Do nothing as start size is not supported by GPUParticleSystem
  66989. return this;
  66990. };
  66991. /**
  66992. * Not supported by GPUParticleSystem
  66993. * @param gradient defines the gradient to remove
  66994. * @returns the current particle system
  66995. */
  66996. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  66997. // Do nothing as start size is not supported by GPUParticleSystem
  66998. return this;
  66999. };
  67000. /**
  67001. * Not supported by GPUParticleSystem
  67002. * @param gradient defines the gradient to use (between 0 and 1)
  67003. * @param min defines the alpha remap minimal range
  67004. * @param max defines the alpha remap maximal range
  67005. * @returns the current particle system
  67006. */
  67007. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  67008. // Do nothing as start size is not supported by GPUParticleSystem
  67009. return this;
  67010. };
  67011. /**
  67012. * Not supported by GPUParticleSystem
  67013. * @param gradient defines the gradient to remove
  67014. * @returns the current particle system
  67015. */
  67016. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  67017. // Do nothing as start size is not supported by GPUParticleSystem
  67018. return this;
  67019. };
  67020. /**
  67021. * Not supported by GPUParticleSystem
  67022. * @param gradient defines the gradient to use (between 0 and 1)
  67023. * @param color defines the color to affect to the specified gradient
  67024. * @returns the current particle system
  67025. */
  67026. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  67027. //Not supported by GPUParticleSystem
  67028. return this;
  67029. };
  67030. /**
  67031. * Not supported by GPUParticleSystem
  67032. * @param gradient defines the gradient to remove
  67033. * @returns the current particle system
  67034. */
  67035. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  67036. //Not supported by GPUParticleSystem
  67037. return this;
  67038. };
  67039. /**
  67040. * Not supported by GPUParticleSystem
  67041. * @returns the list of ramp gradients
  67042. */
  67043. GPUParticleSystem.prototype.getRampGradients = function () {
  67044. return null;
  67045. };
  67046. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  67047. /**
  67048. * Not supported by GPUParticleSystem
  67049. * Gets or sets a boolean indicating that ramp gradients must be used
  67050. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  67051. */
  67052. get: function () {
  67053. //Not supported by GPUParticleSystem
  67054. return false;
  67055. },
  67056. set: function (value) {
  67057. //Not supported by GPUParticleSystem
  67058. },
  67059. enumerable: true,
  67060. configurable: true
  67061. });
  67062. /**
  67063. * Not supported by GPUParticleSystem
  67064. * @param gradient defines the gradient to use (between 0 and 1)
  67065. * @param factor defines the life time factor to affect to the specified gradient
  67066. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  67067. * @returns the current particle system
  67068. */
  67069. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  67070. //Not supported by GPUParticleSystem
  67071. return this;
  67072. };
  67073. /**
  67074. * Not supported by GPUParticleSystem
  67075. * @param gradient defines the gradient to remove
  67076. * @returns the current particle system
  67077. */
  67078. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  67079. //Not supported by GPUParticleSystem
  67080. return this;
  67081. };
  67082. GPUParticleSystem.prototype._reset = function () {
  67083. this._releaseBuffers();
  67084. };
  67085. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  67086. var updateVertexBuffers = {};
  67087. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  67088. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  67089. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  67090. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  67091. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  67092. var offset = 12;
  67093. if (!this._colorGradientsTexture) {
  67094. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  67095. offset += 4;
  67096. }
  67097. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  67098. offset += 3;
  67099. if (!this._isBillboardBased) {
  67100. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  67101. offset += 3;
  67102. }
  67103. if (this._angularSpeedGradientsTexture) {
  67104. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  67105. offset += 1;
  67106. }
  67107. else {
  67108. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  67109. offset += 2;
  67110. }
  67111. if (this._isAnimationSheetEnabled) {
  67112. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  67113. offset += 1;
  67114. if (this.spriteRandomStartCell) {
  67115. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  67116. offset += 1;
  67117. }
  67118. }
  67119. if (this.noiseTexture) {
  67120. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  67121. offset += 3;
  67122. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  67123. offset += 3;
  67124. }
  67125. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  67126. this._engine.bindArrayBuffer(null);
  67127. return vao;
  67128. };
  67129. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  67130. var renderVertexBuffers = {};
  67131. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  67132. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  67133. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  67134. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  67135. var offset = 12;
  67136. if (!this._colorGradientsTexture) {
  67137. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  67138. offset += 4;
  67139. }
  67140. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  67141. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  67142. }
  67143. offset += 3; // Direction
  67144. if (!this._isBillboardBased) {
  67145. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  67146. offset += 3;
  67147. }
  67148. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  67149. if (this._angularSpeedGradientsTexture) {
  67150. offset++;
  67151. }
  67152. else {
  67153. offset += 2;
  67154. }
  67155. if (this._isAnimationSheetEnabled) {
  67156. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  67157. offset += 1;
  67158. if (this.spriteRandomStartCell) {
  67159. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  67160. offset += 1;
  67161. }
  67162. }
  67163. if (this.noiseTexture) {
  67164. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  67165. offset += 3;
  67166. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  67167. offset += 3;
  67168. }
  67169. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  67170. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  67171. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  67172. this._engine.bindArrayBuffer(null);
  67173. return vao;
  67174. };
  67175. GPUParticleSystem.prototype._initialize = function (force) {
  67176. if (force === void 0) { force = false; }
  67177. if (this._buffer0 && !force) {
  67178. return;
  67179. }
  67180. var engine = this._scene.getEngine();
  67181. var data = new Array();
  67182. this._attributesStrideSize = 21;
  67183. this._targetIndex = 0;
  67184. if (!this.isBillboardBased) {
  67185. this._attributesStrideSize += 3;
  67186. }
  67187. if (this._colorGradientsTexture) {
  67188. this._attributesStrideSize -= 4;
  67189. }
  67190. if (this._angularSpeedGradientsTexture) {
  67191. this._attributesStrideSize -= 1;
  67192. }
  67193. if (this._isAnimationSheetEnabled) {
  67194. this._attributesStrideSize += 1;
  67195. if (this.spriteRandomStartCell) {
  67196. this._attributesStrideSize += 1;
  67197. }
  67198. }
  67199. if (this.noiseTexture) {
  67200. this._attributesStrideSize += 6;
  67201. }
  67202. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  67203. // position
  67204. data.push(0.0);
  67205. data.push(0.0);
  67206. data.push(0.0);
  67207. // Age and life
  67208. data.push(0.0); // create the particle as a dead one to create a new one at start
  67209. data.push(0.0);
  67210. // Seed
  67211. data.push(Math.random());
  67212. data.push(Math.random());
  67213. data.push(Math.random());
  67214. data.push(Math.random());
  67215. // Size
  67216. data.push(0.0);
  67217. data.push(0.0);
  67218. data.push(0.0);
  67219. if (!this._colorGradientsTexture) {
  67220. // color
  67221. data.push(0.0);
  67222. data.push(0.0);
  67223. data.push(0.0);
  67224. data.push(0.0);
  67225. }
  67226. // direction
  67227. data.push(0.0);
  67228. data.push(0.0);
  67229. data.push(0.0);
  67230. if (!this.isBillboardBased) {
  67231. // initialDirection
  67232. data.push(0.0);
  67233. data.push(0.0);
  67234. data.push(0.0);
  67235. }
  67236. // angle
  67237. data.push(0.0);
  67238. if (!this._angularSpeedGradientsTexture) {
  67239. data.push(0.0);
  67240. }
  67241. if (this._isAnimationSheetEnabled) {
  67242. data.push(0.0);
  67243. if (this.spriteRandomStartCell) {
  67244. data.push(0.0);
  67245. }
  67246. }
  67247. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  67248. data.push(Math.random());
  67249. data.push(Math.random());
  67250. data.push(Math.random());
  67251. data.push(Math.random());
  67252. data.push(Math.random());
  67253. data.push(Math.random());
  67254. }
  67255. }
  67256. // Sprite data
  67257. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  67258. -0.5, 0.5, 0, 1,
  67259. -0.5, -0.5, 0, 0,
  67260. 0.5, -0.5, 1, 0]);
  67261. // Buffers
  67262. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  67263. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  67264. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  67265. // Update VAO
  67266. this._updateVAO = [];
  67267. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  67268. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  67269. // Render VAO
  67270. this._renderVAO = [];
  67271. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  67272. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  67273. // Links
  67274. this._sourceBuffer = this._buffer0;
  67275. this._targetBuffer = this._buffer1;
  67276. };
  67277. /** @hidden */
  67278. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  67279. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  67280. if (this._isBillboardBased) {
  67281. defines += "\n#define BILLBOARD";
  67282. }
  67283. if (this._colorGradientsTexture) {
  67284. defines += "\n#define COLORGRADIENTS";
  67285. }
  67286. if (this._sizeGradientsTexture) {
  67287. defines += "\n#define SIZEGRADIENTS";
  67288. }
  67289. if (this._angularSpeedGradientsTexture) {
  67290. defines += "\n#define ANGULARSPEEDGRADIENTS";
  67291. }
  67292. if (this._velocityGradientsTexture) {
  67293. defines += "\n#define VELOCITYGRADIENTS";
  67294. }
  67295. if (this._limitVelocityGradientsTexture) {
  67296. defines += "\n#define LIMITVELOCITYGRADIENTS";
  67297. }
  67298. if (this._dragGradientsTexture) {
  67299. defines += "\n#define DRAGGRADIENTS";
  67300. }
  67301. if (this.isAnimationSheetEnabled) {
  67302. defines += "\n#define ANIMATESHEET";
  67303. if (this.spriteRandomStartCell) {
  67304. defines += "\n#define ANIMATESHEETRANDOMSTART";
  67305. }
  67306. }
  67307. if (this.noiseTexture) {
  67308. defines += "\n#define NOISE";
  67309. }
  67310. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  67311. return;
  67312. }
  67313. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  67314. if (!this._colorGradientsTexture) {
  67315. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  67316. }
  67317. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  67318. if (!this._isBillboardBased) {
  67319. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  67320. }
  67321. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  67322. if (this.isAnimationSheetEnabled) {
  67323. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  67324. if (this.spriteRandomStartCell) {
  67325. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  67326. }
  67327. }
  67328. if (this.noiseTexture) {
  67329. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  67330. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  67331. }
  67332. this._updateEffectOptions.defines = defines;
  67333. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  67334. };
  67335. /** @hidden */
  67336. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  67337. var defines = "";
  67338. if (this._scene.clipPlane) {
  67339. defines = "\n#define CLIPPLANE";
  67340. }
  67341. if (this._scene.clipPlane2) {
  67342. defines = "\n#define CLIPPLANE2";
  67343. }
  67344. if (this._scene.clipPlane3) {
  67345. defines = "\n#define CLIPPLANE3";
  67346. }
  67347. if (this._scene.clipPlane4) {
  67348. defines = "\n#define CLIPPLANE4";
  67349. }
  67350. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  67351. defines = "\n#define BLENDMULTIPLYMODE";
  67352. }
  67353. if (this._isBillboardBased) {
  67354. defines += "\n#define BILLBOARD";
  67355. switch (this.billboardMode) {
  67356. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  67357. defines += "\n#define BILLBOARDY";
  67358. break;
  67359. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  67360. defines += "\n#define BILLBOARDSTRETCHED";
  67361. break;
  67362. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  67363. default:
  67364. break;
  67365. }
  67366. }
  67367. if (this._colorGradientsTexture) {
  67368. defines += "\n#define COLORGRADIENTS";
  67369. }
  67370. if (this.isAnimationSheetEnabled) {
  67371. defines += "\n#define ANIMATESHEET";
  67372. }
  67373. if (this._imageProcessingConfiguration) {
  67374. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  67375. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  67376. }
  67377. if (this._renderEffect && this._renderEffect.defines === defines) {
  67378. return;
  67379. }
  67380. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  67381. var samplers = ["textureSampler", "colorGradientSampler"];
  67382. if (BABYLON.ImageProcessingConfiguration) {
  67383. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  67384. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  67385. }
  67386. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  67387. };
  67388. /**
  67389. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  67390. * @param preWarm defines if we are in the pre-warmimg phase
  67391. */
  67392. GPUParticleSystem.prototype.animate = function (preWarm) {
  67393. if (preWarm === void 0) { preWarm = false; }
  67394. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  67395. this._actualFrame += this._timeDelta;
  67396. if (!this._stopped) {
  67397. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  67398. this.stop();
  67399. }
  67400. }
  67401. };
  67402. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  67403. var texture = this[textureName];
  67404. if (!factorGradients || !factorGradients.length || texture) {
  67405. return;
  67406. }
  67407. var data = new Float32Array(this._rawTextureWidth);
  67408. for (var x = 0; x < this._rawTextureWidth; x++) {
  67409. var ratio = x / this._rawTextureWidth;
  67410. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  67411. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  67412. });
  67413. }
  67414. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  67415. };
  67416. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  67417. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  67418. };
  67419. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  67420. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  67421. };
  67422. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  67423. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  67424. };
  67425. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  67426. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  67427. };
  67428. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  67429. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  67430. };
  67431. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  67432. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  67433. return;
  67434. }
  67435. var data = new Uint8Array(this._rawTextureWidth * 4);
  67436. var tmpColor = BABYLON.Tmp.Color4[0];
  67437. for (var x = 0; x < this._rawTextureWidth; x++) {
  67438. var ratio = x / this._rawTextureWidth;
  67439. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  67440. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  67441. data[x * 4] = tmpColor.r * 255;
  67442. data[x * 4 + 1] = tmpColor.g * 255;
  67443. data[x * 4 + 2] = tmpColor.b * 255;
  67444. data[x * 4 + 3] = tmpColor.a * 255;
  67445. });
  67446. }
  67447. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  67448. };
  67449. /**
  67450. * Renders the particle system in its current state
  67451. * @param preWarm defines if the system should only update the particles but not render them
  67452. * @returns the current number of particles
  67453. */
  67454. GPUParticleSystem.prototype.render = function (preWarm) {
  67455. if (preWarm === void 0) { preWarm = false; }
  67456. if (!this._started) {
  67457. return 0;
  67458. }
  67459. this._createColorGradientTexture();
  67460. this._createSizeGradientTexture();
  67461. this._createAngularSpeedGradientTexture();
  67462. this._createVelocityGradientTexture();
  67463. this._createLimitVelocityGradientTexture();
  67464. this._createDragGradientTexture();
  67465. this._recreateUpdateEffect();
  67466. this._recreateRenderEffect();
  67467. if (!this.isReady()) {
  67468. return 0;
  67469. }
  67470. if (!preWarm) {
  67471. if (!this._preWarmDone && this.preWarmCycles) {
  67472. for (var index = 0; index < this.preWarmCycles; index++) {
  67473. this.animate(true);
  67474. this.render(true);
  67475. }
  67476. this._preWarmDone = true;
  67477. }
  67478. if (this._currentRenderId === this._scene.getFrameId()) {
  67479. return 0;
  67480. }
  67481. this._currentRenderId = this._scene.getFrameId();
  67482. }
  67483. // Get everything ready to render
  67484. this._initialize();
  67485. this._accumulatedCount += this.emitRate * this._timeDelta;
  67486. if (this._accumulatedCount > 1) {
  67487. var intPart = this._accumulatedCount | 0;
  67488. this._accumulatedCount -= intPart;
  67489. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  67490. }
  67491. if (!this._currentActiveCount) {
  67492. return 0;
  67493. }
  67494. // Enable update effect
  67495. this._engine.enableEffect(this._updateEffect);
  67496. this._engine.setState(false);
  67497. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  67498. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  67499. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  67500. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  67501. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  67502. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  67503. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  67504. if (!this._colorGradientsTexture) {
  67505. this._updateEffect.setDirectColor4("color1", this.color1);
  67506. this._updateEffect.setDirectColor4("color2", this.color2);
  67507. }
  67508. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  67509. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  67510. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  67511. this._updateEffect.setVector3("gravity", this.gravity);
  67512. if (this._sizeGradientsTexture) {
  67513. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  67514. }
  67515. if (this._angularSpeedGradientsTexture) {
  67516. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  67517. }
  67518. if (this._velocityGradientsTexture) {
  67519. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  67520. }
  67521. if (this._limitVelocityGradientsTexture) {
  67522. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  67523. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  67524. }
  67525. if (this._dragGradientsTexture) {
  67526. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  67527. }
  67528. if (this.particleEmitterType) {
  67529. this.particleEmitterType.applyToShader(this._updateEffect);
  67530. }
  67531. if (this._isAnimationSheetEnabled) {
  67532. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  67533. }
  67534. if (this.noiseTexture) {
  67535. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  67536. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  67537. }
  67538. var emitterWM;
  67539. if (this.emitter.position) {
  67540. var emitterMesh = this.emitter;
  67541. emitterWM = emitterMesh.getWorldMatrix();
  67542. }
  67543. else {
  67544. var emitterPosition = this.emitter;
  67545. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  67546. }
  67547. this._updateEffect.setMatrix("emitterWM", emitterWM);
  67548. // Bind source VAO
  67549. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  67550. // Update
  67551. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  67552. this._engine.setRasterizerState(false);
  67553. this._engine.beginTransformFeedback(true);
  67554. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  67555. this._engine.endTransformFeedback();
  67556. this._engine.setRasterizerState(true);
  67557. this._engine.bindTransformFeedbackBuffer(null);
  67558. if (!preWarm) {
  67559. // Enable render effect
  67560. this._engine.enableEffect(this._renderEffect);
  67561. var viewMatrix = this._scene.getViewMatrix();
  67562. this._renderEffect.setMatrix("view", viewMatrix);
  67563. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  67564. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  67565. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  67566. if (this._colorGradientsTexture) {
  67567. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  67568. }
  67569. else {
  67570. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  67571. }
  67572. if (this._isAnimationSheetEnabled && this.particleTexture) {
  67573. var baseSize = this.particleTexture.getBaseSize();
  67574. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  67575. }
  67576. if (this._isBillboardBased) {
  67577. var camera = this._scene.activeCamera;
  67578. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  67579. }
  67580. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  67581. var invView = viewMatrix.clone();
  67582. invView.invert();
  67583. this._renderEffect.setMatrix("invView", invView);
  67584. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  67585. }
  67586. // image processing
  67587. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  67588. this._imageProcessingConfiguration.bind(this._renderEffect);
  67589. }
  67590. // Draw order
  67591. switch (this.blendMode) {
  67592. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  67593. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  67594. break;
  67595. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  67596. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  67597. break;
  67598. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  67599. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  67600. break;
  67601. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  67602. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  67603. break;
  67604. }
  67605. if (this.forceDepthWrite) {
  67606. this._engine.setDepthWrite(true);
  67607. }
  67608. // Bind source VAO
  67609. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  67610. // Render
  67611. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  67612. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67613. }
  67614. // Switch VAOs
  67615. this._targetIndex++;
  67616. if (this._targetIndex === 2) {
  67617. this._targetIndex = 0;
  67618. }
  67619. // Switch buffers
  67620. var tmpBuffer = this._sourceBuffer;
  67621. this._sourceBuffer = this._targetBuffer;
  67622. this._targetBuffer = tmpBuffer;
  67623. return this._currentActiveCount;
  67624. };
  67625. /**
  67626. * Rebuilds the particle system
  67627. */
  67628. GPUParticleSystem.prototype.rebuild = function () {
  67629. this._initialize(true);
  67630. };
  67631. GPUParticleSystem.prototype._releaseBuffers = function () {
  67632. if (this._buffer0) {
  67633. this._buffer0.dispose();
  67634. this._buffer0 = null;
  67635. }
  67636. if (this._buffer1) {
  67637. this._buffer1.dispose();
  67638. this._buffer1 = null;
  67639. }
  67640. if (this._spriteBuffer) {
  67641. this._spriteBuffer.dispose();
  67642. this._spriteBuffer = null;
  67643. }
  67644. };
  67645. GPUParticleSystem.prototype._releaseVAOs = function () {
  67646. if (!this._updateVAO) {
  67647. return;
  67648. }
  67649. for (var index = 0; index < this._updateVAO.length; index++) {
  67650. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  67651. }
  67652. this._updateVAO = [];
  67653. for (var index = 0; index < this._renderVAO.length; index++) {
  67654. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  67655. }
  67656. this._renderVAO = [];
  67657. };
  67658. /**
  67659. * Disposes the particle system and free the associated resources
  67660. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  67661. */
  67662. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  67663. if (disposeTexture === void 0) { disposeTexture = true; }
  67664. var index = this._scene.particleSystems.indexOf(this);
  67665. if (index > -1) {
  67666. this._scene.particleSystems.splice(index, 1);
  67667. }
  67668. this._releaseBuffers();
  67669. this._releaseVAOs();
  67670. if (this._colorGradientsTexture) {
  67671. this._colorGradientsTexture.dispose();
  67672. this._colorGradientsTexture = null;
  67673. }
  67674. if (this._sizeGradientsTexture) {
  67675. this._sizeGradientsTexture.dispose();
  67676. this._sizeGradientsTexture = null;
  67677. }
  67678. if (this._angularSpeedGradientsTexture) {
  67679. this._angularSpeedGradientsTexture.dispose();
  67680. this._angularSpeedGradientsTexture = null;
  67681. }
  67682. if (this._velocityGradientsTexture) {
  67683. this._velocityGradientsTexture.dispose();
  67684. this._velocityGradientsTexture = null;
  67685. }
  67686. if (this._limitVelocityGradientsTexture) {
  67687. this._limitVelocityGradientsTexture.dispose();
  67688. this._limitVelocityGradientsTexture = null;
  67689. }
  67690. if (this._dragGradientsTexture) {
  67691. this._dragGradientsTexture.dispose();
  67692. this._dragGradientsTexture = null;
  67693. }
  67694. if (this._randomTexture) {
  67695. this._randomTexture.dispose();
  67696. this._randomTexture = null;
  67697. }
  67698. if (this._randomTexture2) {
  67699. this._randomTexture2.dispose();
  67700. this._randomTexture2 = null;
  67701. }
  67702. if (disposeTexture && this.particleTexture) {
  67703. this.particleTexture.dispose();
  67704. this.particleTexture = null;
  67705. }
  67706. if (disposeTexture && this.noiseTexture) {
  67707. this.noiseTexture.dispose();
  67708. this.noiseTexture = null;
  67709. }
  67710. // Callback
  67711. this.onDisposeObservable.notifyObservers(this);
  67712. this.onDisposeObservable.clear();
  67713. };
  67714. /**
  67715. * Clones the particle system.
  67716. * @param name The name of the cloned object
  67717. * @param newEmitter The new emitter to use
  67718. * @returns the cloned particle system
  67719. */
  67720. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  67721. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  67722. BABYLON.Tools.DeepCopy(this, result);
  67723. if (newEmitter === undefined) {
  67724. newEmitter = this.emitter;
  67725. }
  67726. result.emitter = newEmitter;
  67727. if (this.particleTexture) {
  67728. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  67729. }
  67730. return result;
  67731. };
  67732. /**
  67733. * Serializes the particle system to a JSON object.
  67734. * @returns the JSON object
  67735. */
  67736. GPUParticleSystem.prototype.serialize = function () {
  67737. var serializationObject = {};
  67738. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  67739. serializationObject.activeParticleCount = this.activeParticleCount;
  67740. return serializationObject;
  67741. };
  67742. /**
  67743. * Parses a JSON object to create a GPU particle system.
  67744. * @param parsedParticleSystem The JSON object to parse
  67745. * @param scene The scene to create the particle system in
  67746. * @param rootUrl The root url to use to load external dependencies like texture
  67747. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  67748. * @returns the parsed GPU particle system
  67749. */
  67750. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  67751. if (doNotStart === void 0) { doNotStart = false; }
  67752. var name = parsedParticleSystem.name;
  67753. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  67754. if (parsedParticleSystem.activeParticleCount) {
  67755. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  67756. }
  67757. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  67758. // Auto start
  67759. if (parsedParticleSystem.preventAutoStart) {
  67760. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  67761. }
  67762. if (!doNotStart && !particleSystem.preventAutoStart) {
  67763. particleSystem.start();
  67764. }
  67765. return particleSystem;
  67766. };
  67767. return GPUParticleSystem;
  67768. }(BABYLON.BaseParticleSystem));
  67769. BABYLON.GPUParticleSystem = GPUParticleSystem;
  67770. })(BABYLON || (BABYLON = {}));
  67771. //# sourceMappingURL=gpuParticleSystem.js.map
  67772. var BABYLON;
  67773. (function (BABYLON) {
  67774. /**
  67775. * Represents one particle of a solid particle system.
  67776. */
  67777. var SolidParticle = /** @class */ (function () {
  67778. /**
  67779. * Creates a Solid Particle object.
  67780. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  67781. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  67782. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  67783. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  67784. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  67785. * @param shapeId (integer) is the model shape identifier in the SPS.
  67786. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  67787. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  67788. */
  67789. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  67790. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  67791. /**
  67792. * particle global index
  67793. */
  67794. this.idx = 0;
  67795. /**
  67796. * The color of the particle
  67797. */
  67798. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  67799. /**
  67800. * The world space position of the particle.
  67801. */
  67802. this.position = BABYLON.Vector3.Zero();
  67803. /**
  67804. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  67805. */
  67806. this.rotation = BABYLON.Vector3.Zero();
  67807. /**
  67808. * The scaling of the particle.
  67809. */
  67810. this.scaling = BABYLON.Vector3.One();
  67811. /**
  67812. * The uvs of the particle.
  67813. */
  67814. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  67815. /**
  67816. * The current speed of the particle.
  67817. */
  67818. this.velocity = BABYLON.Vector3.Zero();
  67819. /**
  67820. * The pivot point in the particle local space.
  67821. */
  67822. this.pivot = BABYLON.Vector3.Zero();
  67823. /**
  67824. * Must the particle be translated from its pivot point in its local space ?
  67825. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  67826. * Default : false
  67827. */
  67828. this.translateFromPivot = false;
  67829. /**
  67830. * Is the particle active or not ?
  67831. */
  67832. this.alive = true;
  67833. /**
  67834. * Is the particle visible or not ?
  67835. */
  67836. this.isVisible = true;
  67837. /**
  67838. * Index of this particle in the global "positions" array (Internal use)
  67839. * @hidden
  67840. */
  67841. this._pos = 0;
  67842. /**
  67843. * @hidden Index of this particle in the global "indices" array (Internal use)
  67844. */
  67845. this._ind = 0;
  67846. /**
  67847. * ModelShape id of this particle
  67848. */
  67849. this.shapeId = 0;
  67850. /**
  67851. * Index of the particle in its shape id (Internal use)
  67852. */
  67853. this.idxInShape = 0;
  67854. /**
  67855. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  67856. */
  67857. this._stillInvisible = false;
  67858. /**
  67859. * @hidden Last computed particle rotation matrix
  67860. */
  67861. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  67862. /**
  67863. * Parent particle Id, if any.
  67864. * Default null.
  67865. */
  67866. this.parentId = null;
  67867. /**
  67868. * @hidden Internal global position in the SPS.
  67869. */
  67870. this._globalPosition = BABYLON.Vector3.Zero();
  67871. this.idx = particleIndex;
  67872. this._pos = positionIndex;
  67873. this._ind = indiceIndex;
  67874. this._model = model;
  67875. this.shapeId = shapeId;
  67876. this.idxInShape = idxInShape;
  67877. this._sps = sps;
  67878. if (modelBoundingInfo) {
  67879. this._modelBoundingInfo = modelBoundingInfo;
  67880. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  67881. }
  67882. }
  67883. Object.defineProperty(SolidParticle.prototype, "scale", {
  67884. /**
  67885. * Legacy support, changed scale to scaling
  67886. */
  67887. get: function () {
  67888. return this.scaling;
  67889. },
  67890. /**
  67891. * Legacy support, changed scale to scaling
  67892. */
  67893. set: function (scale) {
  67894. this.scaling = scale;
  67895. },
  67896. enumerable: true,
  67897. configurable: true
  67898. });
  67899. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  67900. /**
  67901. * Legacy support, changed quaternion to rotationQuaternion
  67902. */
  67903. get: function () {
  67904. return this.rotationQuaternion;
  67905. },
  67906. /**
  67907. * Legacy support, changed quaternion to rotationQuaternion
  67908. */
  67909. set: function (q) {
  67910. this.rotationQuaternion = q;
  67911. },
  67912. enumerable: true,
  67913. configurable: true
  67914. });
  67915. /**
  67916. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  67917. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  67918. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  67919. * @returns true if it intersects
  67920. */
  67921. SolidParticle.prototype.intersectsMesh = function (target) {
  67922. if (!this._boundingInfo || !target._boundingInfo) {
  67923. return false;
  67924. }
  67925. if (this._sps._bSphereOnly) {
  67926. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  67927. }
  67928. return this._boundingInfo.intersects(target._boundingInfo, false);
  67929. };
  67930. /**
  67931. * get the rotation matrix of the particle
  67932. * @hidden
  67933. */
  67934. SolidParticle.prototype.getRotationMatrix = function (m) {
  67935. var quaternion;
  67936. if (this.rotationQuaternion) {
  67937. quaternion = this.rotationQuaternion;
  67938. }
  67939. else {
  67940. quaternion = BABYLON.Tmp.Quaternion[0];
  67941. var rotation = this.rotation;
  67942. BABYLON.Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion);
  67943. }
  67944. quaternion.toRotationMatrix(m);
  67945. };
  67946. return SolidParticle;
  67947. }());
  67948. BABYLON.SolidParticle = SolidParticle;
  67949. /**
  67950. * Represents the shape of the model used by one particle of a solid particle system.
  67951. * SPS internal tool, don't use it manually.
  67952. */
  67953. var ModelShape = /** @class */ (function () {
  67954. /**
  67955. * 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.
  67956. * SPS internal tool, don't use it manually.
  67957. * @hidden
  67958. */
  67959. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  67960. /**
  67961. * length of the shape in the model indices array (internal use)
  67962. * @hidden
  67963. */
  67964. this._indicesLength = 0;
  67965. this.shapeID = id;
  67966. this._shape = shape;
  67967. this._indicesLength = indicesLength;
  67968. this._shapeUV = shapeUV;
  67969. this._positionFunction = posFunction;
  67970. this._vertexFunction = vtxFunction;
  67971. }
  67972. return ModelShape;
  67973. }());
  67974. BABYLON.ModelShape = ModelShape;
  67975. /**
  67976. * Represents a Depth Sorted Particle in the solid particle system.
  67977. */
  67978. var DepthSortedParticle = /** @class */ (function () {
  67979. function DepthSortedParticle() {
  67980. /**
  67981. * Index of the particle in the "indices" array
  67982. */
  67983. this.ind = 0;
  67984. /**
  67985. * Length of the particle shape in the "indices" array
  67986. */
  67987. this.indicesLength = 0;
  67988. /**
  67989. * Squared distance from the particle to the camera
  67990. */
  67991. this.sqDistance = 0.0;
  67992. }
  67993. return DepthSortedParticle;
  67994. }());
  67995. BABYLON.DepthSortedParticle = DepthSortedParticle;
  67996. })(BABYLON || (BABYLON = {}));
  67997. //# sourceMappingURL=solidParticle.js.map
  67998. var BABYLON;
  67999. (function (BABYLON) {
  68000. var depthSortFunction = function (p1, p2) { return p2.sqDistance - p1.sqDistance; };
  68001. /**
  68002. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  68003. *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.
  68004. * The SPS is also a particle system. It provides some methods to manage the particles.
  68005. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  68006. *
  68007. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  68008. */
  68009. var SolidParticleSystem = /** @class */ (function () {
  68010. /**
  68011. * Creates a SPS (Solid Particle System) object.
  68012. * @param name (String) is the SPS name, this will be the underlying mesh name.
  68013. * @param scene (Scene) is the scene in which the SPS is added.
  68014. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  68015. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  68016. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  68017. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  68018. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  68019. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  68020. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  68021. */
  68022. function SolidParticleSystem(name, scene, options) {
  68023. /**
  68024. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  68025. * Example : var p = SPS.particles[i];
  68026. */
  68027. this.particles = new Array();
  68028. /**
  68029. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  68030. */
  68031. this.nbParticles = 0;
  68032. /**
  68033. * If the particles must ever face the camera (default false). Useful for planar particles.
  68034. */
  68035. this.billboard = false;
  68036. /**
  68037. * Recompute normals when adding a shape
  68038. */
  68039. this.recomputeNormals = true;
  68040. /**
  68041. * This a counter ofr your own usage. It's not set by any SPS functions.
  68042. */
  68043. this.counter = 0;
  68044. /**
  68045. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  68046. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  68047. */
  68048. this.vars = {};
  68049. /**
  68050. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  68051. * @hidden
  68052. */
  68053. this._bSphereOnly = false;
  68054. /**
  68055. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  68056. * @hidden
  68057. */
  68058. this._bSphereRadiusFactor = 1.0;
  68059. this._positions = new Array();
  68060. this._indices = new Array();
  68061. this._normals = new Array();
  68062. this._colors = new Array();
  68063. this._uvs = new Array();
  68064. this._index = 0; // indices index
  68065. this._updatable = true;
  68066. this._pickable = false;
  68067. this._isVisibilityBoxLocked = false;
  68068. this._alwaysVisible = false;
  68069. this._depthSort = false;
  68070. this._shapeCounter = 0;
  68071. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  68072. this._color = new BABYLON.Color4(0, 0, 0, 0);
  68073. this._computeParticleColor = true;
  68074. this._computeParticleTexture = true;
  68075. this._computeParticleRotation = true;
  68076. this._computeParticleVertex = false;
  68077. this._computeBoundingBox = false;
  68078. this._depthSortParticles = true;
  68079. this._mustUnrotateFixedNormals = false;
  68080. this._particlesIntersect = false;
  68081. this._needs32Bits = false;
  68082. this.name = name;
  68083. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  68084. this._camera = scene.activeCamera;
  68085. this._pickable = options ? options.isPickable : false;
  68086. this._depthSort = options ? options.enableDepthSort : false;
  68087. this._particlesIntersect = options ? options.particleIntersection : false;
  68088. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  68089. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  68090. if (options && options.updatable !== undefined) {
  68091. this._updatable = options.updatable;
  68092. }
  68093. else {
  68094. this._updatable = true;
  68095. }
  68096. if (this._pickable) {
  68097. this.pickedParticles = [];
  68098. }
  68099. if (this._depthSort) {
  68100. this.depthSortedParticles = [];
  68101. }
  68102. }
  68103. /**
  68104. * Builds the SPS underlying mesh. Returns a standard Mesh.
  68105. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  68106. * @returns the created mesh
  68107. */
  68108. SolidParticleSystem.prototype.buildMesh = function () {
  68109. if (this.nbParticles === 0) {
  68110. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  68111. this.addShape(triangle, 1);
  68112. triangle.dispose();
  68113. }
  68114. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  68115. this._positions32 = new Float32Array(this._positions);
  68116. this._uvs32 = new Float32Array(this._uvs);
  68117. this._colors32 = new Float32Array(this._colors);
  68118. if (this.recomputeNormals) {
  68119. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  68120. }
  68121. this._normals32 = new Float32Array(this._normals);
  68122. this._fixedNormal32 = new Float32Array(this._normals);
  68123. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  68124. this._unrotateFixedNormals();
  68125. }
  68126. var vertexData = new BABYLON.VertexData();
  68127. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  68128. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  68129. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  68130. if (this._uvs32.length > 0) {
  68131. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  68132. }
  68133. if (this._colors32.length > 0) {
  68134. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  68135. }
  68136. var mesh = new BABYLON.Mesh(this.name, this._scene);
  68137. vertexData.applyToMesh(mesh, this._updatable);
  68138. this.mesh = mesh;
  68139. this.mesh.isPickable = this._pickable;
  68140. // free memory
  68141. if (!this._depthSort) {
  68142. this._indices = null;
  68143. }
  68144. this._positions = null;
  68145. this._normals = null;
  68146. this._uvs = null;
  68147. this._colors = null;
  68148. if (!this._updatable) {
  68149. this.particles.length = 0;
  68150. }
  68151. return mesh;
  68152. };
  68153. /**
  68154. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  68155. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  68156. * Thus the particles generated from `digest()` have their property `position` set yet.
  68157. * @param mesh ( Mesh ) is the mesh to be digested
  68158. * @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
  68159. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  68160. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  68161. * @returns the current SPS
  68162. */
  68163. SolidParticleSystem.prototype.digest = function (mesh, options) {
  68164. var size = (options && options.facetNb) || 1;
  68165. var number = (options && options.number) || 0;
  68166. var delta = (options && options.delta) || 0;
  68167. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68168. var meshInd = mesh.getIndices();
  68169. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  68170. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  68171. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68172. var f = 0; // facet counter
  68173. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  68174. // compute size from number
  68175. if (number) {
  68176. number = (number > totalFacets) ? totalFacets : number;
  68177. size = Math.round(totalFacets / number);
  68178. delta = 0;
  68179. }
  68180. else {
  68181. size = (size > totalFacets) ? totalFacets : size;
  68182. }
  68183. var facetPos = []; // submesh positions
  68184. var facetInd = []; // submesh indices
  68185. var facetUV = []; // submesh UV
  68186. var facetCol = []; // submesh colors
  68187. var barycenter = BABYLON.Vector3.Zero();
  68188. var sizeO = size;
  68189. while (f < totalFacets) {
  68190. size = sizeO + Math.floor((1 + delta) * Math.random());
  68191. if (f > totalFacets - size) {
  68192. size = totalFacets - f;
  68193. }
  68194. // reset temp arrays
  68195. facetPos.length = 0;
  68196. facetInd.length = 0;
  68197. facetUV.length = 0;
  68198. facetCol.length = 0;
  68199. // iterate over "size" facets
  68200. var fi = 0;
  68201. for (var j = f * 3; j < (f + size) * 3; j++) {
  68202. facetInd.push(fi);
  68203. var i = meshInd[j];
  68204. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  68205. if (meshUV) {
  68206. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  68207. }
  68208. if (meshCol) {
  68209. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  68210. }
  68211. fi++;
  68212. }
  68213. // create a model shape for each single particle
  68214. var idx = this.nbParticles;
  68215. var shape = this._posToShape(facetPos);
  68216. var shapeUV = this._uvsToShapeUV(facetUV);
  68217. // compute the barycenter of the shape
  68218. var v;
  68219. for (v = 0; v < shape.length; v++) {
  68220. barycenter.addInPlace(shape[v]);
  68221. }
  68222. barycenter.scaleInPlace(1 / shape.length);
  68223. // shift the shape from its barycenter to the origin
  68224. for (v = 0; v < shape.length; v++) {
  68225. shape[v].subtractInPlace(barycenter);
  68226. }
  68227. var bInfo;
  68228. if (this._particlesIntersect) {
  68229. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  68230. }
  68231. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  68232. // add the particle in the SPS
  68233. var currentPos = this._positions.length;
  68234. var currentInd = this._indices.length;
  68235. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  68236. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  68237. // initialize the particle position
  68238. this.particles[this.nbParticles].position.addInPlace(barycenter);
  68239. this._index += shape.length;
  68240. idx++;
  68241. this.nbParticles++;
  68242. this._shapeCounter++;
  68243. f += size;
  68244. }
  68245. return this;
  68246. };
  68247. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  68248. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  68249. var index = 0;
  68250. var idx = 0;
  68251. var tmpNormal = BABYLON.Tmp.Vector3[0];
  68252. var quaternion = BABYLON.Tmp.Quaternion[0];
  68253. var invertedRotMatrix = BABYLON.Tmp.Matrix[0];
  68254. for (var p = 0; p < this.particles.length; p++) {
  68255. var particle = this.particles[p];
  68256. var shape = particle._model._shape;
  68257. // computing the inverse of the rotation matrix from the quaternion
  68258. // is equivalent to computing the matrix of the inverse quaternion, i.e of the conjugate quaternion
  68259. if (particle.rotationQuaternion) {
  68260. particle.rotationQuaternion.conjugateToRef(quaternion);
  68261. }
  68262. else {
  68263. var rotation = particle.rotation;
  68264. BABYLON.Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion);
  68265. quaternion.conjugateInPlace();
  68266. }
  68267. quaternion.toRotationMatrix(invertedRotMatrix);
  68268. for (var pt = 0; pt < shape.length; pt++) {
  68269. idx = index + pt * 3;
  68270. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], invertedRotMatrix, tmpNormal);
  68271. tmpNormal.toArray(this._fixedNormal32, idx);
  68272. }
  68273. index = idx + 3;
  68274. }
  68275. };
  68276. //reset copy
  68277. SolidParticleSystem.prototype._resetCopy = function () {
  68278. var copy = this._copy;
  68279. copy.position.setAll(0);
  68280. copy.rotation.setAll(0);
  68281. copy.rotationQuaternion = null;
  68282. copy.scaling.setAll(1);
  68283. copy.uvs.copyFromFloats(0.0, 0.0, 1.0, 1.0);
  68284. copy.color = null;
  68285. copy.translateFromPivot = false;
  68286. };
  68287. // _meshBuilder : inserts the shape model in the global SPS mesh
  68288. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  68289. var i;
  68290. var u = 0;
  68291. var c = 0;
  68292. var n = 0;
  68293. this._resetCopy();
  68294. var copy = this._copy;
  68295. if (options && options.positionFunction) { // call to custom positionFunction
  68296. options.positionFunction(copy, idx, idxInShape);
  68297. this._mustUnrotateFixedNormals = true;
  68298. }
  68299. var rotMatrix = BABYLON.Tmp.Matrix[0];
  68300. var tmpVertex = BABYLON.Tmp.Vector3[0];
  68301. var tmpRotated = BABYLON.Tmp.Vector3[1];
  68302. var pivotBackTranslation = BABYLON.Tmp.Vector3[2];
  68303. var scaledPivot = BABYLON.Tmp.Vector3[3];
  68304. copy.getRotationMatrix(rotMatrix);
  68305. copy.pivot.multiplyToRef(copy.scaling, scaledPivot);
  68306. if (copy.translateFromPivot) {
  68307. pivotBackTranslation.setAll(0.0);
  68308. }
  68309. else {
  68310. pivotBackTranslation.copyFrom(scaledPivot);
  68311. }
  68312. for (i = 0; i < shape.length; i++) {
  68313. tmpVertex.copyFrom(shape[i]);
  68314. if (options && options.vertexFunction) {
  68315. options.vertexFunction(copy, tmpVertex, i);
  68316. }
  68317. tmpVertex.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot);
  68318. BABYLON.Vector3.TransformCoordinatesToRef(tmpVertex, rotMatrix, tmpRotated);
  68319. tmpRotated.addInPlace(pivotBackTranslation).addInPlace(copy.position);
  68320. positions.push(tmpRotated.x, tmpRotated.y, tmpRotated.z);
  68321. if (meshUV) {
  68322. var copyUvs = copy.uvs;
  68323. uvs.push((copyUvs.z - copyUvs.x) * meshUV[u] + copyUvs.x, (copyUvs.w - copyUvs.y) * meshUV[u + 1] + copyUvs.y);
  68324. u += 2;
  68325. }
  68326. if (copy.color) {
  68327. this._color = copy.color;
  68328. }
  68329. else {
  68330. var color = this._color;
  68331. if (meshCol && meshCol[c] !== undefined) {
  68332. color.r = meshCol[c];
  68333. color.g = meshCol[c + 1];
  68334. color.b = meshCol[c + 2];
  68335. color.a = meshCol[c + 3];
  68336. }
  68337. else {
  68338. color.r = 1.0;
  68339. color.g = 1.0;
  68340. color.b = 1.0;
  68341. color.a = 1.0;
  68342. }
  68343. }
  68344. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  68345. c += 4;
  68346. if (!this.recomputeNormals && meshNor) {
  68347. tmpVertex.x = meshNor[n];
  68348. tmpVertex.y = meshNor[n + 1];
  68349. tmpVertex.z = meshNor[n + 2];
  68350. BABYLON.Vector3.TransformNormalToRef(tmpVertex, rotMatrix, tmpVertex);
  68351. normals.push(tmpVertex.x, tmpVertex.y, tmpVertex.z);
  68352. n += 3;
  68353. }
  68354. }
  68355. for (i = 0; i < meshInd.length; i++) {
  68356. var current_ind = p + meshInd[i];
  68357. indices.push(current_ind);
  68358. if (current_ind > 65535) {
  68359. this._needs32Bits = true;
  68360. }
  68361. }
  68362. if (this._pickable) {
  68363. var nbfaces = meshInd.length / 3;
  68364. for (i = 0; i < nbfaces; i++) {
  68365. this.pickedParticles.push({ idx: idx, faceId: i });
  68366. }
  68367. }
  68368. if (this._depthSort) {
  68369. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  68370. }
  68371. return copy;
  68372. };
  68373. // returns a shape array from positions array
  68374. SolidParticleSystem.prototype._posToShape = function (positions) {
  68375. var shape = [];
  68376. for (var i = 0; i < positions.length; i += 3) {
  68377. shape.push(BABYLON.Vector3.FromArray(positions, i));
  68378. }
  68379. return shape;
  68380. };
  68381. // returns a shapeUV array from a Vector4 uvs
  68382. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  68383. var shapeUV = [];
  68384. if (uvs) {
  68385. for (var i = 0; i < uvs.length; i++) {
  68386. shapeUV.push(uvs[i]);
  68387. }
  68388. }
  68389. return shapeUV;
  68390. };
  68391. // adds a new particle object in the particles array
  68392. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  68393. if (bInfo === void 0) { bInfo = null; }
  68394. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  68395. this.particles.push(sp);
  68396. return sp;
  68397. };
  68398. /**
  68399. * Adds some particles to the SPS from the model shape. Returns the shape id.
  68400. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  68401. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  68402. * @param nb (positive integer) the number of particles to be created from this model
  68403. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  68404. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  68405. * @returns the number of shapes in the system
  68406. */
  68407. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  68408. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68409. var meshInd = mesh.getIndices();
  68410. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  68411. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  68412. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68413. var bbInfo;
  68414. if (this._particlesIntersect) {
  68415. bbInfo = mesh.getBoundingInfo();
  68416. }
  68417. var shape = this._posToShape(meshPos);
  68418. var shapeUV = this._uvsToShapeUV(meshUV);
  68419. var posfunc = options ? options.positionFunction : null;
  68420. var vtxfunc = options ? options.vertexFunction : null;
  68421. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  68422. // particles
  68423. var sp;
  68424. var currentCopy;
  68425. var idx = this.nbParticles;
  68426. for (var i = 0; i < nb; i++) {
  68427. var currentPos = this._positions.length;
  68428. var currentInd = this._indices.length;
  68429. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  68430. if (this._updatable) {
  68431. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  68432. sp.position.copyFrom(currentCopy.position);
  68433. sp.rotation.copyFrom(currentCopy.rotation);
  68434. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  68435. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  68436. }
  68437. if (currentCopy.color && sp.color) {
  68438. sp.color.copyFrom(currentCopy.color);
  68439. }
  68440. sp.scaling.copyFrom(currentCopy.scaling);
  68441. sp.uvs.copyFrom(currentCopy.uvs);
  68442. }
  68443. this._index += shape.length;
  68444. idx++;
  68445. }
  68446. this.nbParticles += nb;
  68447. this._shapeCounter++;
  68448. return this._shapeCounter - 1;
  68449. };
  68450. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  68451. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  68452. this._resetCopy();
  68453. var copy = this._copy;
  68454. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  68455. particle._model._positionFunction(copy, particle.idx, particle.idxInShape);
  68456. }
  68457. var rotMatrix = BABYLON.Tmp.Matrix[0];
  68458. var tmpVertex = BABYLON.Tmp.Vector3[0];
  68459. var tmpRotated = BABYLON.Tmp.Vector3[1];
  68460. var pivotBackTranslation = BABYLON.Tmp.Vector3[2];
  68461. var scaledPivot = BABYLON.Tmp.Vector3[3];
  68462. copy.getRotationMatrix(rotMatrix);
  68463. particle.pivot.multiplyToRef(particle.scaling, scaledPivot);
  68464. if (copy.translateFromPivot) {
  68465. pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  68466. }
  68467. else {
  68468. pivotBackTranslation.copyFrom(scaledPivot);
  68469. }
  68470. var shape = particle._model._shape;
  68471. for (var pt = 0; pt < shape.length; pt++) {
  68472. tmpVertex.copyFrom(shape[pt]);
  68473. if (particle._model._vertexFunction) {
  68474. particle._model._vertexFunction(copy, tmpVertex, pt); // recall to stored vertexFunction
  68475. }
  68476. tmpVertex.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot);
  68477. BABYLON.Vector3.TransformCoordinatesToRef(tmpVertex, rotMatrix, tmpRotated);
  68478. tmpRotated.addInPlace(pivotBackTranslation).addInPlace(copy.position).toArray(this._positions32, particle._pos + pt * 3);
  68479. }
  68480. particle.position.setAll(0.0);
  68481. particle.rotation.setAll(0.0);
  68482. particle.rotationQuaternion = null;
  68483. particle.scaling.setAll(1.0);
  68484. particle.uvs.setAll(0.0);
  68485. particle.pivot.setAll(0.0);
  68486. particle.translateFromPivot = false;
  68487. particle.parentId = null;
  68488. };
  68489. /**
  68490. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  68491. * @returns the SPS.
  68492. */
  68493. SolidParticleSystem.prototype.rebuildMesh = function () {
  68494. for (var p = 0; p < this.particles.length; p++) {
  68495. this._rebuildParticle(this.particles[p]);
  68496. }
  68497. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  68498. return this;
  68499. };
  68500. /**
  68501. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  68502. * This method calls `updateParticle()` for each particle of the SPS.
  68503. * For an animated SPS, it is usually called within the render loop.
  68504. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  68505. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  68506. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  68507. * @returns the SPS.
  68508. */
  68509. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  68510. if (start === void 0) { start = 0; }
  68511. if (end === void 0) { end = this.nbParticles - 1; }
  68512. if (update === void 0) { update = true; }
  68513. if (!this._updatable) {
  68514. return this;
  68515. }
  68516. // custom beforeUpdate
  68517. this.beforeUpdateParticles(start, end, update);
  68518. var rotMatrix = BABYLON.Tmp.Matrix[0];
  68519. var invertedMatrix = BABYLON.Tmp.Matrix[1];
  68520. var mesh = this.mesh;
  68521. var colors32 = this._colors32;
  68522. var positions32 = this._positions32;
  68523. var normals32 = this._normals32;
  68524. var uvs32 = this._uvs32;
  68525. var indices32 = this._indices32;
  68526. var indices = this._indices;
  68527. var fixedNormal32 = this._fixedNormal32;
  68528. var tempVectors = BABYLON.Tmp.Vector3;
  68529. var camAxisX = tempVectors[5].copyFromFloats(1.0, 0.0, 0.0);
  68530. var camAxisY = tempVectors[6].copyFromFloats(0.0, 1.0, 0.0);
  68531. var camAxisZ = tempVectors[7].copyFromFloats(0.0, 0.0, 1.0);
  68532. var minimum = tempVectors[8].setAll(Number.MAX_VALUE);
  68533. var maximum = tempVectors[9].setAll(-Number.MAX_VALUE);
  68534. var camInvertedPosition = tempVectors[10].setAll(0);
  68535. // cases when the World Matrix is to be computed first
  68536. if (this.billboard || this._depthSort) {
  68537. this.mesh.computeWorldMatrix(true);
  68538. this.mesh._worldMatrix.invertToRef(invertedMatrix);
  68539. }
  68540. // if the particles will always face the camera
  68541. if (this.billboard) {
  68542. // compute the camera position and un-rotate it by the current mesh rotation
  68543. var tmpVertex = tempVectors[0];
  68544. this._camera.getDirectionToRef(BABYLON.Axis.Z, tmpVertex);
  68545. BABYLON.Vector3.TransformNormalToRef(tmpVertex, invertedMatrix, camAxisZ);
  68546. camAxisZ.normalize();
  68547. // same for camera up vector extracted from the cam view matrix
  68548. var view = this._camera.getViewMatrix(true);
  68549. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], invertedMatrix, camAxisY);
  68550. BABYLON.Vector3.CrossToRef(camAxisY, camAxisZ, camAxisX);
  68551. camAxisY.normalize();
  68552. camAxisX.normalize();
  68553. }
  68554. // if depthSort, compute the camera global position in the mesh local system
  68555. if (this._depthSort) {
  68556. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, invertedMatrix, camInvertedPosition); // then un-rotate the camera
  68557. }
  68558. BABYLON.Matrix.IdentityToRef(rotMatrix);
  68559. var idx = 0; // current position index in the global array positions32
  68560. var index = 0; // position start index in the global array positions32 of the current particle
  68561. var colidx = 0; // current color index in the global array colors32
  68562. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  68563. var uvidx = 0; // current uv index in the global array uvs32
  68564. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  68565. var pt = 0; // current index in the particle model shape
  68566. if (this.mesh.isFacetDataEnabled) {
  68567. this._computeBoundingBox = true;
  68568. }
  68569. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  68570. if (this._computeBoundingBox) {
  68571. if (start != 0 || end != this.nbParticles - 1) { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  68572. var boundingInfo = this.mesh._boundingInfo;
  68573. if (boundingInfo) {
  68574. minimum.copyFrom(boundingInfo.minimum);
  68575. maximum.copyFrom(boundingInfo.maximum);
  68576. }
  68577. }
  68578. }
  68579. // particle loop
  68580. index = this.particles[start]._pos;
  68581. var vpos = (index / 3) | 0;
  68582. colorIndex = vpos * 4;
  68583. uvIndex = vpos * 2;
  68584. for (var p = start; p <= end; p++) {
  68585. var particle = this.particles[p];
  68586. // call to custom user function to update the particle properties
  68587. this.updateParticle(particle);
  68588. var shape = particle._model._shape;
  68589. var shapeUV = particle._model._shapeUV;
  68590. var particleRotationMatrix = particle._rotationMatrix;
  68591. var particlePosition = particle.position;
  68592. var particleRotation = particle.rotation;
  68593. var particleScaling = particle.scaling;
  68594. var particleGlobalPosition = particle._globalPosition;
  68595. // camera-particle distance for depth sorting
  68596. if (this._depthSort && this._depthSortParticles) {
  68597. var dsp = this.depthSortedParticles[p];
  68598. dsp.ind = particle._ind;
  68599. dsp.indicesLength = particle._model._indicesLength;
  68600. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(particle.position, camInvertedPosition);
  68601. }
  68602. // skip the computations for inactive or already invisible particles
  68603. if (!particle.alive || (particle._stillInvisible && !particle.isVisible)) {
  68604. // increment indexes for the next particle
  68605. pt = shape.length;
  68606. index += pt * 3;
  68607. colorIndex += pt * 4;
  68608. uvIndex += pt * 2;
  68609. continue;
  68610. }
  68611. if (particle.isVisible) {
  68612. particle._stillInvisible = false; // un-mark permanent invisibility
  68613. var scaledPivot = tempVectors[12];
  68614. particle.pivot.multiplyToRef(particleScaling, scaledPivot);
  68615. // particle rotation matrix
  68616. if (this.billboard) {
  68617. particleRotation.x = 0.0;
  68618. particleRotation.y = 0.0;
  68619. }
  68620. if (this._computeParticleRotation || this.billboard) {
  68621. particle.getRotationMatrix(rotMatrix);
  68622. }
  68623. var particleHasParent = (particle.parentId !== null);
  68624. if (particleHasParent) {
  68625. var parent_1 = this.particles[particle.parentId];
  68626. var parentRotationMatrix = parent_1._rotationMatrix;
  68627. var parentGlobalPosition = parent_1._globalPosition;
  68628. var rotatedY = particlePosition.x * parentRotationMatrix[1] + particlePosition.y * parentRotationMatrix[4] + particlePosition.z * parentRotationMatrix[7];
  68629. var rotatedX = particlePosition.x * parentRotationMatrix[0] + particlePosition.y * parentRotationMatrix[3] + particlePosition.z * parentRotationMatrix[6];
  68630. var rotatedZ = particlePosition.x * parentRotationMatrix[2] + particlePosition.y * parentRotationMatrix[5] + particlePosition.z * parentRotationMatrix[8];
  68631. particleGlobalPosition.x = parentGlobalPosition.x + rotatedX;
  68632. particleGlobalPosition.y = parentGlobalPosition.y + rotatedY;
  68633. particleGlobalPosition.z = parentGlobalPosition.z + rotatedZ;
  68634. if (this._computeParticleRotation || this.billboard) {
  68635. var rotMatrixValues = rotMatrix.m;
  68636. particleRotationMatrix[0] = rotMatrixValues[0] * parentRotationMatrix[0] + rotMatrixValues[1] * parentRotationMatrix[3] + rotMatrixValues[2] * parentRotationMatrix[6];
  68637. particleRotationMatrix[1] = rotMatrixValues[0] * parentRotationMatrix[1] + rotMatrixValues[1] * parentRotationMatrix[4] + rotMatrixValues[2] * parentRotationMatrix[7];
  68638. particleRotationMatrix[2] = rotMatrixValues[0] * parentRotationMatrix[2] + rotMatrixValues[1] * parentRotationMatrix[5] + rotMatrixValues[2] * parentRotationMatrix[8];
  68639. particleRotationMatrix[3] = rotMatrixValues[4] * parentRotationMatrix[0] + rotMatrixValues[5] * parentRotationMatrix[3] + rotMatrixValues[6] * parentRotationMatrix[6];
  68640. particleRotationMatrix[4] = rotMatrixValues[4] * parentRotationMatrix[1] + rotMatrixValues[5] * parentRotationMatrix[4] + rotMatrixValues[6] * parentRotationMatrix[7];
  68641. particleRotationMatrix[5] = rotMatrixValues[4] * parentRotationMatrix[2] + rotMatrixValues[5] * parentRotationMatrix[5] + rotMatrixValues[6] * parentRotationMatrix[8];
  68642. particleRotationMatrix[6] = rotMatrixValues[8] * parentRotationMatrix[0] + rotMatrixValues[9] * parentRotationMatrix[3] + rotMatrixValues[10] * parentRotationMatrix[6];
  68643. particleRotationMatrix[7] = rotMatrixValues[8] * parentRotationMatrix[1] + rotMatrixValues[9] * parentRotationMatrix[4] + rotMatrixValues[10] * parentRotationMatrix[7];
  68644. particleRotationMatrix[8] = rotMatrixValues[8] * parentRotationMatrix[2] + rotMatrixValues[9] * parentRotationMatrix[5] + rotMatrixValues[10] * parentRotationMatrix[8];
  68645. }
  68646. }
  68647. else {
  68648. particleGlobalPosition.x = particlePosition.x;
  68649. particleGlobalPosition.y = particlePosition.y;
  68650. particleGlobalPosition.z = particlePosition.z;
  68651. if (this._computeParticleRotation || this.billboard) {
  68652. var rotMatrixValues = rotMatrix.m;
  68653. particleRotationMatrix[0] = rotMatrixValues[0];
  68654. particleRotationMatrix[1] = rotMatrixValues[1];
  68655. particleRotationMatrix[2] = rotMatrixValues[2];
  68656. particleRotationMatrix[3] = rotMatrixValues[4];
  68657. particleRotationMatrix[4] = rotMatrixValues[5];
  68658. particleRotationMatrix[5] = rotMatrixValues[6];
  68659. particleRotationMatrix[6] = rotMatrixValues[8];
  68660. particleRotationMatrix[7] = rotMatrixValues[9];
  68661. particleRotationMatrix[8] = rotMatrixValues[10];
  68662. }
  68663. }
  68664. var pivotBackTranslation = tempVectors[11];
  68665. if (particle.translateFromPivot) {
  68666. pivotBackTranslation.setAll(0.0);
  68667. }
  68668. else {
  68669. pivotBackTranslation.copyFrom(scaledPivot);
  68670. }
  68671. // particle vertex loop
  68672. for (pt = 0; pt < shape.length; pt++) {
  68673. idx = index + pt * 3;
  68674. colidx = colorIndex + pt * 4;
  68675. uvidx = uvIndex + pt * 2;
  68676. var tmpVertex = tempVectors[0];
  68677. tmpVertex.copyFrom(shape[pt]);
  68678. if (this._computeParticleVertex) {
  68679. this.updateParticleVertex(particle, tmpVertex, pt);
  68680. }
  68681. // positions
  68682. var vertexX = tmpVertex.x * particleScaling.x - scaledPivot.x;
  68683. var vertexY = tmpVertex.y * particleScaling.y - scaledPivot.y;
  68684. var vertexZ = tmpVertex.z * particleScaling.z - scaledPivot.z;
  68685. var rotatedX = vertexX * particleRotationMatrix[0] + vertexY * particleRotationMatrix[3] + vertexZ * particleRotationMatrix[6];
  68686. var rotatedY = vertexX * particleRotationMatrix[1] + vertexY * particleRotationMatrix[4] + vertexZ * particleRotationMatrix[7];
  68687. var rotatedZ = vertexX * particleRotationMatrix[2] + vertexY * particleRotationMatrix[5] + vertexZ * particleRotationMatrix[8];
  68688. rotatedX += pivotBackTranslation.x;
  68689. rotatedY += pivotBackTranslation.y;
  68690. rotatedZ += pivotBackTranslation.z;
  68691. var px = positions32[idx] = particleGlobalPosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ;
  68692. var py = positions32[idx + 1] = particleGlobalPosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ;
  68693. var pz = positions32[idx + 2] = particleGlobalPosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ;
  68694. if (this._computeBoundingBox) {
  68695. minimum.minimizeInPlaceFromFloats(px, py, pz);
  68696. maximum.maximizeInPlaceFromFloats(px, py, pz);
  68697. }
  68698. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  68699. if (!this._computeParticleVertex) {
  68700. var normalx = fixedNormal32[idx];
  68701. var normaly = fixedNormal32[idx + 1];
  68702. var normalz = fixedNormal32[idx + 2];
  68703. var rotatedx = normalx * particleRotationMatrix[0] + normaly * particleRotationMatrix[3] + normalz * particleRotationMatrix[6];
  68704. var rotatedy = normalx * particleRotationMatrix[1] + normaly * particleRotationMatrix[4] + normalz * particleRotationMatrix[7];
  68705. var rotatedz = normalx * particleRotationMatrix[2] + normaly * particleRotationMatrix[5] + normalz * particleRotationMatrix[8];
  68706. normals32[idx] = camAxisX.x * rotatedx + camAxisY.x * rotatedy + camAxisZ.x * rotatedz;
  68707. normals32[idx + 1] = camAxisX.y * rotatedx + camAxisY.y * rotatedy + camAxisZ.y * rotatedz;
  68708. normals32[idx + 2] = camAxisX.z * rotatedx + camAxisY.z * rotatedy + camAxisZ.z * rotatedz;
  68709. }
  68710. if (this._computeParticleColor && particle.color) {
  68711. var color = particle.color;
  68712. var colors32_1 = this._colors32;
  68713. colors32_1[colidx] = color.r;
  68714. colors32_1[colidx + 1] = color.g;
  68715. colors32_1[colidx + 2] = color.b;
  68716. colors32_1[colidx + 3] = color.a;
  68717. }
  68718. if (this._computeParticleTexture) {
  68719. var uvs = particle.uvs;
  68720. uvs32[uvidx] = shapeUV[pt * 2] * (uvs.z - uvs.x) + uvs.x;
  68721. uvs32[uvidx + 1] = shapeUV[pt * 2 + 1] * (uvs.w - uvs.y) + uvs.y;
  68722. }
  68723. }
  68724. }
  68725. // particle just set invisible : scaled to zero and positioned at the origin
  68726. else {
  68727. particle._stillInvisible = true; // mark the particle as invisible
  68728. for (pt = 0; pt < shape.length; pt++) {
  68729. idx = index + pt * 3;
  68730. colidx = colorIndex + pt * 4;
  68731. uvidx = uvIndex + pt * 2;
  68732. positions32[idx] = positions32[idx + 1] = positions32[idx + 2] = 0;
  68733. normals32[idx] = normals32[idx + 1] = normals32[idx + 2] = 0;
  68734. if (this._computeParticleColor && particle.color) {
  68735. var color = particle.color;
  68736. colors32[colidx] = color.r;
  68737. colors32[colidx + 1] = color.g;
  68738. colors32[colidx + 2] = color.b;
  68739. colors32[colidx + 3] = color.a;
  68740. }
  68741. if (this._computeParticleTexture) {
  68742. var uvs = particle.uvs;
  68743. uvs32[uvidx] = shapeUV[pt * 2] * (uvs.z - uvs.x) + uvs.x;
  68744. uvs32[uvidx + 1] = shapeUV[pt * 2 + 1] * (uvs.w - uvs.y) + uvs.y;
  68745. }
  68746. }
  68747. }
  68748. // if the particle intersections must be computed : update the bbInfo
  68749. if (this._particlesIntersect) {
  68750. var bInfo = particle._boundingInfo;
  68751. var bBox = bInfo.boundingBox;
  68752. var bSphere = bInfo.boundingSphere;
  68753. var modelBoundingInfo = particle._modelBoundingInfo;
  68754. if (!this._bSphereOnly) {
  68755. // place, scale and rotate the particle bbox within the SPS local system, then update it
  68756. var modelBoundingInfoVectors = modelBoundingInfo.boundingBox.vectors;
  68757. var tempMin = tempVectors[1];
  68758. var tempMax = tempVectors[2];
  68759. tempMin.setAll(Number.MAX_VALUE);
  68760. tempMax.setAll(-Number.MAX_VALUE);
  68761. for (var b = 0; b < 8; b++) {
  68762. var scaledX = modelBoundingInfoVectors[b].x * particleScaling.x;
  68763. var scaledY = modelBoundingInfoVectors[b].y * particleScaling.y;
  68764. var scaledZ = modelBoundingInfoVectors[b].z * particleScaling.z;
  68765. var rotatedX = scaledX * particleRotationMatrix[0] + scaledY * particleRotationMatrix[3] + scaledZ * particleRotationMatrix[6];
  68766. var rotatedY = scaledX * particleRotationMatrix[1] + scaledY * particleRotationMatrix[4] + scaledZ * particleRotationMatrix[7];
  68767. var rotatedZ = scaledX * particleRotationMatrix[2] + scaledY * particleRotationMatrix[5] + scaledZ * particleRotationMatrix[8];
  68768. var x = particlePosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ;
  68769. var y = particlePosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ;
  68770. var z = particlePosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ;
  68771. tempMin.minimizeInPlaceFromFloats(x, y, z);
  68772. tempMax.maximizeInPlaceFromFloats(x, y, z);
  68773. }
  68774. bBox.reConstruct(tempMin, tempMax, mesh._worldMatrix);
  68775. }
  68776. // place and scale the particle bouding sphere in the SPS local system, then update it
  68777. var minBbox = modelBoundingInfo.minimum.multiplyToRef(particleScaling, tempVectors[1]);
  68778. var maxBbox = modelBoundingInfo.maximum.multiplyToRef(particleScaling, tempVectors[2]);
  68779. var bSphereCenter = maxBbox.addToRef(minBbox, tempVectors[3]).scaleInPlace(0.5);
  68780. var halfDiag = maxBbox.subtractToRef(minBbox, tempVectors[4]).scaleInPlace(0.5 * this._bSphereRadiusFactor);
  68781. var bSphereMinBbox = bSphereCenter.subtractToRef(halfDiag, tempVectors[1]);
  68782. var bSphereMaxBbox = bSphereCenter.addToRef(halfDiag, tempVectors[2]);
  68783. bSphere.reConstruct(bSphereMinBbox, bSphereMaxBbox, mesh._worldMatrix);
  68784. }
  68785. // increment indexes for the next particle
  68786. index = idx + 3;
  68787. colorIndex = colidx + 4;
  68788. uvIndex = uvidx + 2;
  68789. }
  68790. // if the VBO must be updated
  68791. if (update) {
  68792. if (this._computeParticleColor) {
  68793. mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors32, false, false);
  68794. }
  68795. if (this._computeParticleTexture) {
  68796. mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs32, false, false);
  68797. }
  68798. mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions32, false, false);
  68799. if (!mesh.areNormalsFrozen || mesh.isFacetDataEnabled) {
  68800. if (this._computeParticleVertex || mesh.isFacetDataEnabled) {
  68801. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  68802. var params = mesh.isFacetDataEnabled ? mesh.getFacetDataParameters() : null;
  68803. BABYLON.VertexData.ComputeNormals(positions32, indices32, normals32, params);
  68804. for (var i = 0; i < normals32.length; i++) {
  68805. fixedNormal32[i] = normals32[i];
  68806. }
  68807. }
  68808. if (!mesh.areNormalsFrozen) {
  68809. mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals32, false, false);
  68810. }
  68811. }
  68812. if (this._depthSort && this._depthSortParticles) {
  68813. var depthSortedParticles = this.depthSortedParticles;
  68814. depthSortedParticles.sort(depthSortFunction);
  68815. var dspl = depthSortedParticles.length;
  68816. var sid = 0;
  68817. for (var sorted = 0; sorted < dspl; sorted++) {
  68818. var lind = depthSortedParticles[sorted].indicesLength;
  68819. var sind = depthSortedParticles[sorted].ind;
  68820. for (var i = 0; i < lind; i++) {
  68821. indices32[sid] = indices[sind + i];
  68822. sid++;
  68823. }
  68824. }
  68825. mesh.updateIndices(indices32);
  68826. }
  68827. }
  68828. if (this._computeBoundingBox) {
  68829. if (mesh._boundingInfo) {
  68830. mesh._boundingInfo.reConstruct(minimum, maximum, mesh._worldMatrix);
  68831. }
  68832. else {
  68833. mesh._boundingInfo = new BABYLON.BoundingInfo(minimum, maximum, mesh._worldMatrix);
  68834. }
  68835. }
  68836. this.afterUpdateParticles(start, end, update);
  68837. return this;
  68838. };
  68839. /**
  68840. * Disposes the SPS.
  68841. */
  68842. SolidParticleSystem.prototype.dispose = function () {
  68843. this.mesh.dispose();
  68844. this.vars = null;
  68845. // drop references to internal big arrays for the GC
  68846. this._positions = null;
  68847. this._indices = null;
  68848. this._normals = null;
  68849. this._uvs = null;
  68850. this._colors = null;
  68851. this._indices32 = null;
  68852. this._positions32 = null;
  68853. this._normals32 = null;
  68854. this._fixedNormal32 = null;
  68855. this._uvs32 = null;
  68856. this._colors32 = null;
  68857. this.pickedParticles = null;
  68858. };
  68859. /**
  68860. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  68861. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68862. * @returns the SPS.
  68863. */
  68864. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  68865. if (!this._isVisibilityBoxLocked) {
  68866. this.mesh.refreshBoundingInfo();
  68867. }
  68868. return this;
  68869. };
  68870. /**
  68871. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  68872. * @param size the size (float) of the visibility box
  68873. * note : this doesn't lock the SPS mesh bounding box.
  68874. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68875. */
  68876. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  68877. var vis = size / 2;
  68878. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  68879. };
  68880. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  68881. /**
  68882. * Gets whether the SPS as always visible or not
  68883. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68884. */
  68885. get: function () {
  68886. return this._alwaysVisible;
  68887. },
  68888. /**
  68889. * Sets the SPS as always visible or not
  68890. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68891. */
  68892. set: function (val) {
  68893. this._alwaysVisible = val;
  68894. this.mesh.alwaysSelectAsActiveMesh = val;
  68895. },
  68896. enumerable: true,
  68897. configurable: true
  68898. });
  68899. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  68900. /**
  68901. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  68902. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68903. */
  68904. get: function () {
  68905. return this._isVisibilityBoxLocked;
  68906. },
  68907. /**
  68908. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  68909. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  68910. */
  68911. set: function (val) {
  68912. this._isVisibilityBoxLocked = val;
  68913. var boundingInfo = this.mesh.getBoundingInfo();
  68914. boundingInfo.isLocked = val;
  68915. },
  68916. enumerable: true,
  68917. configurable: true
  68918. });
  68919. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  68920. /**
  68921. * Gets if `setParticles()` computes the particle rotations or not.
  68922. * Default value : true. The SPS is faster when it's set to false.
  68923. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  68924. */
  68925. get: function () {
  68926. return this._computeParticleRotation;
  68927. },
  68928. /**
  68929. * Tells to `setParticles()` to compute the particle rotations or not.
  68930. * Default value : true. The SPS is faster when it's set to false.
  68931. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  68932. */
  68933. set: function (val) {
  68934. this._computeParticleRotation = val;
  68935. },
  68936. enumerable: true,
  68937. configurable: true
  68938. });
  68939. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  68940. /**
  68941. * Gets if `setParticles()` computes the particle colors or not.
  68942. * Default value : true. The SPS is faster when it's set to false.
  68943. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  68944. */
  68945. get: function () {
  68946. return this._computeParticleColor;
  68947. },
  68948. /**
  68949. * Tells to `setParticles()` to compute the particle colors or not.
  68950. * Default value : true. The SPS is faster when it's set to false.
  68951. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  68952. */
  68953. set: function (val) {
  68954. this._computeParticleColor = val;
  68955. },
  68956. enumerable: true,
  68957. configurable: true
  68958. });
  68959. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  68960. /**
  68961. * Gets if `setParticles()` computes the particle textures or not.
  68962. * Default value : true. The SPS is faster when it's set to false.
  68963. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  68964. */
  68965. get: function () {
  68966. return this._computeParticleTexture;
  68967. },
  68968. set: function (val) {
  68969. this._computeParticleTexture = val;
  68970. },
  68971. enumerable: true,
  68972. configurable: true
  68973. });
  68974. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  68975. /**
  68976. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  68977. * Default value : false. The SPS is faster when it's set to false.
  68978. * Note : the particle custom vertex positions aren't stored values.
  68979. */
  68980. get: function () {
  68981. return this._computeParticleVertex;
  68982. },
  68983. /**
  68984. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  68985. * Default value : false. The SPS is faster when it's set to false.
  68986. * Note : the particle custom vertex positions aren't stored values.
  68987. */
  68988. set: function (val) {
  68989. this._computeParticleVertex = val;
  68990. },
  68991. enumerable: true,
  68992. configurable: true
  68993. });
  68994. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  68995. /**
  68996. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  68997. */
  68998. get: function () {
  68999. return this._computeBoundingBox;
  69000. },
  69001. /**
  69002. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  69003. */
  69004. set: function (val) {
  69005. this._computeBoundingBox = val;
  69006. },
  69007. enumerable: true,
  69008. configurable: true
  69009. });
  69010. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  69011. /**
  69012. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  69013. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  69014. * Default : `true`
  69015. */
  69016. get: function () {
  69017. return this._depthSortParticles;
  69018. },
  69019. /**
  69020. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  69021. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  69022. * Default : `true`
  69023. */
  69024. set: function (val) {
  69025. this._depthSortParticles = val;
  69026. },
  69027. enumerable: true,
  69028. configurable: true
  69029. });
  69030. // =======================================================================
  69031. // Particle behavior logic
  69032. // these following methods may be overwritten by the user to fit his needs
  69033. /**
  69034. * This function does nothing. It may be overwritten to set all the particle first values.
  69035. * The SPS doesn't call this function, you may have to call it by your own.
  69036. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  69037. */
  69038. SolidParticleSystem.prototype.initParticles = function () {
  69039. };
  69040. /**
  69041. * This function does nothing. It may be overwritten to recycle a particle.
  69042. * The SPS doesn't call this function, you may have to call it by your own.
  69043. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  69044. * @param particle The particle to recycle
  69045. * @returns the recycled particle
  69046. */
  69047. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  69048. return particle;
  69049. };
  69050. /**
  69051. * Updates a particle : this function should be overwritten by the user.
  69052. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  69053. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  69054. * @example : just set a particle position or velocity and recycle conditions
  69055. * @param particle The particle to update
  69056. * @returns the updated particle
  69057. */
  69058. SolidParticleSystem.prototype.updateParticle = function (particle) {
  69059. return particle;
  69060. };
  69061. /**
  69062. * Updates a vertex of a particle : it can be overwritten by the user.
  69063. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  69064. * @param particle the current particle
  69065. * @param vertex the current index of the current particle
  69066. * @param pt the index of the current vertex in the particle shape
  69067. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  69068. * @example : just set a vertex particle position
  69069. * @returns the updated vertex
  69070. */
  69071. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  69072. return vertex;
  69073. };
  69074. /**
  69075. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  69076. * This does nothing and may be overwritten by the user.
  69077. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  69078. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  69079. * @param update the boolean update value actually passed to setParticles()
  69080. */
  69081. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  69082. };
  69083. /**
  69084. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  69085. * This will be passed three parameters.
  69086. * This does nothing and may be overwritten by the user.
  69087. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  69088. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  69089. * @param update the boolean update value actually passed to setParticles()
  69090. */
  69091. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  69092. };
  69093. return SolidParticleSystem;
  69094. }());
  69095. BABYLON.SolidParticleSystem = SolidParticleSystem;
  69096. })(BABYLON || (BABYLON = {}));
  69097. //# sourceMappingURL=solidParticleSystem.js.map
  69098. var BABYLON;
  69099. (function (BABYLON) {
  69100. /**
  69101. * Class containing static functions to help procedurally build meshes
  69102. */
  69103. var MeshBuilder = /** @class */ (function () {
  69104. function MeshBuilder() {
  69105. }
  69106. MeshBuilder.updateSideOrientation = function (orientation) {
  69107. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  69108. return BABYLON.Mesh.DOUBLESIDE;
  69109. }
  69110. if (orientation === undefined || orientation === null) {
  69111. return BABYLON.Mesh.FRONTSIDE;
  69112. }
  69113. return orientation;
  69114. };
  69115. /**
  69116. * Creates a box mesh
  69117. * * The parameter `size` sets the size (float) of each box side (default 1)
  69118. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  69119. * * 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)
  69120. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  69121. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69122. * * 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
  69123. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69124. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  69125. * @param name defines the name of the mesh
  69126. * @param options defines the options used to create the mesh
  69127. * @param scene defines the hosting scene
  69128. * @returns the box mesh
  69129. */
  69130. MeshBuilder.CreateBox = function (name, options, scene) {
  69131. if (scene === void 0) { scene = null; }
  69132. var box = new BABYLON.Mesh(name, scene);
  69133. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69134. box._originalBuilderSideOrientation = options.sideOrientation;
  69135. var vertexData = BABYLON.VertexData.CreateBox(options);
  69136. vertexData.applyToMesh(box, options.updatable);
  69137. return box;
  69138. };
  69139. /**
  69140. * Creates a sphere mesh
  69141. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  69142. * * 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`)
  69143. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  69144. * * 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
  69145. * * 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)
  69146. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69147. * * 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
  69148. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69149. * @param name defines the name of the mesh
  69150. * @param options defines the options used to create the mesh
  69151. * @param scene defines the hosting scene
  69152. * @returns the sphere mesh
  69153. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  69154. */
  69155. MeshBuilder.CreateSphere = function (name, options, scene) {
  69156. var sphere = new BABYLON.Mesh(name, scene);
  69157. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69158. sphere._originalBuilderSideOrientation = options.sideOrientation;
  69159. var vertexData = BABYLON.VertexData.CreateSphere(options);
  69160. vertexData.applyToMesh(sphere, options.updatable);
  69161. return sphere;
  69162. };
  69163. /**
  69164. * Creates a plane polygonal mesh. By default, this is a disc
  69165. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  69166. * * 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
  69167. * * 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
  69168. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69169. * * 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
  69170. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69171. * @param name defines the name of the mesh
  69172. * @param options defines the options used to create the mesh
  69173. * @param scene defines the hosting scene
  69174. * @returns the plane polygonal mesh
  69175. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  69176. */
  69177. MeshBuilder.CreateDisc = function (name, options, scene) {
  69178. if (scene === void 0) { scene = null; }
  69179. var disc = new BABYLON.Mesh(name, scene);
  69180. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69181. disc._originalBuilderSideOrientation = options.sideOrientation;
  69182. var vertexData = BABYLON.VertexData.CreateDisc(options);
  69183. vertexData.applyToMesh(disc, options.updatable);
  69184. return disc;
  69185. };
  69186. /**
  69187. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  69188. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  69189. * * 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`)
  69190. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  69191. * * 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
  69192. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69193. * * 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
  69194. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69195. * @param name defines the name of the mesh
  69196. * @param options defines the options used to create the mesh
  69197. * @param scene defines the hosting scene
  69198. * @returns the icosahedron mesh
  69199. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  69200. */
  69201. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  69202. var sphere = new BABYLON.Mesh(name, scene);
  69203. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69204. sphere._originalBuilderSideOrientation = options.sideOrientation;
  69205. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  69206. vertexData.applyToMesh(sphere, options.updatable);
  69207. return sphere;
  69208. };
  69209. /**
  69210. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  69211. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  69212. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  69213. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  69214. * * 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
  69215. * * 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
  69216. * * 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
  69217. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69218. * * 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
  69219. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  69220. * * 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
  69221. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  69222. * * 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
  69223. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  69224. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69225. * @param name defines the name of the mesh
  69226. * @param options defines the options used to create the mesh
  69227. * @param scene defines the hosting scene
  69228. * @returns the ribbon mesh
  69229. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  69230. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  69231. */
  69232. MeshBuilder.CreateRibbon = function (name, options, scene) {
  69233. if (scene === void 0) { scene = null; }
  69234. var pathArray = options.pathArray;
  69235. var closeArray = options.closeArray;
  69236. var closePath = options.closePath;
  69237. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69238. var instance = options.instance;
  69239. var updatable = options.updatable;
  69240. if (instance) { // existing ribbon instance update
  69241. // positionFunction : ribbon case
  69242. // only pathArray and sideOrientation parameters are taken into account for positions update
  69243. var minimum_1 = BABYLON.Tmp.Vector3[0].setAll(Number.MAX_VALUE);
  69244. var maximum_1 = BABYLON.Tmp.Vector3[1].setAll(-Number.MAX_VALUE);
  69245. var positionFunction = function (positions) {
  69246. var minlg = pathArray[0].length;
  69247. var mesh = instance;
  69248. var i = 0;
  69249. var ns = (mesh._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  69250. for (var si = 1; si <= ns; ++si) {
  69251. for (var p = 0; p < pathArray.length; ++p) {
  69252. var path = pathArray[p];
  69253. var l = path.length;
  69254. minlg = (minlg < l) ? minlg : l;
  69255. for (var j = 0; j < minlg; ++j) {
  69256. var pathPoint = path[j];
  69257. positions[i] = pathPoint.x;
  69258. positions[i + 1] = pathPoint.y;
  69259. positions[i + 2] = pathPoint.z;
  69260. minimum_1.minimizeInPlaceFromFloats(pathPoint.x, pathPoint.y, pathPoint.z);
  69261. maximum_1.maximizeInPlaceFromFloats(pathPoint.x, pathPoint.y, pathPoint.z);
  69262. i += 3;
  69263. }
  69264. if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) {
  69265. var pathPoint = path[0];
  69266. positions[i] = pathPoint.x;
  69267. positions[i + 1] = pathPoint.y;
  69268. positions[i + 2] = pathPoint.z;
  69269. i += 3;
  69270. }
  69271. }
  69272. }
  69273. };
  69274. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  69275. positionFunction(positions);
  69276. if (instance._boundingInfo) {
  69277. instance._boundingInfo.reConstruct(minimum_1, maximum_1, instance._worldMatrix);
  69278. }
  69279. else {
  69280. instance._boundingInfo = new BABYLON.BoundingInfo(minimum_1, maximum_1, instance._worldMatrix);
  69281. }
  69282. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  69283. if (options.colors) {
  69284. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  69285. for (var c = 0, colorIndex = 0; c < options.colors.length; c++, colorIndex += 4) {
  69286. var color = options.colors[c];
  69287. colors[colorIndex] = color.r;
  69288. colors[colorIndex + 1] = color.g;
  69289. colors[colorIndex + 2] = color.b;
  69290. colors[colorIndex + 3] = color.a;
  69291. }
  69292. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  69293. }
  69294. if (options.uvs) {
  69295. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  69296. for (var i = 0; i < options.uvs.length; i++) {
  69297. uvs[i * 2] = options.uvs[i].x;
  69298. uvs[i * 2 + 1] = options.uvs[i].y;
  69299. }
  69300. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  69301. }
  69302. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  69303. var indices = instance.getIndices();
  69304. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  69305. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  69306. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  69307. if (instance._creationDataStorage && instance._creationDataStorage.closePath) {
  69308. var indexFirst = 0;
  69309. var indexLast = 0;
  69310. for (var p = 0; p < pathArray.length; p++) {
  69311. indexFirst = instance._creationDataStorage.idx[p] * 3;
  69312. if (p + 1 < pathArray.length) {
  69313. indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3;
  69314. }
  69315. else {
  69316. indexLast = normals.length - 3;
  69317. }
  69318. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  69319. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  69320. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  69321. normals[indexLast] = normals[indexFirst];
  69322. normals[indexLast + 1] = normals[indexFirst + 1];
  69323. normals[indexLast + 2] = normals[indexFirst + 2];
  69324. }
  69325. }
  69326. if (!(instance.areNormalsFrozen)) {
  69327. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  69328. }
  69329. }
  69330. return instance;
  69331. }
  69332. else { // new ribbon creation
  69333. var ribbon = new BABYLON.Mesh(name, scene);
  69334. ribbon._originalBuilderSideOrientation = sideOrientation;
  69335. ribbon._creationDataStorage = new BABYLON._CreationDataStorage();
  69336. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  69337. if (closePath) {
  69338. ribbon._creationDataStorage.idx = vertexData._idx;
  69339. }
  69340. ribbon._creationDataStorage.closePath = closePath;
  69341. ribbon._creationDataStorage.closeArray = closeArray;
  69342. vertexData.applyToMesh(ribbon, updatable);
  69343. return ribbon;
  69344. }
  69345. };
  69346. /**
  69347. * Creates a cylinder or a cone mesh
  69348. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  69349. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  69350. * * 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.
  69351. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  69352. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  69353. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  69354. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  69355. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  69356. * * 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).
  69357. * * 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
  69358. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  69359. * * 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
  69360. * * 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.
  69361. * * If `enclose` is false, a ring surface is one element.
  69362. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  69363. * * 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
  69364. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69365. * * 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
  69366. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69367. * @param name defines the name of the mesh
  69368. * @param options defines the options used to create the mesh
  69369. * @param scene defines the hosting scene
  69370. * @returns the cylinder mesh
  69371. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  69372. */
  69373. MeshBuilder.CreateCylinder = function (name, options, scene) {
  69374. var cylinder = new BABYLON.Mesh(name, scene);
  69375. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69376. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  69377. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  69378. vertexData.applyToMesh(cylinder, options.updatable);
  69379. return cylinder;
  69380. };
  69381. /**
  69382. * Creates a torus mesh
  69383. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  69384. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  69385. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  69386. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69387. * * 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
  69388. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69389. * @param name defines the name of the mesh
  69390. * @param options defines the options used to create the mesh
  69391. * @param scene defines the hosting scene
  69392. * @returns the torus mesh
  69393. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  69394. */
  69395. MeshBuilder.CreateTorus = function (name, options, scene) {
  69396. var torus = new BABYLON.Mesh(name, scene);
  69397. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69398. torus._originalBuilderSideOrientation = options.sideOrientation;
  69399. var vertexData = BABYLON.VertexData.CreateTorus(options);
  69400. vertexData.applyToMesh(torus, options.updatable);
  69401. return torus;
  69402. };
  69403. /**
  69404. * Creates a torus knot mesh
  69405. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  69406. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  69407. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  69408. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  69409. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69410. * * 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
  69411. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69412. * @param name defines the name of the mesh
  69413. * @param options defines the options used to create the mesh
  69414. * @param scene defines the hosting scene
  69415. * @returns the torus knot mesh
  69416. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  69417. */
  69418. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  69419. var torusKnot = new BABYLON.Mesh(name, scene);
  69420. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69421. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  69422. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  69423. vertexData.applyToMesh(torusKnot, options.updatable);
  69424. return torusKnot;
  69425. };
  69426. /**
  69427. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  69428. * * 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
  69429. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  69430. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  69431. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  69432. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  69433. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  69434. * * 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
  69435. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  69436. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69437. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  69438. * @param name defines the name of the new line system
  69439. * @param options defines the options used to create the line system
  69440. * @param scene defines the hosting scene
  69441. * @returns a new line system mesh
  69442. */
  69443. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  69444. var instance = options.instance;
  69445. var lines = options.lines;
  69446. var colors = options.colors;
  69447. if (instance) { // lines update
  69448. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  69449. var vertexColor;
  69450. var lineColors;
  69451. if (colors) {
  69452. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  69453. }
  69454. var i = 0;
  69455. var c = 0;
  69456. for (var l = 0; l < lines.length; l++) {
  69457. var points = lines[l];
  69458. for (var p = 0; p < points.length; p++) {
  69459. positions[i] = points[p].x;
  69460. positions[i + 1] = points[p].y;
  69461. positions[i + 2] = points[p].z;
  69462. if (colors && vertexColor) {
  69463. lineColors = colors[l];
  69464. vertexColor[c] = lineColors[p].r;
  69465. vertexColor[c + 1] = lineColors[p].g;
  69466. vertexColor[c + 2] = lineColors[p].b;
  69467. vertexColor[c + 3] = lineColors[p].a;
  69468. c += 4;
  69469. }
  69470. i += 3;
  69471. }
  69472. }
  69473. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  69474. if (colors && vertexColor) {
  69475. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  69476. }
  69477. return instance;
  69478. }
  69479. // line system creation
  69480. var useVertexColor = (colors) ? true : false;
  69481. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  69482. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  69483. vertexData.applyToMesh(lineSystem, options.updatable);
  69484. return lineSystem;
  69485. };
  69486. /**
  69487. * Creates a line mesh
  69488. * 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
  69489. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  69490. * * The parameter `points` is an array successive Vector3
  69491. * * 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
  69492. * * The optional parameter `colors` is an array of successive Color4, one per line point
  69493. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  69494. * * When updating an instance, remember that only point positions can change, not the number of points
  69495. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69496. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  69497. * @param name defines the name of the new line system
  69498. * @param options defines the options used to create the line system
  69499. * @param scene defines the hosting scene
  69500. * @returns a new line mesh
  69501. */
  69502. MeshBuilder.CreateLines = function (name, options, scene) {
  69503. if (scene === void 0) { scene = null; }
  69504. var colors = (options.colors) ? [options.colors] : null;
  69505. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  69506. return lines;
  69507. };
  69508. /**
  69509. * Creates a dashed line mesh
  69510. * * 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
  69511. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  69512. * * The parameter `points` is an array successive Vector3
  69513. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  69514. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  69515. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  69516. * * 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
  69517. * * When updating an instance, remember that only point positions can change, not the number of points
  69518. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69519. * @param name defines the name of the mesh
  69520. * @param options defines the options used to create the mesh
  69521. * @param scene defines the hosting scene
  69522. * @returns the dashed line mesh
  69523. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  69524. */
  69525. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  69526. if (scene === void 0) { scene = null; }
  69527. var points = options.points;
  69528. var instance = options.instance;
  69529. var gapSize = options.gapSize || 1;
  69530. var dashSize = options.dashSize || 3;
  69531. if (instance) { // dashed lines update
  69532. var positionFunction = function (positions) {
  69533. var curvect = BABYLON.Vector3.Zero();
  69534. var nbSeg = positions.length / 6;
  69535. var lg = 0;
  69536. var nb = 0;
  69537. var shft = 0;
  69538. var dashshft = 0;
  69539. var curshft = 0;
  69540. var p = 0;
  69541. var i = 0;
  69542. var j = 0;
  69543. for (i = 0; i < points.length - 1; i++) {
  69544. points[i + 1].subtractToRef(points[i], curvect);
  69545. lg += curvect.length();
  69546. }
  69547. shft = lg / nbSeg;
  69548. var dashSize = instance._creationDataStorage.dashSize;
  69549. var gapSize = instance._creationDataStorage.gapSize;
  69550. dashshft = dashSize * shft / (dashSize + gapSize);
  69551. for (i = 0; i < points.length - 1; i++) {
  69552. points[i + 1].subtractToRef(points[i], curvect);
  69553. nb = Math.floor(curvect.length() / shft);
  69554. curvect.normalize();
  69555. j = 0;
  69556. while (j < nb && p < positions.length) {
  69557. curshft = shft * j;
  69558. positions[p] = points[i].x + curshft * curvect.x;
  69559. positions[p + 1] = points[i].y + curshft * curvect.y;
  69560. positions[p + 2] = points[i].z + curshft * curvect.z;
  69561. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  69562. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  69563. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  69564. p += 6;
  69565. j++;
  69566. }
  69567. }
  69568. while (p < positions.length) {
  69569. positions[p] = points[i].x;
  69570. positions[p + 1] = points[i].y;
  69571. positions[p + 2] = points[i].z;
  69572. p += 3;
  69573. }
  69574. };
  69575. instance.updateMeshPositions(positionFunction, false);
  69576. return instance;
  69577. }
  69578. // dashed lines creation
  69579. var dashedLines = new BABYLON.LinesMesh(name, scene);
  69580. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  69581. vertexData.applyToMesh(dashedLines, options.updatable);
  69582. dashedLines._creationDataStorage = new BABYLON._CreationDataStorage();
  69583. dashedLines._creationDataStorage.dashSize = dashSize;
  69584. dashedLines._creationDataStorage.gapSize = gapSize;
  69585. return dashedLines;
  69586. };
  69587. /**
  69588. * 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.
  69589. * * 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.
  69590. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  69591. * * 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.
  69592. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  69593. * * 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
  69594. * * 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
  69595. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  69596. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69597. * * 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
  69598. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  69599. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69600. * @param name defines the name of the mesh
  69601. * @param options defines the options used to create the mesh
  69602. * @param scene defines the hosting scene
  69603. * @returns the extruded shape mesh
  69604. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  69605. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  69606. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  69607. */
  69608. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  69609. if (scene === void 0) { scene = null; }
  69610. var path = options.path;
  69611. var shape = options.shape;
  69612. var scale = options.scale || 1;
  69613. var rotation = options.rotation || 0;
  69614. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  69615. var updatable = options.updatable;
  69616. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69617. var instance = options.instance || null;
  69618. var invertUV = options.invertUV || false;
  69619. 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);
  69620. };
  69621. /**
  69622. * Creates an custom extruded shape mesh.
  69623. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  69624. * * 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.
  69625. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  69626. * * 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
  69627. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  69628. * * 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
  69629. * * It must returns a float value that will be the scale value applied to the shape on each path point
  69630. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  69631. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  69632. * * 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
  69633. * * 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
  69634. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  69635. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69636. * * 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
  69637. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  69638. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69639. * @param name defines the name of the mesh
  69640. * @param options defines the options used to create the mesh
  69641. * @param scene defines the hosting scene
  69642. * @returns the custom extruded shape mesh
  69643. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  69644. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  69645. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  69646. */
  69647. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  69648. var path = options.path;
  69649. var shape = options.shape;
  69650. var scaleFunction = options.scaleFunction || (function () { return 1; });
  69651. var rotationFunction = options.rotationFunction || (function () { return 0; });
  69652. var ribbonCloseArray = options.ribbonCloseArray || false;
  69653. var ribbonClosePath = options.ribbonClosePath || false;
  69654. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  69655. var updatable = options.updatable;
  69656. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69657. var instance = options.instance;
  69658. var invertUV = options.invertUV || false;
  69659. 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);
  69660. };
  69661. /**
  69662. * Creates lathe mesh.
  69663. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  69664. * * 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
  69665. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  69666. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  69667. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  69668. * * 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
  69669. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  69670. * * 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
  69671. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69672. * * 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
  69673. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  69674. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69675. * @param name defines the name of the mesh
  69676. * @param options defines the options used to create the mesh
  69677. * @param scene defines the hosting scene
  69678. * @returns the lathe mesh
  69679. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  69680. */
  69681. MeshBuilder.CreateLathe = function (name, options, scene) {
  69682. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  69683. var closed = (options.closed === undefined) ? true : options.closed;
  69684. var shape = options.shape;
  69685. var radius = options.radius || 1;
  69686. var tessellation = options.tessellation || 64;
  69687. var clip = options.clip || 0;
  69688. var updatable = options.updatable;
  69689. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69690. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  69691. var pi2 = Math.PI * 2;
  69692. var paths = new Array();
  69693. var invertUV = options.invertUV || false;
  69694. var i = 0;
  69695. var p = 0;
  69696. var step = pi2 / tessellation * arc;
  69697. var rotated;
  69698. var path = new Array();
  69699. for (i = 0; i <= tessellation - clip; i++) {
  69700. var path = [];
  69701. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  69702. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  69703. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  69704. }
  69705. for (p = 0; p < shape.length; p++) {
  69706. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  69707. path.push(rotated);
  69708. }
  69709. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  69710. 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));
  69711. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  69712. }
  69713. paths.push(path);
  69714. }
  69715. // lathe ribbon
  69716. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  69717. return lathe;
  69718. };
  69719. /**
  69720. * Creates a plane mesh
  69721. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  69722. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  69723. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  69724. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69725. * * 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
  69726. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69727. * @param name defines the name of the mesh
  69728. * @param options defines the options used to create the mesh
  69729. * @param scene defines the hosting scene
  69730. * @returns the plane mesh
  69731. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  69732. */
  69733. MeshBuilder.CreatePlane = function (name, options, scene) {
  69734. var plane = new BABYLON.Mesh(name, scene);
  69735. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69736. plane._originalBuilderSideOrientation = options.sideOrientation;
  69737. var vertexData = BABYLON.VertexData.CreatePlane(options);
  69738. vertexData.applyToMesh(plane, options.updatable);
  69739. if (options.sourcePlane) {
  69740. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  69741. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  69742. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  69743. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  69744. plane.rotate(vectorProduct, product);
  69745. }
  69746. }
  69747. return plane;
  69748. };
  69749. /**
  69750. * Creates a ground mesh
  69751. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  69752. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  69753. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69754. * @param name defines the name of the mesh
  69755. * @param options defines the options used to create the mesh
  69756. * @param scene defines the hosting scene
  69757. * @returns the ground mesh
  69758. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  69759. */
  69760. MeshBuilder.CreateGround = function (name, options, scene) {
  69761. var ground = new BABYLON.GroundMesh(name, scene);
  69762. ground._setReady(false);
  69763. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  69764. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  69765. ground._width = options.width || 1;
  69766. ground._height = options.height || 1;
  69767. ground._maxX = ground._width / 2;
  69768. ground._maxZ = ground._height / 2;
  69769. ground._minX = -ground._maxX;
  69770. ground._minZ = -ground._maxZ;
  69771. var vertexData = BABYLON.VertexData.CreateGround(options);
  69772. vertexData.applyToMesh(ground, options.updatable);
  69773. ground._setReady(true);
  69774. return ground;
  69775. };
  69776. /**
  69777. * Creates a tiled ground mesh
  69778. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  69779. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  69780. * * 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
  69781. * * 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
  69782. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69783. * @param name defines the name of the mesh
  69784. * @param options defines the options used to create the mesh
  69785. * @param scene defines the hosting scene
  69786. * @returns the tiled ground mesh
  69787. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  69788. */
  69789. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  69790. var tiledGround = new BABYLON.Mesh(name, scene);
  69791. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  69792. vertexData.applyToMesh(tiledGround, options.updatable);
  69793. return tiledGround;
  69794. };
  69795. /**
  69796. * Creates a ground mesh from a height map
  69797. * * The parameter `url` sets the URL of the height map image resource.
  69798. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  69799. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  69800. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  69801. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  69802. * * 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.
  69803. * * 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).
  69804. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  69805. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  69806. * @param name defines the name of the mesh
  69807. * @param url defines the url to the height map
  69808. * @param options defines the options used to create the mesh
  69809. * @param scene defines the hosting scene
  69810. * @returns the ground mesh
  69811. * @see http://doc.babylonjs.com/babylon101/height_map
  69812. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  69813. */
  69814. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  69815. var width = options.width || 10.0;
  69816. var height = options.height || 10.0;
  69817. var subdivisions = options.subdivisions || 1 | 0;
  69818. var minHeight = options.minHeight || 0.0;
  69819. var maxHeight = options.maxHeight || 1.0;
  69820. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  69821. var alphaFilter = options.alphaFilter || 0.0;
  69822. var updatable = options.updatable;
  69823. var onReady = options.onReady;
  69824. var ground = new BABYLON.GroundMesh(name, scene);
  69825. ground._subdivisionsX = subdivisions;
  69826. ground._subdivisionsY = subdivisions;
  69827. ground._width = width;
  69828. ground._height = height;
  69829. ground._maxX = ground._width / 2.0;
  69830. ground._maxZ = ground._height / 2.0;
  69831. ground._minX = -ground._maxX;
  69832. ground._minZ = -ground._maxZ;
  69833. ground._setReady(false);
  69834. var onload = function (img) {
  69835. // Getting height map data
  69836. var canvas = document.createElement("canvas");
  69837. var context = canvas.getContext("2d");
  69838. if (!context) {
  69839. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  69840. }
  69841. if (scene.isDisposed) {
  69842. return;
  69843. }
  69844. var bufferWidth = img.width;
  69845. var bufferHeight = img.height;
  69846. canvas.width = bufferWidth;
  69847. canvas.height = bufferHeight;
  69848. context.drawImage(img, 0, 0);
  69849. // Create VertexData from map data
  69850. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  69851. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  69852. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  69853. width: width, height: height,
  69854. subdivisions: subdivisions,
  69855. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  69856. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  69857. alphaFilter: alphaFilter
  69858. });
  69859. vertexData.applyToMesh(ground, updatable);
  69860. //execute ready callback, if set
  69861. if (onReady) {
  69862. onReady(ground);
  69863. }
  69864. ground._setReady(true);
  69865. };
  69866. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.offlineProvider);
  69867. return ground;
  69868. };
  69869. /**
  69870. * Creates a polygon mesh
  69871. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  69872. * * 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
  69873. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69874. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69875. * * 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)
  69876. * * Remember you can only change the shape positions, not their number when updating a polygon
  69877. * @param name defines the name of the mesh
  69878. * @param options defines the options used to create the mesh
  69879. * @param scene defines the hosting scene
  69880. * @returns the polygon mesh
  69881. */
  69882. MeshBuilder.CreatePolygon = function (name, options, scene) {
  69883. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69884. var shape = options.shape;
  69885. var holes = options.holes || [];
  69886. var depth = options.depth || 0;
  69887. var contours = [];
  69888. var hole = [];
  69889. for (var i = 0; i < shape.length; i++) {
  69890. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  69891. }
  69892. var epsilon = 0.00000001;
  69893. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  69894. contours.pop();
  69895. }
  69896. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  69897. for (var hNb = 0; hNb < holes.length; hNb++) {
  69898. hole = [];
  69899. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  69900. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  69901. }
  69902. polygonTriangulation.addHole(hole);
  69903. }
  69904. var polygon = polygonTriangulation.build(options.updatable, depth);
  69905. polygon._originalBuilderSideOrientation = options.sideOrientation;
  69906. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  69907. vertexData.applyToMesh(polygon, options.updatable);
  69908. return polygon;
  69909. };
  69910. /**
  69911. * Creates an extruded polygon mesh, with depth in the Y direction.
  69912. * * 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)
  69913. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  69914. * @param name defines the name of the mesh
  69915. * @param options defines the options used to create the mesh
  69916. * @param scene defines the hosting scene
  69917. * @returns the polygon mesh
  69918. */
  69919. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  69920. return MeshBuilder.CreatePolygon(name, options, scene);
  69921. };
  69922. /**
  69923. * Creates a tube mesh.
  69924. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  69925. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  69926. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  69927. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  69928. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  69929. * * 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)
  69930. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  69931. * * 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
  69932. * * 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
  69933. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  69934. * * 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
  69935. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  69936. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  69937. * @param name defines the name of the mesh
  69938. * @param options defines the options used to create the mesh
  69939. * @param scene defines the hosting scene
  69940. * @returns the tube mesh
  69941. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  69942. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  69943. */
  69944. MeshBuilder.CreateTube = function (name, options, scene) {
  69945. var path = options.path;
  69946. var instance = options.instance;
  69947. var radius = 1.0;
  69948. if (options.radius !== undefined) {
  69949. radius = options.radius;
  69950. }
  69951. else if (instance) {
  69952. radius = instance._creationDataStorage.radius;
  69953. }
  69954. var tessellation = options.tessellation || 64 | 0;
  69955. var radiusFunction = options.radiusFunction || null;
  69956. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  69957. var invertUV = options.invertUV || false;
  69958. var updatable = options.updatable;
  69959. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  69960. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  69961. // tube geometry
  69962. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  69963. var tangents = path3D.getTangents();
  69964. var normals = path3D.getNormals();
  69965. var distances = path3D.getDistances();
  69966. var pi2 = Math.PI * 2;
  69967. var step = pi2 / tessellation * arc;
  69968. var returnRadius = function () { return radius; };
  69969. var radiusFunctionFinal = radiusFunction || returnRadius;
  69970. var circlePath;
  69971. var rad;
  69972. var normal;
  69973. var rotated;
  69974. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  69975. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  69976. for (var i = 0; i < path.length; i++) {
  69977. rad = radiusFunctionFinal(i, distances[i]); // current radius
  69978. circlePath = Array(); // current circle array
  69979. normal = normals[i]; // current normal
  69980. for (var t = 0; t < tessellation; t++) {
  69981. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  69982. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  69983. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  69984. rotated.scaleInPlace(rad).addInPlace(path[i]);
  69985. circlePath[t] = rotated;
  69986. }
  69987. circlePaths[index] = circlePath;
  69988. index++;
  69989. }
  69990. // cap
  69991. var capPath = function (nbPoints, pathIndex) {
  69992. var pointCap = Array();
  69993. for (var i = 0; i < nbPoints; i++) {
  69994. pointCap.push(path[pathIndex]);
  69995. }
  69996. return pointCap;
  69997. };
  69998. switch (cap) {
  69999. case BABYLON.Mesh.NO_CAP:
  70000. break;
  70001. case BABYLON.Mesh.CAP_START:
  70002. circlePaths[0] = capPath(tessellation, 0);
  70003. circlePaths[1] = circlePaths[2].slice(0);
  70004. break;
  70005. case BABYLON.Mesh.CAP_END:
  70006. circlePaths[index] = circlePaths[index - 1].slice(0);
  70007. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  70008. break;
  70009. case BABYLON.Mesh.CAP_ALL:
  70010. circlePaths[0] = capPath(tessellation, 0);
  70011. circlePaths[1] = circlePaths[2].slice(0);
  70012. circlePaths[index] = circlePaths[index - 1].slice(0);
  70013. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  70014. break;
  70015. default:
  70016. break;
  70017. }
  70018. return circlePaths;
  70019. };
  70020. var path3D;
  70021. var pathArray;
  70022. if (instance) { // tube update
  70023. var storage = instance._creationDataStorage;
  70024. var arc = options.arc || storage.arc;
  70025. path3D = storage.path3D.update(path);
  70026. pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc);
  70027. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  70028. // Update mode, no need to recreate the storage.
  70029. storage.path3D = path3D;
  70030. storage.pathArray = pathArray;
  70031. storage.arc = arc;
  70032. storage.radius = radius;
  70033. return instance;
  70034. }
  70035. // tube creation
  70036. path3D = new BABYLON.Path3D(path);
  70037. var newPathArray = new Array();
  70038. cap = (cap < 0 || cap > 3) ? 0 : cap;
  70039. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  70040. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  70041. tube._creationDataStorage.pathArray = pathArray;
  70042. tube._creationDataStorage.path3D = path3D;
  70043. tube._creationDataStorage.tessellation = tessellation;
  70044. tube._creationDataStorage.cap = cap;
  70045. tube._creationDataStorage.arc = options.arc;
  70046. tube._creationDataStorage.radius = radius;
  70047. return tube;
  70048. };
  70049. /**
  70050. * Creates a polyhedron mesh
  70051. * * 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
  70052. * * The parameter `size` (positive float, default 1) sets the polygon size
  70053. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  70054. * * 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`
  70055. * * 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
  70056. * * 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)`)
  70057. * * 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
  70058. * * 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
  70059. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  70060. * * 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
  70061. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  70062. * @param name defines the name of the mesh
  70063. * @param options defines the options used to create the mesh
  70064. * @param scene defines the hosting scene
  70065. * @returns the polyhedron mesh
  70066. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  70067. */
  70068. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  70069. var polyhedron = new BABYLON.Mesh(name, scene);
  70070. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  70071. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  70072. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  70073. vertexData.applyToMesh(polyhedron, options.updatable);
  70074. return polyhedron;
  70075. };
  70076. /**
  70077. * Creates a decal mesh.
  70078. * 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
  70079. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  70080. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  70081. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  70082. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  70083. * @param name defines the name of the mesh
  70084. * @param sourceMesh defines the mesh where the decal must be applied
  70085. * @param options defines the options used to create the mesh
  70086. * @param scene defines the hosting scene
  70087. * @returns the decal mesh
  70088. * @see http://doc.babylonjs.com/how_to/decals
  70089. */
  70090. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  70091. var indices = sourceMesh.getIndices();
  70092. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  70093. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  70094. var position = options.position || BABYLON.Vector3.Zero();
  70095. var normal = options.normal || BABYLON.Vector3.Up();
  70096. var size = options.size || BABYLON.Vector3.One();
  70097. var angle = options.angle || 0;
  70098. // Getting correct rotation
  70099. if (!normal) {
  70100. var target = new BABYLON.Vector3(0, 0, 1);
  70101. var camera = sourceMesh.getScene().activeCamera;
  70102. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  70103. normal = camera.globalPosition.subtract(cameraWorldTarget);
  70104. }
  70105. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  70106. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  70107. var pitch = Math.atan2(normal.y, len);
  70108. // Matrix
  70109. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  70110. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  70111. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  70112. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  70113. var vertexData = new BABYLON.VertexData();
  70114. vertexData.indices = [];
  70115. vertexData.positions = [];
  70116. vertexData.normals = [];
  70117. vertexData.uvs = [];
  70118. var currentVertexDataIndex = 0;
  70119. var extractDecalVector3 = function (indexId) {
  70120. var result = new BABYLON.PositionNormalVertex();
  70121. if (!indices || !positions || !normals) {
  70122. return result;
  70123. }
  70124. var vertexId = indices[indexId];
  70125. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  70126. // Send vector to decal local world
  70127. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  70128. // Get normal
  70129. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  70130. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  70131. return result;
  70132. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  70133. var clip = function (vertices, axis) {
  70134. if (vertices.length === 0) {
  70135. return vertices;
  70136. }
  70137. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  70138. var clipVertices = function (v0, v1) {
  70139. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  70140. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  70141. };
  70142. var result = new Array();
  70143. for (var index = 0; index < vertices.length; index += 3) {
  70144. var v1Out;
  70145. var v2Out;
  70146. var v3Out;
  70147. var total = 0;
  70148. var nV1 = null;
  70149. var nV2 = null;
  70150. var nV3 = null;
  70151. var nV4 = null;
  70152. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  70153. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  70154. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  70155. v1Out = d1 > 0;
  70156. v2Out = d2 > 0;
  70157. v3Out = d3 > 0;
  70158. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  70159. switch (total) {
  70160. case 0:
  70161. result.push(vertices[index]);
  70162. result.push(vertices[index + 1]);
  70163. result.push(vertices[index + 2]);
  70164. break;
  70165. case 1:
  70166. if (v1Out) {
  70167. nV1 = vertices[index + 1];
  70168. nV2 = vertices[index + 2];
  70169. nV3 = clipVertices(vertices[index], nV1);
  70170. nV4 = clipVertices(vertices[index], nV2);
  70171. }
  70172. if (v2Out) {
  70173. nV1 = vertices[index];
  70174. nV2 = vertices[index + 2];
  70175. nV3 = clipVertices(vertices[index + 1], nV1);
  70176. nV4 = clipVertices(vertices[index + 1], nV2);
  70177. result.push(nV3);
  70178. result.push(nV2.clone());
  70179. result.push(nV1.clone());
  70180. result.push(nV2.clone());
  70181. result.push(nV3.clone());
  70182. result.push(nV4);
  70183. break;
  70184. }
  70185. if (v3Out) {
  70186. nV1 = vertices[index];
  70187. nV2 = vertices[index + 1];
  70188. nV3 = clipVertices(vertices[index + 2], nV1);
  70189. nV4 = clipVertices(vertices[index + 2], nV2);
  70190. }
  70191. if (nV1 && nV2 && nV3 && nV4) {
  70192. result.push(nV1.clone());
  70193. result.push(nV2.clone());
  70194. result.push(nV3);
  70195. result.push(nV4);
  70196. result.push(nV3.clone());
  70197. result.push(nV2.clone());
  70198. }
  70199. break;
  70200. case 2:
  70201. if (!v1Out) {
  70202. nV1 = vertices[index].clone();
  70203. nV2 = clipVertices(nV1, vertices[index + 1]);
  70204. nV3 = clipVertices(nV1, vertices[index + 2]);
  70205. result.push(nV1);
  70206. result.push(nV2);
  70207. result.push(nV3);
  70208. }
  70209. if (!v2Out) {
  70210. nV1 = vertices[index + 1].clone();
  70211. nV2 = clipVertices(nV1, vertices[index + 2]);
  70212. nV3 = clipVertices(nV1, vertices[index]);
  70213. result.push(nV1);
  70214. result.push(nV2);
  70215. result.push(nV3);
  70216. }
  70217. if (!v3Out) {
  70218. nV1 = vertices[index + 2].clone();
  70219. nV2 = clipVertices(nV1, vertices[index]);
  70220. nV3 = clipVertices(nV1, vertices[index + 1]);
  70221. result.push(nV1);
  70222. result.push(nV2);
  70223. result.push(nV3);
  70224. }
  70225. break;
  70226. case 3:
  70227. break;
  70228. }
  70229. }
  70230. return result;
  70231. };
  70232. for (var index = 0; index < indices.length; index += 3) {
  70233. var faceVertices = new Array();
  70234. faceVertices.push(extractDecalVector3(index));
  70235. faceVertices.push(extractDecalVector3(index + 1));
  70236. faceVertices.push(extractDecalVector3(index + 2));
  70237. // Clip
  70238. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  70239. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  70240. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  70241. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  70242. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  70243. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  70244. if (faceVertices.length === 0) {
  70245. continue;
  70246. }
  70247. // Add UVs and get back to world
  70248. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  70249. var vertex = faceVertices[vIndex];
  70250. //TODO check for Int32Array | Uint32Array | Uint16Array
  70251. vertexData.indices.push(currentVertexDataIndex);
  70252. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  70253. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  70254. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  70255. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  70256. currentVertexDataIndex++;
  70257. }
  70258. }
  70259. // Return mesh
  70260. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  70261. vertexData.applyToMesh(decal);
  70262. decal.position = position.clone();
  70263. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  70264. return decal;
  70265. };
  70266. // Privates
  70267. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  70268. // extrusion geometry
  70269. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  70270. var tangents = path3D.getTangents();
  70271. var normals = path3D.getNormals();
  70272. var binormals = path3D.getBinormals();
  70273. var distances = path3D.getDistances();
  70274. var angle = 0;
  70275. var returnScale = function () { return scale !== null ? scale : 1; };
  70276. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  70277. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  70278. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  70279. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  70280. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  70281. for (var i = 0; i < curve.length; i++) {
  70282. var shapePath = new Array();
  70283. var angleStep = rotate(i, distances[i]);
  70284. var scaleRatio = scl(i, distances[i]);
  70285. for (var p = 0; p < shape.length; p++) {
  70286. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  70287. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  70288. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  70289. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  70290. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  70291. shapePath[p] = rotated;
  70292. }
  70293. shapePaths[index] = shapePath;
  70294. angle += angleStep;
  70295. index++;
  70296. }
  70297. // cap
  70298. var capPath = function (shapePath) {
  70299. var pointCap = Array();
  70300. var barycenter = BABYLON.Vector3.Zero();
  70301. var i;
  70302. for (i = 0; i < shapePath.length; i++) {
  70303. barycenter.addInPlace(shapePath[i]);
  70304. }
  70305. barycenter.scaleInPlace(1.0 / shapePath.length);
  70306. for (i = 0; i < shapePath.length; i++) {
  70307. pointCap.push(barycenter);
  70308. }
  70309. return pointCap;
  70310. };
  70311. switch (cap) {
  70312. case BABYLON.Mesh.NO_CAP:
  70313. break;
  70314. case BABYLON.Mesh.CAP_START:
  70315. shapePaths[0] = capPath(shapePaths[2]);
  70316. shapePaths[1] = shapePaths[2];
  70317. break;
  70318. case BABYLON.Mesh.CAP_END:
  70319. shapePaths[index] = shapePaths[index - 1];
  70320. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  70321. break;
  70322. case BABYLON.Mesh.CAP_ALL:
  70323. shapePaths[0] = capPath(shapePaths[2]);
  70324. shapePaths[1] = shapePaths[2];
  70325. shapePaths[index] = shapePaths[index - 1];
  70326. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  70327. break;
  70328. default:
  70329. break;
  70330. }
  70331. return shapePaths;
  70332. };
  70333. var path3D;
  70334. var pathArray;
  70335. if (instance) { // instance update
  70336. var storage = instance._creationDataStorage;
  70337. path3D = storage.path3D.update(curve);
  70338. pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom);
  70339. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  70340. return instance;
  70341. }
  70342. // extruded shape creation
  70343. path3D = new BABYLON.Path3D(curve);
  70344. var newShapePaths = new Array();
  70345. cap = (cap < 0 || cap > 3) ? 0 : cap;
  70346. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  70347. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  70348. extrudedGeneric._creationDataStorage.pathArray = pathArray;
  70349. extrudedGeneric._creationDataStorage.path3D = path3D;
  70350. extrudedGeneric._creationDataStorage.cap = cap;
  70351. return extrudedGeneric;
  70352. };
  70353. return MeshBuilder;
  70354. }());
  70355. BABYLON.MeshBuilder = MeshBuilder;
  70356. })(BABYLON || (BABYLON = {}));
  70357. //# sourceMappingURL=meshBuilder.js.map
  70358. var BABYLON;
  70359. (function (BABYLON) {
  70360. /**
  70361. * Draco compression (https://google.github.io/draco/)
  70362. *
  70363. * This class wraps the Draco module.
  70364. *
  70365. * **Encoder**
  70366. *
  70367. * The encoder is not currently implemented.
  70368. *
  70369. * **Decoder**
  70370. *
  70371. * 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.
  70372. *
  70373. * To update the configuration, use the following code:
  70374. * ```javascript
  70375. * BABYLON.DracoCompression.Configuration = {
  70376. * decoder: {
  70377. * wasmUrl: "<url to the WebAssembly library>",
  70378. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  70379. * fallbackUrl: "<url to the fallback JavaScript library>",
  70380. * }
  70381. * };
  70382. * ```
  70383. *
  70384. * 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.
  70385. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  70386. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  70387. *
  70388. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  70389. * ```javascript
  70390. * var dracoCompression = new BABYLON.DracoCompression();
  70391. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  70392. * [BABYLON.VertexBuffer.PositionKind]: 0
  70393. * });
  70394. * ```
  70395. *
  70396. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  70397. */
  70398. var DracoCompression = /** @class */ (function () {
  70399. /**
  70400. * Constructor
  70401. */
  70402. function DracoCompression() {
  70403. }
  70404. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  70405. /**
  70406. * Returns true if the decoder is available.
  70407. */
  70408. get: function () {
  70409. if (typeof DracoDecoderModule !== "undefined") {
  70410. return true;
  70411. }
  70412. var decoder = DracoCompression.Configuration.decoder;
  70413. if (decoder) {
  70414. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  70415. return true;
  70416. }
  70417. if (decoder.fallbackUrl) {
  70418. return true;
  70419. }
  70420. }
  70421. return false;
  70422. },
  70423. enumerable: true,
  70424. configurable: true
  70425. });
  70426. /**
  70427. * Stop all async operations and release resources.
  70428. */
  70429. DracoCompression.prototype.dispose = function () {
  70430. };
  70431. /**
  70432. * Decode Draco compressed mesh data to vertex data.
  70433. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  70434. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  70435. * @returns A promise that resolves with the decoded vertex data
  70436. */
  70437. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  70438. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  70439. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  70440. var module = wrappedModule.module;
  70441. var vertexData = new BABYLON.VertexData();
  70442. var buffer = new module.DecoderBuffer();
  70443. buffer.Init(dataView, dataView.byteLength);
  70444. var decoder = new module.Decoder();
  70445. var geometry;
  70446. var status;
  70447. try {
  70448. var type = decoder.GetEncodedGeometryType(buffer);
  70449. switch (type) {
  70450. case module.TRIANGULAR_MESH:
  70451. geometry = new module.Mesh();
  70452. status = decoder.DecodeBufferToMesh(buffer, geometry);
  70453. break;
  70454. case module.POINT_CLOUD:
  70455. geometry = new module.PointCloud();
  70456. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  70457. break;
  70458. default:
  70459. throw new Error("Invalid geometry type " + type);
  70460. }
  70461. if (!status.ok() || !geometry.ptr) {
  70462. throw new Error(status.error_msg());
  70463. }
  70464. var numPoints = geometry.num_points();
  70465. if (type === module.TRIANGULAR_MESH) {
  70466. var numFaces = geometry.num_faces();
  70467. var faceIndices = new module.DracoInt32Array();
  70468. try {
  70469. var indices = new Uint32Array(numFaces * 3);
  70470. for (var i = 0; i < numFaces; i++) {
  70471. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  70472. var offset = i * 3;
  70473. indices[offset + 0] = faceIndices.GetValue(0);
  70474. indices[offset + 1] = faceIndices.GetValue(1);
  70475. indices[offset + 2] = faceIndices.GetValue(2);
  70476. }
  70477. vertexData.indices = indices;
  70478. }
  70479. finally {
  70480. module.destroy(faceIndices);
  70481. }
  70482. }
  70483. for (var kind in attributes) {
  70484. var uniqueId = attributes[kind];
  70485. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  70486. var dracoData = new module.DracoFloat32Array();
  70487. try {
  70488. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  70489. var babylonData = new Float32Array(numPoints * attribute.num_components());
  70490. for (var i = 0; i < babylonData.length; i++) {
  70491. babylonData[i] = dracoData.GetValue(i);
  70492. }
  70493. vertexData.set(babylonData, kind);
  70494. }
  70495. finally {
  70496. module.destroy(dracoData);
  70497. }
  70498. }
  70499. }
  70500. finally {
  70501. if (geometry) {
  70502. module.destroy(geometry);
  70503. }
  70504. module.destroy(decoder);
  70505. module.destroy(buffer);
  70506. }
  70507. return vertexData;
  70508. });
  70509. };
  70510. DracoCompression._GetDecoderModule = function () {
  70511. if (!DracoCompression._DecoderModulePromise) {
  70512. var promise = null;
  70513. var config_1 = {};
  70514. if (typeof DracoDecoderModule !== "undefined") {
  70515. promise = Promise.resolve();
  70516. }
  70517. else {
  70518. var decoder = DracoCompression.Configuration.decoder;
  70519. if (decoder) {
  70520. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  70521. promise = Promise.all([
  70522. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  70523. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  70524. config_1.wasmBinary = data;
  70525. })
  70526. ]);
  70527. }
  70528. else if (decoder.fallbackUrl) {
  70529. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  70530. }
  70531. }
  70532. }
  70533. if (!promise) {
  70534. throw new Error("Draco decoder module is not available");
  70535. }
  70536. DracoCompression._DecoderModulePromise = promise.then(function () {
  70537. return new Promise(function (resolve) {
  70538. config_1.onModuleLoaded = function (decoderModule) {
  70539. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  70540. resolve({ module: decoderModule });
  70541. };
  70542. DracoDecoderModule(config_1);
  70543. });
  70544. });
  70545. }
  70546. return DracoCompression._DecoderModulePromise;
  70547. };
  70548. DracoCompression._LoadScriptAsync = function (url) {
  70549. return new Promise(function (resolve, reject) {
  70550. BABYLON.Tools.LoadScript(url, function () {
  70551. resolve();
  70552. }, function (message) {
  70553. reject(new Error(message));
  70554. });
  70555. });
  70556. };
  70557. DracoCompression._LoadFileAsync = function (url) {
  70558. return new Promise(function (resolve, reject) {
  70559. BABYLON.Tools.LoadFile(url, function (data) {
  70560. resolve(data);
  70561. }, undefined, undefined, true, function (request, exception) {
  70562. reject(exception);
  70563. });
  70564. });
  70565. };
  70566. /**
  70567. * The configuration. Defaults to the following urls:
  70568. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  70569. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  70570. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  70571. */
  70572. DracoCompression.Configuration = {
  70573. decoder: {
  70574. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  70575. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  70576. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  70577. }
  70578. };
  70579. return DracoCompression;
  70580. }());
  70581. BABYLON.DracoCompression = DracoCompression;
  70582. })(BABYLON || (BABYLON = {}));
  70583. //# sourceMappingURL=dracoCompression.js.map
  70584. var BABYLON;
  70585. (function (BABYLON) {
  70586. // Sets the default audio engine to Babylon.js
  70587. BABYLON.Engine.AudioEngineFactory = function (hostElement) { return new AudioEngine(hostElement); };
  70588. /**
  70589. * This represents the default audio engine used in babylon.
  70590. * It is responsible to play, synchronize and analyse sounds throughout the application.
  70591. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  70592. */
  70593. var AudioEngine = /** @class */ (function () {
  70594. /**
  70595. * Instantiates a new audio engine.
  70596. *
  70597. * There should be only one per page as some browsers restrict the number
  70598. * of audio contexts you can create.
  70599. * @param hostElement defines the host element where to display the mute icon if necessary
  70600. */
  70601. function AudioEngine(hostElement) {
  70602. if (hostElement === void 0) { hostElement = null; }
  70603. var _this = this;
  70604. this._audioContext = null;
  70605. this._audioContextInitialized = false;
  70606. this._muteButton = null;
  70607. /**
  70608. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  70609. */
  70610. this.canUseWebAudio = false;
  70611. /**
  70612. * Defines if Babylon should emit a warning if WebAudio is not supported.
  70613. * @ignoreNaming
  70614. */
  70615. this.WarnedWebAudioUnsupported = false;
  70616. /**
  70617. * Gets whether or not mp3 are supported by your browser.
  70618. */
  70619. this.isMP3supported = false;
  70620. /**
  70621. * Gets whether or not ogg are supported by your browser.
  70622. */
  70623. this.isOGGsupported = false;
  70624. /**
  70625. * Gets whether audio has been unlocked on the device.
  70626. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  70627. * a user interaction has happened.
  70628. */
  70629. this.unlocked = true;
  70630. /**
  70631. * Defines if the audio engine relies on a custom unlocked button.
  70632. * In this case, the embedded button will not be displayed.
  70633. */
  70634. this.useCustomUnlockedButton = false;
  70635. /**
  70636. * Event raised when audio has been unlocked on the browser.
  70637. */
  70638. this.onAudioUnlockedObservable = new BABYLON.Observable();
  70639. /**
  70640. * Event raised when audio has been locked on the browser.
  70641. */
  70642. this.onAudioLockedObservable = new BABYLON.Observable();
  70643. this._tryToRun = false;
  70644. this._onResize = function () {
  70645. _this._moveButtonToTopLeft();
  70646. };
  70647. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  70648. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  70649. this.canUseWebAudio = true;
  70650. }
  70651. var audioElem = document.createElement('audio');
  70652. this._hostElement = hostElement;
  70653. try {
  70654. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  70655. this.isMP3supported = true;
  70656. }
  70657. }
  70658. catch (e) {
  70659. // protect error during capability check.
  70660. }
  70661. try {
  70662. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  70663. this.isOGGsupported = true;
  70664. }
  70665. }
  70666. catch (e) {
  70667. // protect error during capability check.
  70668. }
  70669. }
  70670. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  70671. /**
  70672. * Gets the current AudioContext if available.
  70673. */
  70674. get: function () {
  70675. if (!this._audioContextInitialized) {
  70676. this._initializeAudioContext();
  70677. }
  70678. else {
  70679. if (!this.unlocked && !this._muteButton) {
  70680. this._displayMuteButton();
  70681. }
  70682. }
  70683. return this._audioContext;
  70684. },
  70685. enumerable: true,
  70686. configurable: true
  70687. });
  70688. /**
  70689. * Flags the audio engine in Locked state.
  70690. * This happens due to new browser policies preventing audio to autoplay.
  70691. */
  70692. AudioEngine.prototype.lock = function () {
  70693. this._triggerSuspendedState();
  70694. };
  70695. /**
  70696. * Unlocks the audio engine once a user action has been done on the dom.
  70697. * This is helpful to resume play once browser policies have been satisfied.
  70698. */
  70699. AudioEngine.prototype.unlock = function () {
  70700. this._triggerRunningState();
  70701. };
  70702. AudioEngine.prototype._resumeAudioContext = function () {
  70703. var result;
  70704. if (this._audioContext.resume) {
  70705. result = this._audioContext.resume();
  70706. }
  70707. return result || Promise.resolve();
  70708. };
  70709. AudioEngine.prototype._initializeAudioContext = function () {
  70710. try {
  70711. if (this.canUseWebAudio) {
  70712. this._audioContext = new AudioContext();
  70713. // create a global volume gain node
  70714. this.masterGain = this._audioContext.createGain();
  70715. this.masterGain.gain.value = 1;
  70716. this.masterGain.connect(this._audioContext.destination);
  70717. this._audioContextInitialized = true;
  70718. if (this._audioContext.state === "running") {
  70719. // Do not wait for the promise to unlock.
  70720. this._triggerRunningState();
  70721. }
  70722. }
  70723. }
  70724. catch (e) {
  70725. this.canUseWebAudio = false;
  70726. BABYLON.Tools.Error("Web Audio: " + e.message);
  70727. }
  70728. };
  70729. AudioEngine.prototype._triggerRunningState = function () {
  70730. var _this = this;
  70731. if (this._tryToRun) {
  70732. return;
  70733. }
  70734. this._tryToRun = true;
  70735. this._resumeAudioContext()
  70736. .then(function () {
  70737. _this._tryToRun = false;
  70738. if (_this._muteButton) {
  70739. _this._hideMuteButton();
  70740. }
  70741. }).catch(function () {
  70742. _this._tryToRun = false;
  70743. _this.unlocked = false;
  70744. });
  70745. // Notify users that the audio stack is unlocked/unmuted
  70746. this.unlocked = true;
  70747. this.onAudioUnlockedObservable.notifyObservers(this);
  70748. };
  70749. AudioEngine.prototype._triggerSuspendedState = function () {
  70750. this.unlocked = false;
  70751. this.onAudioLockedObservable.notifyObservers(this);
  70752. this._displayMuteButton();
  70753. };
  70754. AudioEngine.prototype._displayMuteButton = function () {
  70755. var _this = this;
  70756. if (this.useCustomUnlockedButton) {
  70757. return;
  70758. }
  70759. this._muteButton = document.createElement("BUTTON");
  70760. this._muteButton.className = "babylonUnmuteIcon";
  70761. this._muteButton.id = "babylonUnmuteIconBtn";
  70762. this._muteButton.title = "Unmute";
  70763. 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) }";
  70764. var style = document.createElement('style');
  70765. style.appendChild(document.createTextNode(css));
  70766. document.getElementsByTagName('head')[0].appendChild(style);
  70767. document.body.appendChild(this._muteButton);
  70768. this._moveButtonToTopLeft();
  70769. this._muteButton.addEventListener('touchend', function () {
  70770. _this._triggerRunningState();
  70771. }, true);
  70772. this._muteButton.addEventListener('click', function () {
  70773. _this._triggerRunningState();
  70774. }, true);
  70775. window.addEventListener("resize", this._onResize);
  70776. };
  70777. AudioEngine.prototype._moveButtonToTopLeft = function () {
  70778. if (this._hostElement && this._muteButton) {
  70779. this._muteButton.style.top = this._hostElement.offsetTop + 20 + "px";
  70780. this._muteButton.style.left = this._hostElement.offsetLeft + 20 + "px";
  70781. }
  70782. };
  70783. AudioEngine.prototype._hideMuteButton = function () {
  70784. if (this._muteButton) {
  70785. document.body.removeChild(this._muteButton);
  70786. this._muteButton = null;
  70787. }
  70788. };
  70789. /**
  70790. * Destroy and release the resources associated with the audio ccontext.
  70791. */
  70792. AudioEngine.prototype.dispose = function () {
  70793. if (this.canUseWebAudio && this._audioContextInitialized) {
  70794. if (this._connectedAnalyser && this._audioContext) {
  70795. this._connectedAnalyser.stopDebugCanvas();
  70796. this._connectedAnalyser.dispose();
  70797. this.masterGain.disconnect();
  70798. this.masterGain.connect(this._audioContext.destination);
  70799. this._connectedAnalyser = null;
  70800. }
  70801. this.masterGain.gain.value = 1;
  70802. }
  70803. this.WarnedWebAudioUnsupported = false;
  70804. this._hideMuteButton();
  70805. window.removeEventListener("resize", this._onResize);
  70806. this.onAudioUnlockedObservable.clear();
  70807. this.onAudioLockedObservable.clear();
  70808. };
  70809. /**
  70810. * Gets the global volume sets on the master gain.
  70811. * @returns the global volume if set or -1 otherwise
  70812. */
  70813. AudioEngine.prototype.getGlobalVolume = function () {
  70814. if (this.canUseWebAudio && this._audioContextInitialized) {
  70815. return this.masterGain.gain.value;
  70816. }
  70817. else {
  70818. return -1;
  70819. }
  70820. };
  70821. /**
  70822. * Sets the global volume of your experience (sets on the master gain).
  70823. * @param newVolume Defines the new global volume of the application
  70824. */
  70825. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  70826. if (this.canUseWebAudio && this._audioContextInitialized) {
  70827. this.masterGain.gain.value = newVolume;
  70828. }
  70829. };
  70830. /**
  70831. * Connect the audio engine to an audio analyser allowing some amazing
  70832. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  70833. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  70834. * @param analyser The analyser to connect to the engine
  70835. */
  70836. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  70837. if (this._connectedAnalyser) {
  70838. this._connectedAnalyser.stopDebugCanvas();
  70839. }
  70840. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  70841. this._connectedAnalyser = analyser;
  70842. this.masterGain.disconnect();
  70843. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  70844. }
  70845. };
  70846. return AudioEngine;
  70847. }());
  70848. BABYLON.AudioEngine = AudioEngine;
  70849. })(BABYLON || (BABYLON = {}));
  70850. //# sourceMappingURL=audioEngine.js.map
  70851. var BABYLON;
  70852. (function (BABYLON) {
  70853. /**
  70854. * Defines a sound that can be played in the application.
  70855. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  70856. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  70857. */
  70858. var Sound = /** @class */ (function () {
  70859. /**
  70860. * Create a sound and attach it to a scene
  70861. * @param name Name of your sound
  70862. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  70863. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  70864. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  70865. */
  70866. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  70867. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  70868. var _this = this;
  70869. /**
  70870. * Does the sound autoplay once loaded.
  70871. */
  70872. this.autoplay = false;
  70873. /**
  70874. * Does the sound loop after it finishes playing once.
  70875. */
  70876. this.loop = false;
  70877. /**
  70878. * Does the sound use a custom attenuation curve to simulate the falloff
  70879. * happening when the source gets further away from the camera.
  70880. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  70881. */
  70882. this.useCustomAttenuation = false;
  70883. /**
  70884. * Is this sound currently played.
  70885. */
  70886. this.isPlaying = false;
  70887. /**
  70888. * Is this sound currently paused.
  70889. */
  70890. this.isPaused = false;
  70891. /**
  70892. * Does this sound enables spatial sound.
  70893. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70894. */
  70895. this.spatialSound = false;
  70896. /**
  70897. * Define the reference distance the sound should be heard perfectly.
  70898. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70899. */
  70900. this.refDistance = 1;
  70901. /**
  70902. * Define the roll off factor of spatial sounds.
  70903. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70904. */
  70905. this.rolloffFactor = 1;
  70906. /**
  70907. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  70908. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70909. */
  70910. this.maxDistance = 100;
  70911. /**
  70912. * Define the distance attenuation model the sound will follow.
  70913. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70914. */
  70915. this.distanceModel = "linear";
  70916. /**
  70917. * Observable event when the current playing sound finishes.
  70918. */
  70919. this.onEndedObservable = new BABYLON.Observable();
  70920. this._panningModel = "equalpower";
  70921. this._playbackRate = 1;
  70922. this._streaming = false;
  70923. this._startTime = 0;
  70924. this._startOffset = 0;
  70925. this._position = BABYLON.Vector3.Zero();
  70926. /** @hidden */
  70927. this._positionInEmitterSpace = false;
  70928. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  70929. this._volume = 1;
  70930. this._isReadyToPlay = false;
  70931. this._isDirectional = false;
  70932. // Used if you'd like to create a directional sound.
  70933. // If not set, the sound will be omnidirectional
  70934. this._coneInnerAngle = 360;
  70935. this._coneOuterAngle = 360;
  70936. this._coneOuterGain = 0;
  70937. this._isOutputConnected = false;
  70938. this._urlType = "Unknown";
  70939. this.name = name;
  70940. this._scene = scene;
  70941. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70942. if (!compo) {
  70943. compo = new BABYLON.AudioSceneComponent(scene);
  70944. scene._addComponent(compo);
  70945. }
  70946. this._readyToPlayCallback = readyToPlayCallback;
  70947. // Default custom attenuation function is a linear attenuation
  70948. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  70949. if (currentDistance < maxDistance) {
  70950. return currentVolume * (1 - currentDistance / maxDistance);
  70951. }
  70952. else {
  70953. return 0;
  70954. }
  70955. };
  70956. if (options) {
  70957. this.autoplay = options.autoplay || false;
  70958. this.loop = options.loop || false;
  70959. // if volume === 0, we need another way to check this option
  70960. if (options.volume !== undefined) {
  70961. this._volume = options.volume;
  70962. }
  70963. this.spatialSound = options.spatialSound || false;
  70964. this.maxDistance = options.maxDistance || 100;
  70965. this.useCustomAttenuation = options.useCustomAttenuation || false;
  70966. this.rolloffFactor = options.rolloffFactor || 1;
  70967. this.refDistance = options.refDistance || 1;
  70968. this.distanceModel = options.distanceModel || "linear";
  70969. this._playbackRate = options.playbackRate || 1;
  70970. this._streaming = options.streaming || false;
  70971. }
  70972. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  70973. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  70974. this._soundGain.gain.value = this._volume;
  70975. this._inputAudioNode = this._soundGain;
  70976. this._outputAudioNode = this._soundGain;
  70977. if (this.spatialSound) {
  70978. this._createSpatialParameters();
  70979. }
  70980. this._scene.mainSoundTrack.AddSound(this);
  70981. var validParameter = true;
  70982. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  70983. if (urlOrArrayBuffer) {
  70984. try {
  70985. if (typeof (urlOrArrayBuffer) === "string") {
  70986. this._urlType = "String";
  70987. }
  70988. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  70989. this._urlType = "ArrayBuffer";
  70990. }
  70991. else if (urlOrArrayBuffer instanceof MediaStream) {
  70992. this._urlType = "MediaStream";
  70993. }
  70994. else if (Array.isArray(urlOrArrayBuffer)) {
  70995. this._urlType = "Array";
  70996. }
  70997. var urls = [];
  70998. var codecSupportedFound = false;
  70999. switch (this._urlType) {
  71000. case "MediaStream":
  71001. this._streaming = true;
  71002. this._isReadyToPlay = true;
  71003. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  71004. if (this.autoplay) {
  71005. this.play();
  71006. }
  71007. if (this._readyToPlayCallback) {
  71008. this._readyToPlayCallback();
  71009. }
  71010. break;
  71011. case "ArrayBuffer":
  71012. if (urlOrArrayBuffer.byteLength > 0) {
  71013. codecSupportedFound = true;
  71014. this._soundLoaded(urlOrArrayBuffer);
  71015. }
  71016. break;
  71017. case "String":
  71018. urls.push(urlOrArrayBuffer);
  71019. case "Array":
  71020. if (urls.length === 0) {
  71021. urls = urlOrArrayBuffer;
  71022. }
  71023. // If we found a supported format, we load it immediately and stop the loop
  71024. for (var i = 0; i < urls.length; i++) {
  71025. var url = urls[i];
  71026. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  71027. codecSupportedFound = true;
  71028. }
  71029. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  71030. codecSupportedFound = true;
  71031. }
  71032. if (url.indexOf(".wav", url.length - 4) !== -1) {
  71033. codecSupportedFound = true;
  71034. }
  71035. if (url.indexOf("blob:") !== -1) {
  71036. codecSupportedFound = true;
  71037. }
  71038. if (codecSupportedFound) {
  71039. // Loading sound using XHR2
  71040. if (!this._streaming) {
  71041. this._scene._loadFile(url, function (data) {
  71042. _this._soundLoaded(data);
  71043. }, undefined, true, true, function (exception) {
  71044. if (exception) {
  71045. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  71046. }
  71047. BABYLON.Tools.Error("Sound creation aborted.");
  71048. _this._scene.mainSoundTrack.RemoveSound(_this);
  71049. });
  71050. }
  71051. // Streaming sound using HTML5 Audio tag
  71052. else {
  71053. this._htmlAudioElement = new Audio(url);
  71054. this._htmlAudioElement.controls = false;
  71055. this._htmlAudioElement.loop = this.loop;
  71056. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  71057. this._htmlAudioElement.preload = "auto";
  71058. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  71059. _this._isReadyToPlay = true;
  71060. if (_this.autoplay) {
  71061. _this.play();
  71062. }
  71063. if (_this._readyToPlayCallback) {
  71064. _this._readyToPlayCallback();
  71065. }
  71066. });
  71067. document.body.appendChild(this._htmlAudioElement);
  71068. this._htmlAudioElement.load();
  71069. }
  71070. break;
  71071. }
  71072. }
  71073. break;
  71074. default:
  71075. validParameter = false;
  71076. break;
  71077. }
  71078. if (!validParameter) {
  71079. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  71080. }
  71081. else {
  71082. if (!codecSupportedFound) {
  71083. this._isReadyToPlay = true;
  71084. // Simulating a ready to play event to avoid breaking code path
  71085. if (this._readyToPlayCallback) {
  71086. window.setTimeout(function () {
  71087. if (_this._readyToPlayCallback) {
  71088. _this._readyToPlayCallback();
  71089. }
  71090. }, 1000);
  71091. }
  71092. }
  71093. }
  71094. }
  71095. catch (ex) {
  71096. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  71097. this._scene.mainSoundTrack.RemoveSound(this);
  71098. }
  71099. }
  71100. }
  71101. else {
  71102. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  71103. this._scene.mainSoundTrack.AddSound(this);
  71104. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  71105. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  71106. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  71107. }
  71108. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  71109. if (this._readyToPlayCallback) {
  71110. window.setTimeout(function () {
  71111. if (_this._readyToPlayCallback) {
  71112. _this._readyToPlayCallback();
  71113. }
  71114. }, 1000);
  71115. }
  71116. }
  71117. }
  71118. /**
  71119. * Release the sound and its associated resources
  71120. */
  71121. Sound.prototype.dispose = function () {
  71122. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71123. if (this.isPlaying) {
  71124. this.stop();
  71125. }
  71126. this._isReadyToPlay = false;
  71127. if (this.soundTrackId === -1) {
  71128. this._scene.mainSoundTrack.RemoveSound(this);
  71129. }
  71130. else if (this._scene.soundTracks) {
  71131. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  71132. }
  71133. if (this._soundGain) {
  71134. this._soundGain.disconnect();
  71135. this._soundGain = null;
  71136. }
  71137. if (this._soundPanner) {
  71138. this._soundPanner.disconnect();
  71139. this._soundPanner = null;
  71140. }
  71141. if (this._soundSource) {
  71142. this._soundSource.disconnect();
  71143. this._soundSource = null;
  71144. }
  71145. this._audioBuffer = null;
  71146. if (this._htmlAudioElement) {
  71147. this._htmlAudioElement.pause();
  71148. this._htmlAudioElement.src = "";
  71149. document.body.removeChild(this._htmlAudioElement);
  71150. }
  71151. if (this._streamingSource) {
  71152. this._streamingSource.disconnect();
  71153. }
  71154. if (this._connectedMesh && this._registerFunc) {
  71155. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  71156. this._connectedMesh = null;
  71157. }
  71158. }
  71159. };
  71160. /**
  71161. * Gets if the sounds is ready to be played or not.
  71162. * @returns true if ready, otherwise false
  71163. */
  71164. Sound.prototype.isReady = function () {
  71165. return this._isReadyToPlay;
  71166. };
  71167. Sound.prototype._soundLoaded = function (audioData) {
  71168. var _this = this;
  71169. if (!BABYLON.Engine.audioEngine.audioContext) {
  71170. return;
  71171. }
  71172. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  71173. _this._audioBuffer = buffer;
  71174. _this._isReadyToPlay = true;
  71175. if (_this.autoplay) {
  71176. _this.play();
  71177. }
  71178. if (_this._readyToPlayCallback) {
  71179. _this._readyToPlayCallback();
  71180. }
  71181. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  71182. };
  71183. /**
  71184. * Sets the data of the sound from an audiobuffer
  71185. * @param audioBuffer The audioBuffer containing the data
  71186. */
  71187. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  71188. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71189. this._audioBuffer = audioBuffer;
  71190. this._isReadyToPlay = true;
  71191. }
  71192. };
  71193. /**
  71194. * Updates the current sounds options such as maxdistance, loop...
  71195. * @param options A JSON object containing values named as the object properties
  71196. */
  71197. Sound.prototype.updateOptions = function (options) {
  71198. if (options) {
  71199. this.loop = options.loop || this.loop;
  71200. this.maxDistance = options.maxDistance || this.maxDistance;
  71201. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  71202. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  71203. this.refDistance = options.refDistance || this.refDistance;
  71204. this.distanceModel = options.distanceModel || this.distanceModel;
  71205. this._playbackRate = options.playbackRate || this._playbackRate;
  71206. this._updateSpatialParameters();
  71207. if (this.isPlaying) {
  71208. if (this._streaming && this._htmlAudioElement) {
  71209. this._htmlAudioElement.playbackRate = this._playbackRate;
  71210. }
  71211. else {
  71212. if (this._soundSource) {
  71213. this._soundSource.playbackRate.value = this._playbackRate;
  71214. }
  71215. }
  71216. }
  71217. }
  71218. };
  71219. Sound.prototype._createSpatialParameters = function () {
  71220. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  71221. if (this._scene.headphone) {
  71222. this._panningModel = "HRTF";
  71223. }
  71224. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  71225. this._updateSpatialParameters();
  71226. this._soundPanner.connect(this._outputAudioNode);
  71227. this._inputAudioNode = this._soundPanner;
  71228. }
  71229. };
  71230. Sound.prototype._updateSpatialParameters = function () {
  71231. if (this.spatialSound && this._soundPanner) {
  71232. if (this.useCustomAttenuation) {
  71233. // Tricks to disable in a way embedded Web Audio attenuation
  71234. this._soundPanner.distanceModel = "linear";
  71235. this._soundPanner.maxDistance = Number.MAX_VALUE;
  71236. this._soundPanner.refDistance = 1;
  71237. this._soundPanner.rolloffFactor = 1;
  71238. this._soundPanner.panningModel = this._panningModel;
  71239. }
  71240. else {
  71241. this._soundPanner.distanceModel = this.distanceModel;
  71242. this._soundPanner.maxDistance = this.maxDistance;
  71243. this._soundPanner.refDistance = this.refDistance;
  71244. this._soundPanner.rolloffFactor = this.rolloffFactor;
  71245. this._soundPanner.panningModel = this._panningModel;
  71246. }
  71247. }
  71248. };
  71249. /**
  71250. * Switch the panning model to HRTF:
  71251. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  71252. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71253. */
  71254. Sound.prototype.switchPanningModelToHRTF = function () {
  71255. this._panningModel = "HRTF";
  71256. this._switchPanningModel();
  71257. };
  71258. /**
  71259. * Switch the panning model to Equal Power:
  71260. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  71261. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71262. */
  71263. Sound.prototype.switchPanningModelToEqualPower = function () {
  71264. this._panningModel = "equalpower";
  71265. this._switchPanningModel();
  71266. };
  71267. Sound.prototype._switchPanningModel = function () {
  71268. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  71269. this._soundPanner.panningModel = this._panningModel;
  71270. }
  71271. };
  71272. /**
  71273. * Connect this sound to a sound track audio node like gain...
  71274. * @param soundTrackAudioNode the sound track audio node to connect to
  71275. */
  71276. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  71277. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71278. if (this._isOutputConnected) {
  71279. this._outputAudioNode.disconnect();
  71280. }
  71281. this._outputAudioNode.connect(soundTrackAudioNode);
  71282. this._isOutputConnected = true;
  71283. }
  71284. };
  71285. /**
  71286. * Transform this sound into a directional source
  71287. * @param coneInnerAngle Size of the inner cone in degree
  71288. * @param coneOuterAngle Size of the outer cone in degree
  71289. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  71290. */
  71291. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  71292. if (coneOuterAngle < coneInnerAngle) {
  71293. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  71294. return;
  71295. }
  71296. this._coneInnerAngle = coneInnerAngle;
  71297. this._coneOuterAngle = coneOuterAngle;
  71298. this._coneOuterGain = coneOuterGain;
  71299. this._isDirectional = true;
  71300. if (this.isPlaying && this.loop) {
  71301. this.stop();
  71302. this.play();
  71303. }
  71304. };
  71305. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  71306. /**
  71307. * Gets or sets the inner angle for the directional cone.
  71308. */
  71309. get: function () {
  71310. return this._coneInnerAngle;
  71311. },
  71312. /**
  71313. * Gets or sets the inner angle for the directional cone.
  71314. */
  71315. set: function (value) {
  71316. if (value != this._coneInnerAngle) {
  71317. if (this._coneOuterAngle < value) {
  71318. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  71319. return;
  71320. }
  71321. this._coneInnerAngle = value;
  71322. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  71323. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  71324. }
  71325. }
  71326. },
  71327. enumerable: true,
  71328. configurable: true
  71329. });
  71330. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  71331. /**
  71332. * Gets or sets the outer angle for the directional cone.
  71333. */
  71334. get: function () {
  71335. return this._coneOuterAngle;
  71336. },
  71337. /**
  71338. * Gets or sets the outer angle for the directional cone.
  71339. */
  71340. set: function (value) {
  71341. if (value != this._coneOuterAngle) {
  71342. if (value < this._coneInnerAngle) {
  71343. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  71344. return;
  71345. }
  71346. this._coneOuterAngle = value;
  71347. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  71348. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  71349. }
  71350. }
  71351. },
  71352. enumerable: true,
  71353. configurable: true
  71354. });
  71355. /**
  71356. * Sets the position of the emitter if spatial sound is enabled
  71357. * @param newPosition Defines the new posisiton
  71358. */
  71359. Sound.prototype.setPosition = function (newPosition) {
  71360. this._position = newPosition;
  71361. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  71362. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  71363. }
  71364. };
  71365. /**
  71366. * Sets the local direction of the emitter if spatial sound is enabled
  71367. * @param newLocalDirection Defines the new local direction
  71368. */
  71369. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  71370. this._localDirection = newLocalDirection;
  71371. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  71372. this._updateDirection();
  71373. }
  71374. };
  71375. Sound.prototype._updateDirection = function () {
  71376. if (!this._connectedMesh || !this._soundPanner) {
  71377. return;
  71378. }
  71379. var mat = this._connectedMesh.getWorldMatrix();
  71380. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  71381. direction.normalize();
  71382. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  71383. };
  71384. /** @hidden */
  71385. Sound.prototype.updateDistanceFromListener = function () {
  71386. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  71387. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  71388. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  71389. }
  71390. };
  71391. /**
  71392. * Sets a new custom attenuation function for the sound.
  71393. * @param callback Defines the function used for the attenuation
  71394. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  71395. */
  71396. Sound.prototype.setAttenuationFunction = function (callback) {
  71397. this._customAttenuationFunction = callback;
  71398. };
  71399. /**
  71400. * Play the sound
  71401. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  71402. * @param offset (optional) Start the sound setting it at a specific time
  71403. */
  71404. Sound.prototype.play = function (time, offset) {
  71405. var _this = this;
  71406. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  71407. try {
  71408. if (this._startOffset < 0) {
  71409. time = -this._startOffset;
  71410. this._startOffset = 0;
  71411. }
  71412. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  71413. if (!this._soundSource || !this._streamingSource) {
  71414. if (this.spatialSound && this._soundPanner) {
  71415. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  71416. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  71417. }
  71418. if (this._isDirectional) {
  71419. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  71420. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  71421. this._soundPanner.coneOuterGain = this._coneOuterGain;
  71422. if (this._connectedMesh) {
  71423. this._updateDirection();
  71424. }
  71425. else {
  71426. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  71427. }
  71428. }
  71429. }
  71430. }
  71431. if (this._streaming) {
  71432. if (!this._streamingSource) {
  71433. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  71434. this._htmlAudioElement.onended = function () { _this._onended(); };
  71435. this._htmlAudioElement.playbackRate = this._playbackRate;
  71436. }
  71437. this._streamingSource.disconnect();
  71438. this._streamingSource.connect(this._inputAudioNode);
  71439. if (this._htmlAudioElement) {
  71440. // required to manage properly the new suspended default state of Chrome
  71441. // When the option 'streaming: true' is used, we need first to wait for
  71442. // the audio engine to be unlocked by a user gesture before trying to play
  71443. // an HTML Audio elememt
  71444. var tryToPlay = function () {
  71445. if (BABYLON.Engine.audioEngine.unlocked) {
  71446. var playPromise = _this._htmlAudioElement.play();
  71447. // In browsers that don’t yet support this functionality,
  71448. // playPromise won’t be defined.
  71449. if (playPromise !== undefined) {
  71450. playPromise.catch(function (error) {
  71451. // Automatic playback failed.
  71452. // Waiting for the audio engine to be unlocked by user click on unmute
  71453. BABYLON.Engine.audioEngine.lock();
  71454. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  71455. });
  71456. }
  71457. }
  71458. else {
  71459. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  71460. }
  71461. };
  71462. tryToPlay();
  71463. }
  71464. }
  71465. else {
  71466. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  71467. this._soundSource.buffer = this._audioBuffer;
  71468. this._soundSource.connect(this._inputAudioNode);
  71469. this._soundSource.loop = this.loop;
  71470. this._soundSource.playbackRate.value = this._playbackRate;
  71471. this._soundSource.onended = function () { _this._onended(); };
  71472. if (this._soundSource.buffer) {
  71473. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  71474. }
  71475. }
  71476. this._startTime = startTime;
  71477. this.isPlaying = true;
  71478. this.isPaused = false;
  71479. }
  71480. catch (ex) {
  71481. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  71482. }
  71483. }
  71484. };
  71485. Sound.prototype._onended = function () {
  71486. this.isPlaying = false;
  71487. if (this.onended) {
  71488. this.onended();
  71489. }
  71490. this.onEndedObservable.notifyObservers(this);
  71491. };
  71492. /**
  71493. * Stop the sound
  71494. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  71495. */
  71496. Sound.prototype.stop = function (time) {
  71497. if (this.isPlaying) {
  71498. if (this._streaming) {
  71499. if (this._htmlAudioElement) {
  71500. this._htmlAudioElement.pause();
  71501. // Test needed for Firefox or it will generate an Invalid State Error
  71502. if (this._htmlAudioElement.currentTime > 0) {
  71503. this._htmlAudioElement.currentTime = 0;
  71504. }
  71505. }
  71506. else {
  71507. this._streamingSource.disconnect();
  71508. }
  71509. }
  71510. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  71511. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  71512. this._soundSource.stop(stopTime);
  71513. this._soundSource.onended = function () { };
  71514. if (!this.isPaused) {
  71515. this._startOffset = 0;
  71516. }
  71517. }
  71518. this.isPlaying = false;
  71519. }
  71520. };
  71521. /**
  71522. * Put the sound in pause
  71523. */
  71524. Sound.prototype.pause = function () {
  71525. if (this.isPlaying) {
  71526. this.isPaused = true;
  71527. if (this._streaming) {
  71528. if (this._htmlAudioElement) {
  71529. this._htmlAudioElement.pause();
  71530. }
  71531. else {
  71532. this._streamingSource.disconnect();
  71533. }
  71534. }
  71535. else if (BABYLON.Engine.audioEngine.audioContext) {
  71536. this.stop(0);
  71537. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  71538. }
  71539. }
  71540. };
  71541. /**
  71542. * Sets a dedicated volume for this sounds
  71543. * @param newVolume Define the new volume of the sound
  71544. * @param time Define in how long the sound should be at this value
  71545. */
  71546. Sound.prototype.setVolume = function (newVolume, time) {
  71547. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  71548. if (time && BABYLON.Engine.audioEngine.audioContext) {
  71549. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  71550. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  71551. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  71552. }
  71553. else {
  71554. this._soundGain.gain.value = newVolume;
  71555. }
  71556. }
  71557. this._volume = newVolume;
  71558. };
  71559. /**
  71560. * Set the sound play back rate
  71561. * @param newPlaybackRate Define the playback rate the sound should be played at
  71562. */
  71563. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  71564. this._playbackRate = newPlaybackRate;
  71565. if (this.isPlaying) {
  71566. if (this._streaming && this._htmlAudioElement) {
  71567. this._htmlAudioElement.playbackRate = this._playbackRate;
  71568. }
  71569. else if (this._soundSource) {
  71570. this._soundSource.playbackRate.value = this._playbackRate;
  71571. }
  71572. }
  71573. };
  71574. /**
  71575. * Gets the volume of the sound.
  71576. * @returns the volume of the sound
  71577. */
  71578. Sound.prototype.getVolume = function () {
  71579. return this._volume;
  71580. };
  71581. /**
  71582. * Attach the sound to a dedicated mesh
  71583. * @param meshToConnectTo The mesh to connect the sound with
  71584. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  71585. */
  71586. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  71587. var _this = this;
  71588. if (this._connectedMesh && this._registerFunc) {
  71589. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  71590. this._registerFunc = null;
  71591. }
  71592. this._connectedMesh = meshToConnectTo;
  71593. if (!this.spatialSound) {
  71594. this.spatialSound = true;
  71595. this._createSpatialParameters();
  71596. if (this.isPlaying && this.loop) {
  71597. this.stop();
  71598. this.play();
  71599. }
  71600. }
  71601. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  71602. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  71603. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  71604. };
  71605. /**
  71606. * Detach the sound from the previously attached mesh
  71607. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  71608. */
  71609. Sound.prototype.detachFromMesh = function () {
  71610. if (this._connectedMesh && this._registerFunc) {
  71611. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  71612. this._registerFunc = null;
  71613. this._connectedMesh = null;
  71614. }
  71615. };
  71616. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  71617. if (!node.getBoundingInfo) {
  71618. return;
  71619. }
  71620. var mesh = node;
  71621. if (this._positionInEmitterSpace) {
  71622. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  71623. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  71624. }
  71625. else {
  71626. var boundingInfo = mesh.getBoundingInfo();
  71627. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  71628. }
  71629. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  71630. this._updateDirection();
  71631. }
  71632. };
  71633. /**
  71634. * Clone the current sound in the scene.
  71635. * @returns the new sound clone
  71636. */
  71637. Sound.prototype.clone = function () {
  71638. var _this = this;
  71639. if (!this._streaming) {
  71640. var setBufferAndRun = function () {
  71641. if (_this._isReadyToPlay) {
  71642. clonedSound._audioBuffer = _this.getAudioBuffer();
  71643. clonedSound._isReadyToPlay = true;
  71644. if (clonedSound.autoplay) {
  71645. clonedSound.play();
  71646. }
  71647. }
  71648. else {
  71649. window.setTimeout(setBufferAndRun, 300);
  71650. }
  71651. };
  71652. var currentOptions = {
  71653. autoplay: this.autoplay, loop: this.loop,
  71654. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  71655. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  71656. refDistance: this.refDistance, distanceModel: this.distanceModel
  71657. };
  71658. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  71659. if (this.useCustomAttenuation) {
  71660. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  71661. }
  71662. clonedSound.setPosition(this._position);
  71663. clonedSound.setPlaybackRate(this._playbackRate);
  71664. setBufferAndRun();
  71665. return clonedSound;
  71666. }
  71667. // Can't clone a streaming sound
  71668. else {
  71669. return null;
  71670. }
  71671. };
  71672. /**
  71673. * Gets the current underlying audio buffer containing the data
  71674. * @returns the audio buffer
  71675. */
  71676. Sound.prototype.getAudioBuffer = function () {
  71677. return this._audioBuffer;
  71678. };
  71679. /**
  71680. * Serializes the Sound in a JSON representation
  71681. * @returns the JSON representation of the sound
  71682. */
  71683. Sound.prototype.serialize = function () {
  71684. var serializationObject = {
  71685. name: this.name,
  71686. url: this.name,
  71687. autoplay: this.autoplay,
  71688. loop: this.loop,
  71689. volume: this._volume,
  71690. spatialSound: this.spatialSound,
  71691. maxDistance: this.maxDistance,
  71692. rolloffFactor: this.rolloffFactor,
  71693. refDistance: this.refDistance,
  71694. distanceModel: this.distanceModel,
  71695. playbackRate: this._playbackRate,
  71696. panningModel: this._panningModel,
  71697. soundTrackId: this.soundTrackId
  71698. };
  71699. if (this.spatialSound) {
  71700. if (this._connectedMesh) {
  71701. serializationObject.connectedMeshId = this._connectedMesh.id;
  71702. }
  71703. serializationObject.position = this._position.asArray();
  71704. serializationObject.refDistance = this.refDistance;
  71705. serializationObject.distanceModel = this.distanceModel;
  71706. serializationObject.isDirectional = this._isDirectional;
  71707. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  71708. serializationObject.coneInnerAngle = this._coneInnerAngle;
  71709. serializationObject.coneOuterAngle = this._coneOuterAngle;
  71710. serializationObject.coneOuterGain = this._coneOuterGain;
  71711. }
  71712. return serializationObject;
  71713. };
  71714. /**
  71715. * Parse a JSON representation of a sound to innstantiate in a given scene
  71716. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  71717. * @param scene Define the scene the new parsed sound should be created in
  71718. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  71719. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  71720. * @returns the newly parsed sound
  71721. */
  71722. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  71723. var soundName = parsedSound.name;
  71724. var soundUrl;
  71725. if (parsedSound.url) {
  71726. soundUrl = rootUrl + parsedSound.url;
  71727. }
  71728. else {
  71729. soundUrl = rootUrl + soundName;
  71730. }
  71731. var options = {
  71732. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  71733. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  71734. rolloffFactor: parsedSound.rolloffFactor,
  71735. refDistance: parsedSound.refDistance,
  71736. distanceModel: parsedSound.distanceModel,
  71737. playbackRate: parsedSound.playbackRate
  71738. };
  71739. var newSound;
  71740. if (!sourceSound) {
  71741. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  71742. scene._addPendingData(newSound);
  71743. }
  71744. else {
  71745. var setBufferAndRun = function () {
  71746. if (sourceSound._isReadyToPlay) {
  71747. newSound._audioBuffer = sourceSound.getAudioBuffer();
  71748. newSound._isReadyToPlay = true;
  71749. if (newSound.autoplay) {
  71750. newSound.play();
  71751. }
  71752. }
  71753. else {
  71754. window.setTimeout(setBufferAndRun, 300);
  71755. }
  71756. };
  71757. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  71758. setBufferAndRun();
  71759. }
  71760. if (parsedSound.position) {
  71761. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  71762. newSound.setPosition(soundPosition);
  71763. }
  71764. if (parsedSound.isDirectional) {
  71765. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  71766. if (parsedSound.localDirectionToMesh) {
  71767. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  71768. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  71769. }
  71770. }
  71771. if (parsedSound.connectedMeshId) {
  71772. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  71773. if (connectedMesh) {
  71774. newSound.attachToMesh(connectedMesh);
  71775. }
  71776. }
  71777. return newSound;
  71778. };
  71779. return Sound;
  71780. }());
  71781. BABYLON.Sound = Sound;
  71782. })(BABYLON || (BABYLON = {}));
  71783. //# sourceMappingURL=sound.js.map
  71784. var BABYLON;
  71785. (function (BABYLON) {
  71786. /**
  71787. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  71788. * It will be also used in a future release to apply effects on a specific track.
  71789. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  71790. */
  71791. var SoundTrack = /** @class */ (function () {
  71792. /**
  71793. * Creates a new sound track.
  71794. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  71795. * @param scene Define the scene the sound track belongs to
  71796. * @param options
  71797. */
  71798. function SoundTrack(scene, options) {
  71799. if (options === void 0) { options = {}; }
  71800. /**
  71801. * The unique identifier of the sound track in the scene.
  71802. */
  71803. this.id = -1;
  71804. this._isMainTrack = false;
  71805. this._isInitialized = false;
  71806. this._scene = scene;
  71807. this.soundCollection = new Array();
  71808. this._options = options;
  71809. if (!this._isMainTrack && this._scene.soundTracks) {
  71810. this._scene.soundTracks.push(this);
  71811. this.id = this._scene.soundTracks.length - 1;
  71812. }
  71813. }
  71814. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  71815. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  71816. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  71817. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  71818. if (this._options) {
  71819. if (this._options.volume) {
  71820. this._outputAudioNode.gain.value = this._options.volume;
  71821. }
  71822. if (this._options.mainTrack) {
  71823. this._isMainTrack = this._options.mainTrack;
  71824. }
  71825. }
  71826. this._isInitialized = true;
  71827. }
  71828. };
  71829. /**
  71830. * Release the sound track and its associated resources
  71831. */
  71832. SoundTrack.prototype.dispose = function () {
  71833. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  71834. if (this._connectedAnalyser) {
  71835. this._connectedAnalyser.stopDebugCanvas();
  71836. }
  71837. while (this.soundCollection.length) {
  71838. this.soundCollection[0].dispose();
  71839. }
  71840. if (this._outputAudioNode) {
  71841. this._outputAudioNode.disconnect();
  71842. }
  71843. this._outputAudioNode = null;
  71844. }
  71845. };
  71846. /**
  71847. * Adds a sound to this sound track
  71848. * @param sound define the cound to add
  71849. * @ignoreNaming
  71850. */
  71851. SoundTrack.prototype.AddSound = function (sound) {
  71852. if (!this._isInitialized) {
  71853. this._initializeSoundTrackAudioGraph();
  71854. }
  71855. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  71856. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  71857. }
  71858. if (sound.soundTrackId) {
  71859. if (sound.soundTrackId === -1) {
  71860. this._scene.mainSoundTrack.RemoveSound(sound);
  71861. }
  71862. else if (this._scene.soundTracks) {
  71863. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  71864. }
  71865. }
  71866. this.soundCollection.push(sound);
  71867. sound.soundTrackId = this.id;
  71868. };
  71869. /**
  71870. * Removes a sound to this sound track
  71871. * @param sound define the cound to remove
  71872. * @ignoreNaming
  71873. */
  71874. SoundTrack.prototype.RemoveSound = function (sound) {
  71875. var index = this.soundCollection.indexOf(sound);
  71876. if (index !== -1) {
  71877. this.soundCollection.splice(index, 1);
  71878. }
  71879. };
  71880. /**
  71881. * Set a global volume for the full sound track.
  71882. * @param newVolume Define the new volume of the sound track
  71883. */
  71884. SoundTrack.prototype.setVolume = function (newVolume) {
  71885. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  71886. this._outputAudioNode.gain.value = newVolume;
  71887. }
  71888. };
  71889. /**
  71890. * Switch the panning model to HRTF:
  71891. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  71892. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71893. */
  71894. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  71895. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71896. for (var i = 0; i < this.soundCollection.length; i++) {
  71897. this.soundCollection[i].switchPanningModelToHRTF();
  71898. }
  71899. }
  71900. };
  71901. /**
  71902. * Switch the panning model to Equal Power:
  71903. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  71904. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  71905. */
  71906. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  71907. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71908. for (var i = 0; i < this.soundCollection.length; i++) {
  71909. this.soundCollection[i].switchPanningModelToEqualPower();
  71910. }
  71911. }
  71912. };
  71913. /**
  71914. * Connect the sound track to an audio analyser allowing some amazing
  71915. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  71916. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  71917. * @param analyser The analyser to connect to the engine
  71918. */
  71919. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  71920. if (this._connectedAnalyser) {
  71921. this._connectedAnalyser.stopDebugCanvas();
  71922. }
  71923. this._connectedAnalyser = analyser;
  71924. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  71925. this._outputAudioNode.disconnect();
  71926. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  71927. }
  71928. };
  71929. return SoundTrack;
  71930. }());
  71931. BABYLON.SoundTrack = SoundTrack;
  71932. })(BABYLON || (BABYLON = {}));
  71933. //# sourceMappingURL=soundtrack.js.map
  71934. var BABYLON;
  71935. (function (BABYLON) {
  71936. /**
  71937. * Class used to work with sound analyzer using fast fourier transform (FFT)
  71938. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  71939. */
  71940. var Analyser = /** @class */ (function () {
  71941. /**
  71942. * Creates a new analyser
  71943. * @param scene defines hosting scene
  71944. */
  71945. function Analyser(scene) {
  71946. /**
  71947. * Gets or sets the smoothing
  71948. * @ignorenaming
  71949. */
  71950. this.SMOOTHING = 0.75;
  71951. /**
  71952. * Gets or sets the FFT table size
  71953. * @ignorenaming
  71954. */
  71955. this.FFT_SIZE = 512;
  71956. /**
  71957. * Gets or sets the bar graph amplitude
  71958. * @ignorenaming
  71959. */
  71960. this.BARGRAPHAMPLITUDE = 256;
  71961. /**
  71962. * Gets or sets the position of the debug canvas
  71963. * @ignorenaming
  71964. */
  71965. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  71966. /**
  71967. * Gets or sets the debug canvas size
  71968. * @ignorenaming
  71969. */
  71970. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  71971. this._scene = scene;
  71972. this._audioEngine = BABYLON.Engine.audioEngine;
  71973. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  71974. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  71975. this._webAudioAnalyser.minDecibels = -140;
  71976. this._webAudioAnalyser.maxDecibels = 0;
  71977. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  71978. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  71979. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  71980. }
  71981. }
  71982. /**
  71983. * Get the number of data values you will have to play with for the visualization
  71984. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  71985. * @returns a number
  71986. */
  71987. Analyser.prototype.getFrequencyBinCount = function () {
  71988. if (this._audioEngine.canUseWebAudio) {
  71989. return this._webAudioAnalyser.frequencyBinCount;
  71990. }
  71991. else {
  71992. return 0;
  71993. }
  71994. };
  71995. /**
  71996. * Gets the current frequency data as a byte array
  71997. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  71998. * @returns a Uint8Array
  71999. */
  72000. Analyser.prototype.getByteFrequencyData = function () {
  72001. if (this._audioEngine.canUseWebAudio) {
  72002. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  72003. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  72004. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  72005. }
  72006. return this._byteFreqs;
  72007. };
  72008. /**
  72009. * Gets the current waveform as a byte array
  72010. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  72011. * @returns a Uint8Array
  72012. */
  72013. Analyser.prototype.getByteTimeDomainData = function () {
  72014. if (this._audioEngine.canUseWebAudio) {
  72015. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  72016. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  72017. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  72018. }
  72019. return this._byteTime;
  72020. };
  72021. /**
  72022. * Gets the current frequency data as a float array
  72023. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  72024. * @returns a Float32Array
  72025. */
  72026. Analyser.prototype.getFloatFrequencyData = function () {
  72027. if (this._audioEngine.canUseWebAudio) {
  72028. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  72029. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  72030. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  72031. }
  72032. return this._floatFreqs;
  72033. };
  72034. /**
  72035. * Renders the debug canvas
  72036. */
  72037. Analyser.prototype.drawDebugCanvas = function () {
  72038. var _this = this;
  72039. if (this._audioEngine.canUseWebAudio) {
  72040. if (!this._debugCanvas) {
  72041. this._debugCanvas = document.createElement("canvas");
  72042. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  72043. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  72044. this._debugCanvas.style.position = "absolute";
  72045. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  72046. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  72047. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  72048. document.body.appendChild(this._debugCanvas);
  72049. this._registerFunc = function () {
  72050. _this.drawDebugCanvas();
  72051. };
  72052. this._scene.registerBeforeRender(this._registerFunc);
  72053. }
  72054. if (this._registerFunc && this._debugCanvasContext) {
  72055. var workingArray = this.getByteFrequencyData();
  72056. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  72057. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  72058. // Draw the frequency domain chart.
  72059. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  72060. var value = workingArray[i];
  72061. var percent = value / this.BARGRAPHAMPLITUDE;
  72062. var height = this.DEBUGCANVASSIZE.height * percent;
  72063. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  72064. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  72065. var hue = i / this.getFrequencyBinCount() * 360;
  72066. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  72067. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  72068. }
  72069. }
  72070. }
  72071. };
  72072. /**
  72073. * Stops rendering the debug canvas and removes it
  72074. */
  72075. Analyser.prototype.stopDebugCanvas = function () {
  72076. if (this._debugCanvas) {
  72077. if (this._registerFunc) {
  72078. this._scene.unregisterBeforeRender(this._registerFunc);
  72079. this._registerFunc = null;
  72080. }
  72081. document.body.removeChild(this._debugCanvas);
  72082. this._debugCanvas = null;
  72083. this._debugCanvasContext = null;
  72084. }
  72085. };
  72086. /**
  72087. * Connects two audio nodes
  72088. * @param inputAudioNode defines first node to connect
  72089. * @param outputAudioNode defines second node to connect
  72090. */
  72091. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  72092. if (this._audioEngine.canUseWebAudio) {
  72093. inputAudioNode.connect(this._webAudioAnalyser);
  72094. this._webAudioAnalyser.connect(outputAudioNode);
  72095. }
  72096. };
  72097. /**
  72098. * Releases all associated resources
  72099. */
  72100. Analyser.prototype.dispose = function () {
  72101. if (this._audioEngine.canUseWebAudio) {
  72102. this._webAudioAnalyser.disconnect();
  72103. }
  72104. };
  72105. return Analyser;
  72106. }());
  72107. BABYLON.Analyser = Analyser;
  72108. })(BABYLON || (BABYLON = {}));
  72109. //# sourceMappingURL=analyser.js.map
  72110. var BABYLON;
  72111. (function (BABYLON) {
  72112. /**
  72113. * Wraps one or more Sound objects and selects one with random weight for playback.
  72114. */
  72115. var WeightedSound = /** @class */ (function () {
  72116. /**
  72117. * Creates a new WeightedSound from the list of sounds given.
  72118. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  72119. * @param sounds Array of Sounds that will be selected from.
  72120. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  72121. */
  72122. function WeightedSound(loop, sounds, weights) {
  72123. var _this = this;
  72124. /** When true a Sound will be selected and played when the current playing Sound completes. */
  72125. this.loop = false;
  72126. this._coneInnerAngle = 360;
  72127. this._coneOuterAngle = 360;
  72128. this._volume = 1;
  72129. /** A Sound is currently playing. */
  72130. this.isPlaying = false;
  72131. /** A Sound is currently paused. */
  72132. this.isPaused = false;
  72133. this._sounds = [];
  72134. this._weights = [];
  72135. if (sounds.length !== weights.length) {
  72136. throw new Error('Sounds length does not equal weights length');
  72137. }
  72138. this.loop = loop;
  72139. this._weights = weights;
  72140. // Normalize the weights
  72141. var weightSum = 0;
  72142. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  72143. var weight = weights_1[_i];
  72144. weightSum += weight;
  72145. }
  72146. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  72147. for (var i = 0; i < this._weights.length; i++) {
  72148. this._weights[i] *= invWeightSum;
  72149. }
  72150. this._sounds = sounds;
  72151. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  72152. var sound = _b[_a];
  72153. sound.onEndedObservable.add(function () { _this._onended(); });
  72154. }
  72155. }
  72156. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  72157. /**
  72158. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  72159. */
  72160. get: function () {
  72161. return this._coneInnerAngle;
  72162. },
  72163. /**
  72164. * The size of cone in degress for a directional sound in which there will be no attenuation.
  72165. */
  72166. set: function (value) {
  72167. if (value !== this._coneInnerAngle) {
  72168. if (this._coneOuterAngle < value) {
  72169. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  72170. return;
  72171. }
  72172. this._coneInnerAngle = value;
  72173. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  72174. var sound = _a[_i];
  72175. sound.directionalConeInnerAngle = value;
  72176. }
  72177. }
  72178. },
  72179. enumerable: true,
  72180. configurable: true
  72181. });
  72182. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  72183. /**
  72184. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  72185. * Listener angles between innerAngle and outerAngle will falloff linearly.
  72186. */
  72187. get: function () {
  72188. return this._coneOuterAngle;
  72189. },
  72190. /**
  72191. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  72192. * Listener angles between innerAngle and outerAngle will falloff linearly.
  72193. */
  72194. set: function (value) {
  72195. if (value !== this._coneOuterAngle) {
  72196. if (value < this._coneInnerAngle) {
  72197. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  72198. return;
  72199. }
  72200. this._coneOuterAngle = value;
  72201. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  72202. var sound = _a[_i];
  72203. sound.directionalConeOuterAngle = value;
  72204. }
  72205. }
  72206. },
  72207. enumerable: true,
  72208. configurable: true
  72209. });
  72210. Object.defineProperty(WeightedSound.prototype, "volume", {
  72211. /**
  72212. * Playback volume.
  72213. */
  72214. get: function () {
  72215. return this._volume;
  72216. },
  72217. /**
  72218. * Playback volume.
  72219. */
  72220. set: function (value) {
  72221. if (value !== this._volume) {
  72222. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  72223. var sound = _a[_i];
  72224. sound.setVolume(value);
  72225. }
  72226. }
  72227. },
  72228. enumerable: true,
  72229. configurable: true
  72230. });
  72231. WeightedSound.prototype._onended = function () {
  72232. if (this._currentIndex !== undefined) {
  72233. this._sounds[this._currentIndex].autoplay = false;
  72234. }
  72235. if (this.loop && this.isPlaying) {
  72236. this.play();
  72237. }
  72238. else {
  72239. this.isPlaying = false;
  72240. }
  72241. };
  72242. /**
  72243. * Suspend playback
  72244. */
  72245. WeightedSound.prototype.pause = function () {
  72246. this.isPaused = true;
  72247. if (this._currentIndex !== undefined) {
  72248. this._sounds[this._currentIndex].pause();
  72249. }
  72250. };
  72251. /**
  72252. * Stop playback
  72253. */
  72254. WeightedSound.prototype.stop = function () {
  72255. this.isPlaying = false;
  72256. if (this._currentIndex !== undefined) {
  72257. this._sounds[this._currentIndex].stop();
  72258. }
  72259. };
  72260. /**
  72261. * Start playback.
  72262. * @param startOffset Position the clip head at a specific time in seconds.
  72263. */
  72264. WeightedSound.prototype.play = function (startOffset) {
  72265. if (!this.isPaused) {
  72266. this.stop();
  72267. var randomValue = Math.random();
  72268. var total = 0;
  72269. for (var i = 0; i < this._weights.length; i++) {
  72270. total += this._weights[i];
  72271. if (randomValue <= total) {
  72272. this._currentIndex = i;
  72273. break;
  72274. }
  72275. }
  72276. }
  72277. var sound = this._sounds[this._currentIndex];
  72278. if (sound.isReady()) {
  72279. sound.play(0, this.isPaused ? undefined : startOffset);
  72280. }
  72281. else {
  72282. sound.autoplay = true;
  72283. }
  72284. this.isPlaying = true;
  72285. this.isPaused = false;
  72286. };
  72287. return WeightedSound;
  72288. }());
  72289. BABYLON.WeightedSound = WeightedSound;
  72290. })(BABYLON || (BABYLON = {}));
  72291. //# sourceMappingURL=weightedsound.js.map
  72292. var BABYLON;
  72293. (function (BABYLON) {
  72294. // Adds the parser to the scene parsers.
  72295. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  72296. // TODO: add sound
  72297. var loadedSounds = [];
  72298. var loadedSound;
  72299. container.sounds = container.sounds || [];
  72300. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  72301. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  72302. var parsedSound = parsedData.sounds[index];
  72303. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  72304. if (!parsedSound.url) {
  72305. parsedSound.url = parsedSound.name;
  72306. }
  72307. if (!loadedSounds[parsedSound.url]) {
  72308. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  72309. loadedSounds[parsedSound.url] = loadedSound;
  72310. container.sounds.push(loadedSound);
  72311. }
  72312. else {
  72313. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  72314. }
  72315. }
  72316. else {
  72317. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  72318. }
  72319. }
  72320. }
  72321. loadedSounds = [];
  72322. });
  72323. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  72324. get: function () {
  72325. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72326. if (!compo) {
  72327. compo = new AudioSceneComponent(this);
  72328. this._addComponent(compo);
  72329. }
  72330. if (!this._mainSoundTrack) {
  72331. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  72332. }
  72333. return this._mainSoundTrack;
  72334. },
  72335. enumerable: true,
  72336. configurable: true
  72337. });
  72338. BABYLON.Scene.prototype.getSoundByName = function (name) {
  72339. var index;
  72340. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  72341. if (this.mainSoundTrack.soundCollection[index].name === name) {
  72342. return this.mainSoundTrack.soundCollection[index];
  72343. }
  72344. }
  72345. if (this.soundTracks) {
  72346. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  72347. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  72348. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  72349. return this.soundTracks[sdIndex].soundCollection[index];
  72350. }
  72351. }
  72352. }
  72353. }
  72354. return null;
  72355. };
  72356. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  72357. get: function () {
  72358. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72359. if (!compo) {
  72360. compo = new AudioSceneComponent(this);
  72361. this._addComponent(compo);
  72362. }
  72363. return compo.audioEnabled;
  72364. },
  72365. set: function (value) {
  72366. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72367. if (!compo) {
  72368. compo = new AudioSceneComponent(this);
  72369. this._addComponent(compo);
  72370. }
  72371. if (value) {
  72372. compo.enableAudio();
  72373. }
  72374. else {
  72375. compo.disableAudio();
  72376. }
  72377. },
  72378. enumerable: true,
  72379. configurable: true
  72380. });
  72381. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  72382. get: function () {
  72383. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72384. if (!compo) {
  72385. compo = new AudioSceneComponent(this);
  72386. this._addComponent(compo);
  72387. }
  72388. return compo.headphone;
  72389. },
  72390. set: function (value) {
  72391. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  72392. if (!compo) {
  72393. compo = new AudioSceneComponent(this);
  72394. this._addComponent(compo);
  72395. }
  72396. if (value) {
  72397. compo.switchAudioModeForHeadphones();
  72398. }
  72399. else {
  72400. compo.switchAudioModeForNormalSpeakers();
  72401. }
  72402. },
  72403. enumerable: true,
  72404. configurable: true
  72405. });
  72406. /**
  72407. * Defines the sound scene component responsible to manage any sounds
  72408. * in a given scene.
  72409. */
  72410. var AudioSceneComponent = /** @class */ (function () {
  72411. /**
  72412. * Creates a new instance of the component for the given scene
  72413. * @param scene Defines the scene to register the component in
  72414. */
  72415. function AudioSceneComponent(scene) {
  72416. /**
  72417. * The component name helpfull to identify the component in the list of scene components.
  72418. */
  72419. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  72420. this._audioEnabled = true;
  72421. this._headphone = false;
  72422. this.scene = scene;
  72423. scene.soundTracks = new Array();
  72424. scene.sounds = new Array();
  72425. }
  72426. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  72427. /**
  72428. * Gets whether audio is enabled or not.
  72429. * Please use related enable/disable method to switch state.
  72430. */
  72431. get: function () {
  72432. return this._audioEnabled;
  72433. },
  72434. enumerable: true,
  72435. configurable: true
  72436. });
  72437. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  72438. /**
  72439. * Gets whether audio is outputing to headphone or not.
  72440. * Please use the according Switch methods to change output.
  72441. */
  72442. get: function () {
  72443. return this._headphone;
  72444. },
  72445. enumerable: true,
  72446. configurable: true
  72447. });
  72448. /**
  72449. * Registers the component in a given scene
  72450. */
  72451. AudioSceneComponent.prototype.register = function () {
  72452. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  72453. };
  72454. /**
  72455. * Rebuilds the elements related to this component in case of
  72456. * context lost for instance.
  72457. */
  72458. AudioSceneComponent.prototype.rebuild = function () {
  72459. // Nothing to do here. (Not rendering related)
  72460. };
  72461. /**
  72462. * Serializes the component data to the specified json object
  72463. * @param serializationObject The object to serialize to
  72464. */
  72465. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  72466. serializationObject.sounds = [];
  72467. if (this.scene.soundTracks) {
  72468. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  72469. var soundtrack = this.scene.soundTracks[index];
  72470. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  72471. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  72472. }
  72473. }
  72474. }
  72475. };
  72476. /**
  72477. * Adds all the element from the container to the scene
  72478. * @param container the container holding the elements
  72479. */
  72480. AudioSceneComponent.prototype.addFromContainer = function (container) {
  72481. var _this = this;
  72482. if (!container.sounds) {
  72483. return;
  72484. }
  72485. container.sounds.forEach(function (sound) {
  72486. sound.play();
  72487. sound.autoplay = true;
  72488. _this.scene.mainSoundTrack.AddSound(sound);
  72489. });
  72490. };
  72491. /**
  72492. * Removes all the elements in the container from the scene
  72493. * @param container contains the elements to remove
  72494. */
  72495. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  72496. var _this = this;
  72497. if (!container.sounds) {
  72498. return;
  72499. }
  72500. container.sounds.forEach(function (sound) {
  72501. sound.stop();
  72502. sound.autoplay = false;
  72503. _this.scene.mainSoundTrack.RemoveSound(sound);
  72504. });
  72505. };
  72506. /**
  72507. * Disposes the component and the associated ressources.
  72508. */
  72509. AudioSceneComponent.prototype.dispose = function () {
  72510. var scene = this.scene;
  72511. if (scene._mainSoundTrack) {
  72512. scene.mainSoundTrack.dispose();
  72513. }
  72514. if (scene.soundTracks) {
  72515. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  72516. scene.soundTracks[scIndex].dispose();
  72517. }
  72518. }
  72519. };
  72520. /**
  72521. * Disables audio in the associated scene.
  72522. */
  72523. AudioSceneComponent.prototype.disableAudio = function () {
  72524. var scene = this.scene;
  72525. this._audioEnabled = false;
  72526. var i;
  72527. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  72528. scene.mainSoundTrack.soundCollection[i].pause();
  72529. }
  72530. if (scene.soundTracks) {
  72531. for (i = 0; i < scene.soundTracks.length; i++) {
  72532. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  72533. scene.soundTracks[i].soundCollection[j].pause();
  72534. }
  72535. }
  72536. }
  72537. };
  72538. /**
  72539. * Enables audio in the associated scene.
  72540. */
  72541. AudioSceneComponent.prototype.enableAudio = function () {
  72542. var scene = this.scene;
  72543. this._audioEnabled = true;
  72544. var i;
  72545. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  72546. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  72547. scene.mainSoundTrack.soundCollection[i].play();
  72548. }
  72549. }
  72550. if (scene.soundTracks) {
  72551. for (i = 0; i < scene.soundTracks.length; i++) {
  72552. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  72553. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  72554. scene.soundTracks[i].soundCollection[j].play();
  72555. }
  72556. }
  72557. }
  72558. }
  72559. };
  72560. /**
  72561. * Switch audio to headphone output.
  72562. */
  72563. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  72564. var scene = this.scene;
  72565. this._headphone = true;
  72566. scene.mainSoundTrack.switchPanningModelToHRTF();
  72567. if (scene.soundTracks) {
  72568. for (var i = 0; i < scene.soundTracks.length; i++) {
  72569. scene.soundTracks[i].switchPanningModelToHRTF();
  72570. }
  72571. }
  72572. };
  72573. /**
  72574. * Switch audio to normal speakers.
  72575. */
  72576. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  72577. var scene = this.scene;
  72578. this._headphone = false;
  72579. scene.mainSoundTrack.switchPanningModelToEqualPower();
  72580. if (scene.soundTracks) {
  72581. for (var i = 0; i < scene.soundTracks.length; i++) {
  72582. scene.soundTracks[i].switchPanningModelToEqualPower();
  72583. }
  72584. }
  72585. };
  72586. AudioSceneComponent.prototype._afterRender = function () {
  72587. var scene = this.scene;
  72588. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  72589. return;
  72590. }
  72591. var listeningCamera;
  72592. var audioEngine = BABYLON.Engine.audioEngine;
  72593. if (scene.activeCameras.length > 0) {
  72594. listeningCamera = scene.activeCameras[0];
  72595. }
  72596. else {
  72597. listeningCamera = scene.activeCamera;
  72598. }
  72599. if (listeningCamera && audioEngine.audioContext) {
  72600. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  72601. // for VR cameras
  72602. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  72603. listeningCamera = listeningCamera.rigCameras[0];
  72604. }
  72605. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  72606. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  72607. cameraDirection.normalize();
  72608. // To avoid some errors on GearVR
  72609. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  72610. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  72611. }
  72612. var i;
  72613. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  72614. var sound = scene.mainSoundTrack.soundCollection[i];
  72615. if (sound.useCustomAttenuation) {
  72616. sound.updateDistanceFromListener();
  72617. }
  72618. }
  72619. if (scene.soundTracks) {
  72620. for (i = 0; i < scene.soundTracks.length; i++) {
  72621. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  72622. sound = scene.soundTracks[i].soundCollection[j];
  72623. if (sound.useCustomAttenuation) {
  72624. sound.updateDistanceFromListener();
  72625. }
  72626. }
  72627. }
  72628. }
  72629. }
  72630. };
  72631. return AudioSceneComponent;
  72632. }());
  72633. BABYLON.AudioSceneComponent = AudioSceneComponent;
  72634. })(BABYLON || (BABYLON = {}));
  72635. //# sourceMappingURL=audioSceneComponent.js.map
  72636. var BABYLON;
  72637. (function (BABYLON) {
  72638. /**
  72639. * This defines an action helpful to play a defined sound on a triggered action.
  72640. */
  72641. var PlaySoundAction = /** @class */ (function (_super) {
  72642. __extends(PlaySoundAction, _super);
  72643. /**
  72644. * Instantiate the action
  72645. * @param triggerOptions defines the trigger options
  72646. * @param sound defines the sound to play
  72647. * @param condition defines the trigger related conditions
  72648. */
  72649. function PlaySoundAction(triggerOptions, sound, condition) {
  72650. var _this = _super.call(this, triggerOptions, condition) || this;
  72651. _this._sound = sound;
  72652. return _this;
  72653. }
  72654. /** @hidden */
  72655. PlaySoundAction.prototype._prepare = function () {
  72656. };
  72657. /**
  72658. * Execute the action and play the sound.
  72659. */
  72660. PlaySoundAction.prototype.execute = function () {
  72661. if (this._sound !== undefined) {
  72662. this._sound.play();
  72663. }
  72664. };
  72665. /**
  72666. * Serializes the actions and its related information.
  72667. * @param parent defines the object to serialize in
  72668. * @returns the serialized object
  72669. */
  72670. PlaySoundAction.prototype.serialize = function (parent) {
  72671. return _super.prototype._serialize.call(this, {
  72672. name: "PlaySoundAction",
  72673. properties: [{ name: "sound", value: this._sound.name }]
  72674. }, parent);
  72675. };
  72676. return PlaySoundAction;
  72677. }(BABYLON.Action));
  72678. BABYLON.PlaySoundAction = PlaySoundAction;
  72679. /**
  72680. * This defines an action helpful to stop a defined sound on a triggered action.
  72681. */
  72682. var StopSoundAction = /** @class */ (function (_super) {
  72683. __extends(StopSoundAction, _super);
  72684. /**
  72685. * Instantiate the action
  72686. * @param triggerOptions defines the trigger options
  72687. * @param sound defines the sound to stop
  72688. * @param condition defines the trigger related conditions
  72689. */
  72690. function StopSoundAction(triggerOptions, sound, condition) {
  72691. var _this = _super.call(this, triggerOptions, condition) || this;
  72692. _this._sound = sound;
  72693. return _this;
  72694. }
  72695. /** @hidden */
  72696. StopSoundAction.prototype._prepare = function () {
  72697. };
  72698. /**
  72699. * Execute the action and stop the sound.
  72700. */
  72701. StopSoundAction.prototype.execute = function () {
  72702. if (this._sound !== undefined) {
  72703. this._sound.stop();
  72704. }
  72705. };
  72706. /**
  72707. * Serializes the actions and its related information.
  72708. * @param parent defines the object to serialize in
  72709. * @returns the serialized object
  72710. */
  72711. StopSoundAction.prototype.serialize = function (parent) {
  72712. return _super.prototype._serialize.call(this, {
  72713. name: "StopSoundAction",
  72714. properties: [{ name: "sound", value: this._sound.name }]
  72715. }, parent);
  72716. };
  72717. return StopSoundAction;
  72718. }(BABYLON.Action));
  72719. BABYLON.StopSoundAction = StopSoundAction;
  72720. })(BABYLON || (BABYLON = {}));
  72721. //# sourceMappingURL=directAudioActions.js.map
  72722. var BABYLON;
  72723. (function (BABYLON) {
  72724. /**
  72725. * Class for creating a cube texture
  72726. */
  72727. var CubeTexture = /** @class */ (function (_super) {
  72728. __extends(CubeTexture, _super);
  72729. /**
  72730. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  72731. * as prefiltered data.
  72732. * @param rootUrl defines the url of the texture or the root name of the six images
  72733. * @param scene defines the scene the texture is attached to
  72734. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  72735. * @param noMipmap defines if mipmaps should be created or not
  72736. * @param files defines the six files to load for the different faces
  72737. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  72738. * @param onError defines a callback triggered in case of error during load
  72739. * @param format defines the internal format to use for the texture once loaded
  72740. * @param prefiltered defines whether or not the texture is created from prefiltered data
  72741. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  72742. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  72743. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  72744. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  72745. * @return the cube texture
  72746. */
  72747. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  72748. if (extensions === void 0) { extensions = null; }
  72749. if (noMipmap === void 0) { noMipmap = false; }
  72750. if (files === void 0) { files = null; }
  72751. if (onLoad === void 0) { onLoad = null; }
  72752. if (onError === void 0) { onError = null; }
  72753. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  72754. if (prefiltered === void 0) { prefiltered = false; }
  72755. if (forcedExtension === void 0) { forcedExtension = null; }
  72756. if (createPolynomials === void 0) { createPolynomials = false; }
  72757. if (lodScale === void 0) { lodScale = 0.8; }
  72758. if (lodOffset === void 0) { lodOffset = 0; }
  72759. var _this = _super.call(this, scene) || this;
  72760. /**
  72761. * Gets or sets the center of the bounding box associated with the cube texture.
  72762. * It must define where the camera used to render the texture was set
  72763. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  72764. */
  72765. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  72766. _this._rotationY = 0;
  72767. /** @hidden */
  72768. _this._prefiltered = false;
  72769. _this.name = rootUrl;
  72770. _this.url = rootUrl;
  72771. _this._noMipmap = noMipmap;
  72772. _this.hasAlpha = false;
  72773. _this._format = format;
  72774. _this.isCube = true;
  72775. _this._textureMatrix = BABYLON.Matrix.Identity();
  72776. _this._createPolynomials = createPolynomials;
  72777. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  72778. if (!rootUrl && !files) {
  72779. return _this;
  72780. }
  72781. var lastDot = rootUrl.lastIndexOf(".");
  72782. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  72783. var isDDS = (extension === ".dds");
  72784. var isEnv = (extension === ".env");
  72785. if (isEnv) {
  72786. _this.gammaSpace = false;
  72787. _this._prefiltered = false;
  72788. }
  72789. else {
  72790. _this._prefiltered = prefiltered;
  72791. if (prefiltered) {
  72792. _this.gammaSpace = false;
  72793. }
  72794. }
  72795. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  72796. if (!files) {
  72797. if (!isEnv && !isDDS && !extensions) {
  72798. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  72799. }
  72800. files = [];
  72801. if (extensions) {
  72802. for (var index = 0; index < extensions.length; index++) {
  72803. files.push(rootUrl + extensions[index]);
  72804. }
  72805. }
  72806. }
  72807. _this._files = files;
  72808. if (!_this._texture) {
  72809. if (!scene.useDelayedTextureLoading) {
  72810. if (prefiltered) {
  72811. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  72812. }
  72813. else {
  72814. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  72815. }
  72816. }
  72817. else {
  72818. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  72819. }
  72820. }
  72821. else if (onLoad) {
  72822. if (_this._texture.isReady) {
  72823. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  72824. }
  72825. else {
  72826. _this._texture.onLoadedObservable.add(onLoad);
  72827. }
  72828. }
  72829. return _this;
  72830. }
  72831. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  72832. /**
  72833. * Returns the bounding box size
  72834. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  72835. */
  72836. get: function () {
  72837. return this._boundingBoxSize;
  72838. },
  72839. /**
  72840. * Gets or sets the size of the bounding box associated with the cube texture
  72841. * When defined, the cubemap will switch to local mode
  72842. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  72843. * @example https://www.babylonjs-playground.com/#RNASML
  72844. */
  72845. set: function (value) {
  72846. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  72847. return;
  72848. }
  72849. this._boundingBoxSize = value;
  72850. var scene = this.getScene();
  72851. if (scene) {
  72852. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  72853. }
  72854. },
  72855. enumerable: true,
  72856. configurable: true
  72857. });
  72858. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  72859. /**
  72860. * Gets texture matrix rotation angle around Y axis radians.
  72861. */
  72862. get: function () {
  72863. return this._rotationY;
  72864. },
  72865. /**
  72866. * Sets texture matrix rotation angle around Y axis in radians.
  72867. */
  72868. set: function (value) {
  72869. this._rotationY = value;
  72870. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  72871. },
  72872. enumerable: true,
  72873. configurable: true
  72874. });
  72875. /**
  72876. * Creates a cube texture from an array of image urls
  72877. * @param files defines an array of image urls
  72878. * @param scene defines the hosting scene
  72879. * @param noMipmap specifies if mip maps are not used
  72880. * @returns a cube texture
  72881. */
  72882. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  72883. var rootUrlKey = "";
  72884. files.forEach(function (url) { return rootUrlKey += url; });
  72885. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  72886. };
  72887. /**
  72888. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  72889. * @param url defines the url of the prefiltered texture
  72890. * @param scene defines the scene the texture is attached to
  72891. * @param forcedExtension defines the extension of the file if different from the url
  72892. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  72893. * @return the prefiltered texture
  72894. */
  72895. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  72896. if (forcedExtension === void 0) { forcedExtension = null; }
  72897. if (createPolynomials === void 0) { createPolynomials = true; }
  72898. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  72899. };
  72900. /**
  72901. * Delays loading of the cube texture
  72902. */
  72903. CubeTexture.prototype.delayLoad = function () {
  72904. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  72905. return;
  72906. }
  72907. var scene = this.getScene();
  72908. if (!scene) {
  72909. return;
  72910. }
  72911. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  72912. this._texture = this._getFromCache(this.url, this._noMipmap);
  72913. if (!this._texture) {
  72914. if (this._prefiltered) {
  72915. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  72916. }
  72917. else {
  72918. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  72919. }
  72920. }
  72921. };
  72922. /**
  72923. * Returns the reflection texture matrix
  72924. * @returns the reflection texture matrix
  72925. */
  72926. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  72927. return this._textureMatrix;
  72928. };
  72929. /**
  72930. * Sets the reflection texture matrix
  72931. * @param value Reflection texture matrix
  72932. */
  72933. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  72934. this._textureMatrix = value;
  72935. };
  72936. /**
  72937. * Parses text to create a cube texture
  72938. * @param parsedTexture define the serialized text to read from
  72939. * @param scene defines the hosting scene
  72940. * @param rootUrl defines the root url of the cube texture
  72941. * @returns a cube texture
  72942. */
  72943. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  72944. var texture = BABYLON.SerializationHelper.Parse(function () {
  72945. var prefiltered = false;
  72946. if (parsedTexture.prefiltered) {
  72947. prefiltered = parsedTexture.prefiltered;
  72948. }
  72949. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  72950. }, parsedTexture, scene);
  72951. // Local Cubemaps
  72952. if (parsedTexture.boundingBoxPosition) {
  72953. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  72954. }
  72955. if (parsedTexture.boundingBoxSize) {
  72956. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  72957. }
  72958. // Animations
  72959. if (parsedTexture.animations) {
  72960. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  72961. var parsedAnimation = parsedTexture.animations[animationIndex];
  72962. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  72963. }
  72964. }
  72965. return texture;
  72966. };
  72967. /**
  72968. * Makes a clone, or deep copy, of the cube texture
  72969. * @returns a new cube texture
  72970. */
  72971. CubeTexture.prototype.clone = function () {
  72972. var _this = this;
  72973. return BABYLON.SerializationHelper.Clone(function () {
  72974. var scene = _this.getScene();
  72975. if (!scene) {
  72976. return _this;
  72977. }
  72978. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  72979. }, this);
  72980. };
  72981. __decorate([
  72982. BABYLON.serialize("rotationY")
  72983. ], CubeTexture.prototype, "rotationY", null);
  72984. return CubeTexture;
  72985. }(BABYLON.BaseTexture));
  72986. BABYLON.CubeTexture = CubeTexture;
  72987. })(BABYLON || (BABYLON = {}));
  72988. //# sourceMappingURL=cubeTexture.js.map
  72989. var BABYLON;
  72990. (function (BABYLON) {
  72991. /**
  72992. * Raw cube texture where the raw buffers are passed in
  72993. */
  72994. var RawCubeTexture = /** @class */ (function (_super) {
  72995. __extends(RawCubeTexture, _super);
  72996. /**
  72997. * Creates a cube texture where the raw buffers are passed in.
  72998. * @param scene defines the scene the texture is attached to
  72999. * @param data defines the array of data to use to create each face
  73000. * @param size defines the size of the textures
  73001. * @param format defines the format of the data
  73002. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  73003. * @param generateMipMaps defines if the engine should generate the mip levels
  73004. * @param invertY defines if data must be stored with Y axis inverted
  73005. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  73006. * @param compression defines the compression used (null by default)
  73007. */
  73008. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  73009. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  73010. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73011. if (generateMipMaps === void 0) { generateMipMaps = false; }
  73012. if (invertY === void 0) { invertY = false; }
  73013. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73014. if (compression === void 0) { compression = null; }
  73015. var _this = _super.call(this, "", scene) || this;
  73016. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  73017. return _this;
  73018. }
  73019. /**
  73020. * Updates the raw cube texture.
  73021. * @param data defines the data to store
  73022. * @param format defines the data format
  73023. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  73024. * @param invertY defines if data must be stored with Y axis inverted
  73025. * @param compression defines the compression used (null by default)
  73026. * @param level defines which level of the texture to update
  73027. */
  73028. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  73029. if (compression === void 0) { compression = null; }
  73030. if (level === void 0) { level = 0; }
  73031. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  73032. };
  73033. /**
  73034. * Updates a raw cube texture with RGBD encoded data.
  73035. * @param data defines the array of data [mipmap][face] to use to create each face
  73036. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  73037. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  73038. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  73039. * @returns a promsie that resolves when the operation is complete
  73040. */
  73041. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  73042. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  73043. if (lodScale === void 0) { lodScale = 0.8; }
  73044. if (lodOffset === void 0) { lodOffset = 0; }
  73045. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  73046. };
  73047. /**
  73048. * Clones the raw cube texture.
  73049. * @return a new cube texture
  73050. */
  73051. RawCubeTexture.prototype.clone = function () {
  73052. var _this = this;
  73053. return BABYLON.SerializationHelper.Clone(function () {
  73054. var scene = _this.getScene();
  73055. var internalTexture = _this._texture;
  73056. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  73057. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  73058. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  73059. }
  73060. return texture;
  73061. }, this);
  73062. };
  73063. /** @hidden */
  73064. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  73065. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  73066. internalTexture._bufferViewArrayArray = data;
  73067. internalTexture._lodGenerationScale = lodScale;
  73068. internalTexture._lodGenerationOffset = lodOffset;
  73069. internalTexture._sphericalPolynomial = sphericalPolynomial;
  73070. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  73071. internalTexture.isReady = true;
  73072. });
  73073. };
  73074. return RawCubeTexture;
  73075. }(BABYLON.CubeTexture));
  73076. BABYLON.RawCubeTexture = RawCubeTexture;
  73077. })(BABYLON || (BABYLON = {}));
  73078. //# sourceMappingURL=rawCubeTexture.js.map
  73079. var BABYLON;
  73080. (function (BABYLON) {
  73081. /**
  73082. * This Helps creating a texture that will be created from a camera in your scene.
  73083. * It is basically a dynamic texture that could be used to create special effects for instance.
  73084. * Actually, It is the base of lot of effects in the framework like post process, shadows, effect layers and rendering pipelines...
  73085. */
  73086. var RenderTargetTexture = /** @class */ (function (_super) {
  73087. __extends(RenderTargetTexture, _super);
  73088. /**
  73089. * Instantiate a render target texture. This is mainly used to render of screen the scene to for instance apply post processse
  73090. * or used a shadow, depth texture...
  73091. * @param name The friendly name of the texture
  73092. * @param size The size of the RTT (number if square, or {width: number, height:number} or {ratio:} to define a ratio from the main scene)
  73093. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  73094. * @param generateMipMaps True if mip maps need to be generated after render.
  73095. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  73096. * @param type The type of the buffer in the RTT (int, half float, float...)
  73097. * @param isCube True if a cube texture needs to be created
  73098. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  73099. * @param generateDepthBuffer True to generate a depth buffer
  73100. * @param generateStencilBuffer True to generate a stencil buffer
  73101. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  73102. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  73103. * @param delayAllocation if the texture allocation should be delayed (default: false)
  73104. */
  73105. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format, delayAllocation) {
  73106. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  73107. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73108. if (isCube === void 0) { isCube = false; }
  73109. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73110. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  73111. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  73112. if (isMulti === void 0) { isMulti = false; }
  73113. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  73114. if (delayAllocation === void 0) { delayAllocation = false; }
  73115. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  73116. _this.isCube = isCube;
  73117. /**
  73118. * Define if particles should be rendered in your texture.
  73119. */
  73120. _this.renderParticles = true;
  73121. /**
  73122. * Define if sprites should be rendered in your texture.
  73123. */
  73124. _this.renderSprites = false;
  73125. /**
  73126. * Override the default coordinates mode to projection for RTT as it is the most common case for rendered textures.
  73127. */
  73128. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  73129. /**
  73130. * Define if the camera viewport should be respected while rendering the texture or if the render should be done to the entire texture.
  73131. */
  73132. _this.ignoreCameraViewport = false;
  73133. /**
  73134. * An event triggered when the texture is unbind.
  73135. */
  73136. _this.onBeforeBindObservable = new BABYLON.Observable();
  73137. /**
  73138. * An event triggered when the texture is unbind.
  73139. */
  73140. _this.onAfterUnbindObservable = new BABYLON.Observable();
  73141. /**
  73142. * An event triggered before rendering the texture
  73143. */
  73144. _this.onBeforeRenderObservable = new BABYLON.Observable();
  73145. /**
  73146. * An event triggered after rendering the texture
  73147. */
  73148. _this.onAfterRenderObservable = new BABYLON.Observable();
  73149. /**
  73150. * An event triggered after the texture clear
  73151. */
  73152. _this.onClearObservable = new BABYLON.Observable();
  73153. _this._currentRefreshId = -1;
  73154. _this._refreshRate = 1;
  73155. _this._samples = 1;
  73156. /**
  73157. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  73158. * It must define where the camera used to render the texture is set
  73159. */
  73160. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  73161. scene = _this.getScene();
  73162. if (!scene) {
  73163. return _this;
  73164. }
  73165. _this.renderList = new Array();
  73166. _this._engine = scene.getEngine();
  73167. _this.name = name;
  73168. _this.isRenderTarget = true;
  73169. _this._initialSizeParameter = size;
  73170. _this._processSizeParameter(size);
  73171. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  73172. });
  73173. _this._generateMipMaps = generateMipMaps ? true : false;
  73174. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  73175. // Rendering groups
  73176. _this._renderingManager = new BABYLON.RenderingManager(scene);
  73177. _this._renderingManager._useSceneAutoClearSetup = true;
  73178. if (isMulti) {
  73179. return _this;
  73180. }
  73181. _this._renderTargetOptions = {
  73182. generateMipMaps: generateMipMaps,
  73183. type: type,
  73184. format: format,
  73185. samplingMode: samplingMode,
  73186. generateDepthBuffer: generateDepthBuffer,
  73187. generateStencilBuffer: generateStencilBuffer
  73188. };
  73189. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  73190. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73191. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73192. }
  73193. if (!delayAllocation) {
  73194. if (isCube) {
  73195. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  73196. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  73197. _this._textureMatrix = BABYLON.Matrix.Identity();
  73198. }
  73199. else {
  73200. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  73201. }
  73202. }
  73203. return _this;
  73204. }
  73205. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  73206. /**
  73207. * Use this list to define the list of mesh you want to render.
  73208. */
  73209. get: function () {
  73210. return this._renderList;
  73211. },
  73212. set: function (value) {
  73213. this._renderList = value;
  73214. if (this._renderList) {
  73215. this._hookArray(this._renderList);
  73216. }
  73217. },
  73218. enumerable: true,
  73219. configurable: true
  73220. });
  73221. RenderTargetTexture.prototype._hookArray = function (array) {
  73222. var _this = this;
  73223. var oldPush = array.push;
  73224. array.push = function () {
  73225. var items = [];
  73226. for (var _i = 0; _i < arguments.length; _i++) {
  73227. items[_i] = arguments[_i];
  73228. }
  73229. var wasEmpty = array.length === 0;
  73230. var result = oldPush.apply(array, items);
  73231. if (wasEmpty) {
  73232. _this.getScene().meshes.forEach(function (mesh) {
  73233. mesh._markSubMeshesAsLightDirty();
  73234. });
  73235. }
  73236. return result;
  73237. };
  73238. var oldSplice = array.splice;
  73239. array.splice = function (index, deleteCount) {
  73240. var deleted = oldSplice.apply(array, [index, deleteCount]);
  73241. if (array.length === 0) {
  73242. _this.getScene().meshes.forEach(function (mesh) {
  73243. mesh._markSubMeshesAsLightDirty();
  73244. });
  73245. }
  73246. return deleted;
  73247. };
  73248. };
  73249. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  73250. /**
  73251. * Set a after unbind callback in the texture.
  73252. * This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended.
  73253. */
  73254. set: function (callback) {
  73255. if (this._onAfterUnbindObserver) {
  73256. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  73257. }
  73258. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  73259. },
  73260. enumerable: true,
  73261. configurable: true
  73262. });
  73263. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  73264. /**
  73265. * Set a before render callback in the texture.
  73266. * This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended.
  73267. */
  73268. set: function (callback) {
  73269. if (this._onBeforeRenderObserver) {
  73270. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  73271. }
  73272. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  73273. },
  73274. enumerable: true,
  73275. configurable: true
  73276. });
  73277. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  73278. /**
  73279. * Set a after render callback in the texture.
  73280. * This has been kept for backward compatibility and use of onAfterRenderObservable is recommended.
  73281. */
  73282. set: function (callback) {
  73283. if (this._onAfterRenderObserver) {
  73284. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  73285. }
  73286. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  73287. },
  73288. enumerable: true,
  73289. configurable: true
  73290. });
  73291. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  73292. /**
  73293. * Set a clear callback in the texture.
  73294. * This has been kept for backward compatibility and use of onClearObservable is recommended.
  73295. */
  73296. set: function (callback) {
  73297. if (this._onClearObserver) {
  73298. this.onClearObservable.remove(this._onClearObserver);
  73299. }
  73300. this._onClearObserver = this.onClearObservable.add(callback);
  73301. },
  73302. enumerable: true,
  73303. configurable: true
  73304. });
  73305. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  73306. /**
  73307. * Gets render target creation options that were used.
  73308. */
  73309. get: function () {
  73310. return this._renderTargetOptions;
  73311. },
  73312. enumerable: true,
  73313. configurable: true
  73314. });
  73315. RenderTargetTexture.prototype._onRatioRescale = function () {
  73316. if (this._sizeRatio) {
  73317. this.resize(this._initialSizeParameter);
  73318. }
  73319. };
  73320. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  73321. get: function () {
  73322. return this._boundingBoxSize;
  73323. },
  73324. /**
  73325. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  73326. * When defined, the cubemap will switch to local mode
  73327. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  73328. * @example https://www.babylonjs-playground.com/#RNASML
  73329. */
  73330. set: function (value) {
  73331. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  73332. return;
  73333. }
  73334. this._boundingBoxSize = value;
  73335. var scene = this.getScene();
  73336. if (scene) {
  73337. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  73338. }
  73339. },
  73340. enumerable: true,
  73341. configurable: true
  73342. });
  73343. /**
  73344. * Creates a depth stencil texture.
  73345. * This is only available in WebGL 2 or with the depth texture extension available.
  73346. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  73347. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  73348. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  73349. */
  73350. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  73351. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  73352. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  73353. if (generateStencil === void 0) { generateStencil = false; }
  73354. if (!this.getScene()) {
  73355. return;
  73356. }
  73357. var engine = this.getScene().getEngine();
  73358. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  73359. bilinearFiltering: bilinearFiltering,
  73360. comparisonFunction: comparisonFunction,
  73361. generateStencil: generateStencil,
  73362. isCube: this.isCube
  73363. });
  73364. engine.setFrameBufferDepthStencilTexture(this);
  73365. };
  73366. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  73367. if (size.ratio) {
  73368. this._sizeRatio = size.ratio;
  73369. this._size = {
  73370. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  73371. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  73372. };
  73373. }
  73374. else {
  73375. this._size = size;
  73376. }
  73377. };
  73378. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  73379. /**
  73380. * Define the number of samples to use in case of MSAA.
  73381. * It defaults to one meaning no MSAA has been enabled.
  73382. */
  73383. get: function () {
  73384. return this._samples;
  73385. },
  73386. set: function (value) {
  73387. if (this._samples === value) {
  73388. return;
  73389. }
  73390. var scene = this.getScene();
  73391. if (!scene) {
  73392. return;
  73393. }
  73394. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  73395. },
  73396. enumerable: true,
  73397. configurable: true
  73398. });
  73399. /**
  73400. * Resets the refresh counter of the texture and start bak from scratch.
  73401. * Could be usefull to regenerate the texture if it is setup to render only once.
  73402. */
  73403. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  73404. this._currentRefreshId = -1;
  73405. };
  73406. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  73407. /**
  73408. * Define the refresh rate of the texture or the rendering frequency.
  73409. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  73410. */
  73411. get: function () {
  73412. return this._refreshRate;
  73413. },
  73414. set: function (value) {
  73415. this._refreshRate = value;
  73416. this.resetRefreshCounter();
  73417. },
  73418. enumerable: true,
  73419. configurable: true
  73420. });
  73421. /**
  73422. * Adds a post process to the render target rendering passes.
  73423. * @param postProcess define the post process to add
  73424. */
  73425. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  73426. if (!this._postProcessManager) {
  73427. var scene = this.getScene();
  73428. if (!scene) {
  73429. return;
  73430. }
  73431. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  73432. this._postProcesses = new Array();
  73433. }
  73434. this._postProcesses.push(postProcess);
  73435. this._postProcesses[0].autoClear = false;
  73436. };
  73437. /**
  73438. * Clear all the post processes attached to the render target
  73439. * @param dispose define if the cleared post processesshould also be disposed (false by default)
  73440. */
  73441. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  73442. if (dispose === void 0) { dispose = false; }
  73443. if (!this._postProcesses) {
  73444. return;
  73445. }
  73446. if (dispose) {
  73447. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  73448. var postProcess = _a[_i];
  73449. postProcess.dispose();
  73450. }
  73451. }
  73452. this._postProcesses = [];
  73453. };
  73454. /**
  73455. * Remove one of the post process from the list of attached post processes to the texture
  73456. * @param postProcess define the post process to remove from the list
  73457. */
  73458. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  73459. if (!this._postProcesses) {
  73460. return;
  73461. }
  73462. var index = this._postProcesses.indexOf(postProcess);
  73463. if (index === -1) {
  73464. return;
  73465. }
  73466. this._postProcesses.splice(index, 1);
  73467. if (this._postProcesses.length > 0) {
  73468. this._postProcesses[0].autoClear = false;
  73469. }
  73470. };
  73471. /** @hidden */
  73472. RenderTargetTexture.prototype._shouldRender = function () {
  73473. if (this._currentRefreshId === -1) { // At least render once
  73474. this._currentRefreshId = 1;
  73475. return true;
  73476. }
  73477. if (this.refreshRate === this._currentRefreshId) {
  73478. this._currentRefreshId = 1;
  73479. return true;
  73480. }
  73481. this._currentRefreshId++;
  73482. return false;
  73483. };
  73484. /**
  73485. * Gets the actual render size of the texture.
  73486. * @returns the width of the render size
  73487. */
  73488. RenderTargetTexture.prototype.getRenderSize = function () {
  73489. return this.getRenderWidth();
  73490. };
  73491. /**
  73492. * Gets the actual render width of the texture.
  73493. * @returns the width of the render size
  73494. */
  73495. RenderTargetTexture.prototype.getRenderWidth = function () {
  73496. if (this._size.width) {
  73497. return this._size.width;
  73498. }
  73499. return this._size;
  73500. };
  73501. /**
  73502. * Gets the actual render height of the texture.
  73503. * @returns the height of the render size
  73504. */
  73505. RenderTargetTexture.prototype.getRenderHeight = function () {
  73506. if (this._size.width) {
  73507. return this._size.height;
  73508. }
  73509. return this._size;
  73510. };
  73511. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  73512. /**
  73513. * Get if the texture can be rescaled or not.
  73514. */
  73515. get: function () {
  73516. return true;
  73517. },
  73518. enumerable: true,
  73519. configurable: true
  73520. });
  73521. /**
  73522. * Resize the texture using a ratio.
  73523. * @param ratio the ratio to apply to the texture size in order to compute the new target size
  73524. */
  73525. RenderTargetTexture.prototype.scale = function (ratio) {
  73526. var newSize = this.getRenderSize() * ratio;
  73527. this.resize(newSize);
  73528. };
  73529. /**
  73530. * Get the texture reflection matrix used to rotate/transform the reflection.
  73531. * @returns the reflection matrix
  73532. */
  73533. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  73534. if (this.isCube) {
  73535. return this._textureMatrix;
  73536. }
  73537. return _super.prototype.getReflectionTextureMatrix.call(this);
  73538. };
  73539. /**
  73540. * Resize the texture to a new desired size.
  73541. * Be carrefull as it will recreate all the data in the new texture.
  73542. * @param size Define the new size. It can be:
  73543. * - a number for squared texture,
  73544. * - an object containing { width: number, height: number }
  73545. * - or an object containing a ratio { ratio: number }
  73546. */
  73547. RenderTargetTexture.prototype.resize = function (size) {
  73548. this.releaseInternalTexture();
  73549. var scene = this.getScene();
  73550. if (!scene) {
  73551. return;
  73552. }
  73553. this._processSizeParameter(size);
  73554. if (this.isCube) {
  73555. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  73556. }
  73557. else {
  73558. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  73559. }
  73560. };
  73561. /**
  73562. * Renders all the objects from the render list into the texture.
  73563. * @param useCameraPostProcess Define if camera post processes should be used during the rendering
  73564. * @param dumpForDebug Define if the rendering result should be dumped (copied) for debugging purpose
  73565. */
  73566. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  73567. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  73568. if (dumpForDebug === void 0) { dumpForDebug = false; }
  73569. var scene = this.getScene();
  73570. if (!scene) {
  73571. return;
  73572. }
  73573. var engine = scene.getEngine();
  73574. if (this.useCameraPostProcesses !== undefined) {
  73575. useCameraPostProcess = this.useCameraPostProcesses;
  73576. }
  73577. if (this._waitingRenderList) {
  73578. this.renderList = [];
  73579. for (var index = 0; index < this._waitingRenderList.length; index++) {
  73580. var id = this._waitingRenderList[index];
  73581. var mesh_1 = scene.getMeshByID(id);
  73582. if (mesh_1) {
  73583. this.renderList.push(mesh_1);
  73584. }
  73585. }
  73586. delete this._waitingRenderList;
  73587. }
  73588. // Is predicate defined?
  73589. if (this.renderListPredicate) {
  73590. if (this.renderList) {
  73591. this.renderList.length = 0; // Clear previous renderList
  73592. }
  73593. else {
  73594. this.renderList = [];
  73595. }
  73596. var scene = this.getScene();
  73597. if (!scene) {
  73598. return;
  73599. }
  73600. var sceneMeshes = scene.meshes;
  73601. for (var index = 0; index < sceneMeshes.length; index++) {
  73602. var mesh = sceneMeshes[index];
  73603. if (this.renderListPredicate(mesh)) {
  73604. this.renderList.push(mesh);
  73605. }
  73606. }
  73607. }
  73608. this.onBeforeBindObservable.notifyObservers(this);
  73609. // Set custom projection.
  73610. // Needs to be before binding to prevent changing the aspect ratio.
  73611. var camera;
  73612. if (this.activeCamera) {
  73613. camera = this.activeCamera;
  73614. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  73615. if (this.activeCamera !== scene.activeCamera) {
  73616. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  73617. }
  73618. }
  73619. else {
  73620. camera = scene.activeCamera;
  73621. if (camera) {
  73622. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  73623. }
  73624. }
  73625. // Prepare renderingManager
  73626. this._renderingManager.reset();
  73627. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  73628. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  73629. var sceneRenderId = scene.getRenderId();
  73630. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  73631. var mesh = currentRenderList[meshIndex];
  73632. if (mesh) {
  73633. if (!mesh.isReady(this.refreshRate === 0)) {
  73634. this.resetRefreshCounter();
  73635. continue;
  73636. }
  73637. mesh._preActivateForIntermediateRendering(sceneRenderId);
  73638. var isMasked = void 0;
  73639. if (!this.renderList && camera) {
  73640. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  73641. }
  73642. else {
  73643. isMasked = false;
  73644. }
  73645. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  73646. mesh._activate(sceneRenderId);
  73647. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  73648. var subMesh = mesh.subMeshes[subIndex];
  73649. scene._activeIndices.addCount(subMesh.indexCount, false);
  73650. this._renderingManager.dispatch(subMesh, mesh);
  73651. }
  73652. }
  73653. }
  73654. }
  73655. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  73656. var particleSystem = scene.particleSystems[particleIndex];
  73657. var emitter = particleSystem.emitter;
  73658. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  73659. continue;
  73660. }
  73661. if (currentRenderList.indexOf(emitter) >= 0) {
  73662. this._renderingManager.dispatchParticles(particleSystem);
  73663. }
  73664. }
  73665. if (this.isCube) {
  73666. for (var face = 0; face < 6; face++) {
  73667. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  73668. scene.incrementRenderId();
  73669. scene.resetCachedMaterial();
  73670. }
  73671. }
  73672. else {
  73673. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  73674. }
  73675. this.onAfterUnbindObservable.notifyObservers(this);
  73676. if (scene.activeCamera) {
  73677. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  73678. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  73679. }
  73680. engine.setViewport(scene.activeCamera.viewport);
  73681. }
  73682. scene.resetCachedMaterial();
  73683. };
  73684. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  73685. var minimum = 128;
  73686. var x = renderDimension * scale;
  73687. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  73688. // Ensure we don't exceed the render dimension (while staying POT)
  73689. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  73690. };
  73691. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  73692. var _this = this;
  73693. if (!this._texture) {
  73694. return;
  73695. }
  73696. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  73697. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  73698. });
  73699. };
  73700. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  73701. var scene = this.getScene();
  73702. if (!scene) {
  73703. return;
  73704. }
  73705. var engine = scene.getEngine();
  73706. if (!this._texture) {
  73707. return;
  73708. }
  73709. // Bind
  73710. if (this._postProcessManager) {
  73711. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  73712. }
  73713. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  73714. if (this._texture) {
  73715. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  73716. }
  73717. }
  73718. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  73719. // Clear
  73720. if (this.onClearObservable.hasObservers()) {
  73721. this.onClearObservable.notifyObservers(engine);
  73722. }
  73723. else {
  73724. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  73725. }
  73726. if (!this._doNotChangeAspectRatio) {
  73727. scene.updateTransformMatrix(true);
  73728. }
  73729. // Render
  73730. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  73731. if (this._postProcessManager) {
  73732. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  73733. }
  73734. else if (useCameraPostProcess) {
  73735. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  73736. }
  73737. if (!this._doNotChangeAspectRatio) {
  73738. scene.updateTransformMatrix(true);
  73739. }
  73740. // Dump ?
  73741. if (dumpForDebug) {
  73742. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  73743. }
  73744. // Unbind
  73745. if (!this.isCube || faceIndex === 5) {
  73746. if (this.isCube) {
  73747. if (faceIndex === 5) {
  73748. engine.generateMipMapsForCubemap(this._texture);
  73749. }
  73750. }
  73751. this.unbindFrameBuffer(engine, faceIndex);
  73752. }
  73753. else {
  73754. this.onAfterRenderObservable.notifyObservers(faceIndex);
  73755. }
  73756. };
  73757. /**
  73758. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  73759. * This allowed control for front to back rendering or reversly depending of the special needs.
  73760. *
  73761. * @param renderingGroupId The rendering group id corresponding to its index
  73762. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  73763. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  73764. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  73765. */
  73766. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  73767. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  73768. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  73769. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  73770. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  73771. };
  73772. /**
  73773. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  73774. *
  73775. * @param renderingGroupId The rendering group id corresponding to its index
  73776. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  73777. */
  73778. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  73779. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  73780. this._renderingManager._useSceneAutoClearSetup = false;
  73781. };
  73782. /**
  73783. * Clones the texture.
  73784. * @returns the cloned texture
  73785. */
  73786. RenderTargetTexture.prototype.clone = function () {
  73787. var textureSize = this.getSize();
  73788. 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);
  73789. // Base texture
  73790. newTexture.hasAlpha = this.hasAlpha;
  73791. newTexture.level = this.level;
  73792. // RenderTarget Texture
  73793. newTexture.coordinatesMode = this.coordinatesMode;
  73794. if (this.renderList) {
  73795. newTexture.renderList = this.renderList.slice(0);
  73796. }
  73797. return newTexture;
  73798. };
  73799. /**
  73800. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  73801. * @returns The JSON representation of the texture
  73802. */
  73803. RenderTargetTexture.prototype.serialize = function () {
  73804. if (!this.name) {
  73805. return null;
  73806. }
  73807. var serializationObject = _super.prototype.serialize.call(this);
  73808. serializationObject.renderTargetSize = this.getRenderSize();
  73809. serializationObject.renderList = [];
  73810. if (this.renderList) {
  73811. for (var index = 0; index < this.renderList.length; index++) {
  73812. serializationObject.renderList.push(this.renderList[index].id);
  73813. }
  73814. }
  73815. return serializationObject;
  73816. };
  73817. /**
  73818. * This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  73819. */
  73820. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  73821. var objBuffer = this.getInternalTexture();
  73822. var scene = this.getScene();
  73823. if (objBuffer && scene) {
  73824. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  73825. }
  73826. };
  73827. /**
  73828. * Dispose the texture and release its associated resources.
  73829. */
  73830. RenderTargetTexture.prototype.dispose = function () {
  73831. if (this._postProcessManager) {
  73832. this._postProcessManager.dispose();
  73833. this._postProcessManager = null;
  73834. }
  73835. this.clearPostProcesses(true);
  73836. if (this._resizeObserver) {
  73837. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  73838. this._resizeObserver = null;
  73839. }
  73840. this.renderList = null;
  73841. // Remove from custom render targets
  73842. var scene = this.getScene();
  73843. if (!scene) {
  73844. return;
  73845. }
  73846. var index = scene.customRenderTargets.indexOf(this);
  73847. if (index >= 0) {
  73848. scene.customRenderTargets.splice(index, 1);
  73849. }
  73850. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  73851. var camera = _a[_i];
  73852. index = camera.customRenderTargets.indexOf(this);
  73853. if (index >= 0) {
  73854. camera.customRenderTargets.splice(index, 1);
  73855. }
  73856. }
  73857. _super.prototype.dispose.call(this);
  73858. };
  73859. /** @hidden */
  73860. RenderTargetTexture.prototype._rebuild = function () {
  73861. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  73862. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  73863. }
  73864. if (this._postProcessManager) {
  73865. this._postProcessManager._rebuild();
  73866. }
  73867. };
  73868. /**
  73869. * Clear the info related to rendering groups preventing retention point in material dispose.
  73870. */
  73871. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  73872. if (this._renderingManager) {
  73873. this._renderingManager.freeRenderingGroups();
  73874. }
  73875. };
  73876. /**
  73877. * The texture will only be rendered once which can be useful to improve performance if everything in your render is static for instance.
  73878. */
  73879. RenderTargetTexture.REFRESHRATE_RENDER_ONCE = 0;
  73880. /**
  73881. * The texture will only be rendered rendered every frame and is recomended for dynamic contents.
  73882. */
  73883. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  73884. /**
  73885. * The texture will be rendered every 2 frames which could be enough if your dynamic objects are not
  73886. * the central point of your effect and can save a lot of performances.
  73887. */
  73888. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  73889. return RenderTargetTexture;
  73890. }(BABYLON.Texture));
  73891. BABYLON.RenderTargetTexture = RenderTargetTexture;
  73892. })(BABYLON || (BABYLON = {}));
  73893. //# sourceMappingURL=renderTargetTexture.js.map
  73894. var BABYLON;
  73895. (function (BABYLON) {
  73896. /**
  73897. * A multi render target, like a render target provides the ability to render to a texture.
  73898. * Unlike the render target, it can render to several draw buffers in one draw.
  73899. * This is specially interesting in deferred rendering or for any effects requiring more than
  73900. * just one color from a single pass.
  73901. */
  73902. var MultiRenderTarget = /** @class */ (function (_super) {
  73903. __extends(MultiRenderTarget, _super);
  73904. /**
  73905. * Instantiate a new multi render target texture.
  73906. * A multi render target, like a render target provides the ability to render to a texture.
  73907. * Unlike the render target, it can render to several draw buffers in one draw.
  73908. * This is specially interesting in deferred rendering or for any effects requiring more than
  73909. * just one color from a single pass.
  73910. * @param name Define the name of the texture
  73911. * @param size Define the size of the buffers to render to
  73912. * @param count Define the number of target we are rendering into
  73913. * @param scene Define the scene the texture belongs to
  73914. * @param options Define the options used to create the multi render target
  73915. */
  73916. function MultiRenderTarget(name, size, count, scene, options) {
  73917. var _this = this;
  73918. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  73919. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  73920. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  73921. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  73922. _this._engine = scene.getEngine();
  73923. if (!_this.isSupported) {
  73924. _this.dispose();
  73925. return;
  73926. }
  73927. var types = [];
  73928. var samplingModes = [];
  73929. for (var i = 0; i < count; i++) {
  73930. if (options && options.types && options.types[i] !== undefined) {
  73931. types.push(options.types[i]);
  73932. }
  73933. else {
  73934. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73935. }
  73936. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  73937. samplingModes.push(options.samplingModes[i]);
  73938. }
  73939. else {
  73940. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73941. }
  73942. }
  73943. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  73944. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  73945. _this._size = size;
  73946. _this._multiRenderTargetOptions = {
  73947. samplingModes: samplingModes,
  73948. generateMipMaps: generateMipMaps,
  73949. generateDepthBuffer: generateDepthBuffer,
  73950. generateStencilBuffer: generateStencilBuffer,
  73951. generateDepthTexture: generateDepthTexture,
  73952. types: types,
  73953. textureCount: count
  73954. };
  73955. _this._createInternalTextures();
  73956. _this._createTextures();
  73957. return _this;
  73958. }
  73959. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  73960. /**
  73961. * Get if draw buffers are currently supported by the used hardware and browser.
  73962. */
  73963. get: function () {
  73964. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  73965. },
  73966. enumerable: true,
  73967. configurable: true
  73968. });
  73969. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  73970. /**
  73971. * Get the list of textures generated by the multi render target.
  73972. */
  73973. get: function () {
  73974. return this._textures;
  73975. },
  73976. enumerable: true,
  73977. configurable: true
  73978. });
  73979. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  73980. /**
  73981. * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set
  73982. */
  73983. get: function () {
  73984. return this._textures[this._textures.length - 1];
  73985. },
  73986. enumerable: true,
  73987. configurable: true
  73988. });
  73989. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  73990. /**
  73991. * Set the wrapping mode on U of all the textures we are rendering to.
  73992. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  73993. */
  73994. set: function (wrap) {
  73995. if (this._textures) {
  73996. for (var i = 0; i < this._textures.length; i++) {
  73997. this._textures[i].wrapU = wrap;
  73998. }
  73999. }
  74000. },
  74001. enumerable: true,
  74002. configurable: true
  74003. });
  74004. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  74005. /**
  74006. * Set the wrapping mode on V of all the textures we are rendering to.
  74007. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  74008. */
  74009. set: function (wrap) {
  74010. if (this._textures) {
  74011. for (var i = 0; i < this._textures.length; i++) {
  74012. this._textures[i].wrapV = wrap;
  74013. }
  74014. }
  74015. },
  74016. enumerable: true,
  74017. configurable: true
  74018. });
  74019. /** @hidden */
  74020. MultiRenderTarget.prototype._rebuild = function () {
  74021. this.releaseInternalTextures();
  74022. this._createInternalTextures();
  74023. for (var i = 0; i < this._internalTextures.length; i++) {
  74024. var texture = this._textures[i];
  74025. texture._texture = this._internalTextures[i];
  74026. }
  74027. // Keeps references to frame buffer and stencil/depth buffer
  74028. this._texture = this._internalTextures[0];
  74029. };
  74030. MultiRenderTarget.prototype._createInternalTextures = function () {
  74031. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  74032. };
  74033. MultiRenderTarget.prototype._createTextures = function () {
  74034. this._textures = [];
  74035. for (var i = 0; i < this._internalTextures.length; i++) {
  74036. var texture = new BABYLON.Texture(null, this.getScene());
  74037. texture._texture = this._internalTextures[i];
  74038. this._textures.push(texture);
  74039. }
  74040. // Keeps references to frame buffer and stencil/depth buffer
  74041. this._texture = this._internalTextures[0];
  74042. };
  74043. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  74044. /**
  74045. * Define the number of samples used if MSAA is enabled.
  74046. */
  74047. get: function () {
  74048. return this._samples;
  74049. },
  74050. set: function (value) {
  74051. if (this._samples === value) {
  74052. return;
  74053. }
  74054. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  74055. },
  74056. enumerable: true,
  74057. configurable: true
  74058. });
  74059. /**
  74060. * Resize all the textures in the multi render target.
  74061. * Be carrefull as it will recreate all the data in the new texture.
  74062. * @param size Define the new size
  74063. */
  74064. MultiRenderTarget.prototype.resize = function (size) {
  74065. this.releaseInternalTextures();
  74066. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  74067. this._createInternalTextures();
  74068. };
  74069. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  74070. var _this = this;
  74071. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  74072. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  74073. });
  74074. };
  74075. /**
  74076. * Dispose the render targets and their associated resources
  74077. */
  74078. MultiRenderTarget.prototype.dispose = function () {
  74079. this.releaseInternalTextures();
  74080. _super.prototype.dispose.call(this);
  74081. };
  74082. /**
  74083. * Release all the underlying texture used as draw buffers.
  74084. */
  74085. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  74086. if (!this._internalTextures) {
  74087. return;
  74088. }
  74089. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  74090. if (this._internalTextures[i] !== undefined) {
  74091. this._internalTextures[i].dispose();
  74092. this._internalTextures.splice(i, 1);
  74093. }
  74094. }
  74095. };
  74096. return MultiRenderTarget;
  74097. }(BABYLON.RenderTargetTexture));
  74098. BABYLON.MultiRenderTarget = MultiRenderTarget;
  74099. })(BABYLON || (BABYLON = {}));
  74100. //# sourceMappingURL=multiRenderTarget.js.map
  74101. var BABYLON;
  74102. (function (BABYLON) {
  74103. /**
  74104. * Mirror texture can be used to simulate the view from a mirror in a scene.
  74105. * It will dynamically be rendered every frame to adapt to the camera point of view.
  74106. * You can then easily use it as a reflectionTexture on a flat surface.
  74107. * In case the surface is not a plane, please consider relying on reflection probes.
  74108. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  74109. */
  74110. var MirrorTexture = /** @class */ (function (_super) {
  74111. __extends(MirrorTexture, _super);
  74112. /**
  74113. * Instantiates a Mirror Texture.
  74114. * Mirror texture can be used to simulate the view from a mirror in a scene.
  74115. * It will dynamically be rendered every frame to adapt to the camera point of view.
  74116. * You can then easily use it as a reflectionTexture on a flat surface.
  74117. * In case the surface is not a plane, please consider relying on reflection probes.
  74118. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  74119. * @param name
  74120. * @param size
  74121. * @param scene
  74122. * @param generateMipMaps
  74123. * @param type
  74124. * @param samplingMode
  74125. * @param generateDepthBuffer
  74126. */
  74127. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  74128. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74129. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74130. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  74131. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  74132. _this.scene = scene;
  74133. /**
  74134. * Define the reflection plane we want to use. The mirrorPlane is usually set to the constructed reflector.
  74135. * It is possible to directly set the mirrorPlane by directly using a BABYLON.Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the mirrorPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the reflector as stated in the doc.
  74136. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  74137. */
  74138. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  74139. _this._transformMatrix = BABYLON.Matrix.Zero();
  74140. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  74141. _this._adaptiveBlurKernel = 0;
  74142. _this._blurKernelX = 0;
  74143. _this._blurKernelY = 0;
  74144. _this._blurRatio = 1.0;
  74145. _this.ignoreCameraViewport = true;
  74146. _this._updateGammaSpace();
  74147. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  74148. _this._updateGammaSpace;
  74149. });
  74150. _this.onBeforeRenderObservable.add(function () {
  74151. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  74152. _this._savedViewMatrix = scene.getViewMatrix();
  74153. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  74154. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  74155. scene.clipPlane = _this.mirrorPlane;
  74156. scene.getEngine().cullBackFaces = false;
  74157. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  74158. });
  74159. _this.onAfterRenderObservable.add(function () {
  74160. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  74161. scene.getEngine().cullBackFaces = true;
  74162. scene._mirroredCameraPosition = null;
  74163. delete scene.clipPlane;
  74164. });
  74165. return _this;
  74166. }
  74167. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  74168. get: function () {
  74169. return this._blurRatio;
  74170. },
  74171. /**
  74172. * Define the blur ratio used to blur the reflection if needed.
  74173. */
  74174. set: function (value) {
  74175. if (this._blurRatio === value) {
  74176. return;
  74177. }
  74178. this._blurRatio = value;
  74179. this._preparePostProcesses();
  74180. },
  74181. enumerable: true,
  74182. configurable: true
  74183. });
  74184. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  74185. /**
  74186. * Define the adaptive blur kernel used to blur the reflection if needed.
  74187. * This will autocompute the closest best match for the `blurKernel`
  74188. */
  74189. set: function (value) {
  74190. this._adaptiveBlurKernel = value;
  74191. this._autoComputeBlurKernel();
  74192. },
  74193. enumerable: true,
  74194. configurable: true
  74195. });
  74196. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  74197. /**
  74198. * Define the blur kernel used to blur the reflection if needed.
  74199. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  74200. */
  74201. set: function (value) {
  74202. this.blurKernelX = value;
  74203. this.blurKernelY = value;
  74204. },
  74205. enumerable: true,
  74206. configurable: true
  74207. });
  74208. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  74209. get: function () {
  74210. return this._blurKernelX;
  74211. },
  74212. /**
  74213. * Define the blur kernel on the X Axis used to blur the reflection if needed.
  74214. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  74215. */
  74216. set: function (value) {
  74217. if (this._blurKernelX === value) {
  74218. return;
  74219. }
  74220. this._blurKernelX = value;
  74221. this._preparePostProcesses();
  74222. },
  74223. enumerable: true,
  74224. configurable: true
  74225. });
  74226. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  74227. get: function () {
  74228. return this._blurKernelY;
  74229. },
  74230. /**
  74231. * Define the blur kernel on the Y Axis used to blur the reflection if needed.
  74232. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  74233. */
  74234. set: function (value) {
  74235. if (this._blurKernelY === value) {
  74236. return;
  74237. }
  74238. this._blurKernelY = value;
  74239. this._preparePostProcesses();
  74240. },
  74241. enumerable: true,
  74242. configurable: true
  74243. });
  74244. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  74245. var engine = this.getScene().getEngine();
  74246. var dw = this.getRenderWidth() / engine.getRenderWidth();
  74247. var dh = this.getRenderHeight() / engine.getRenderHeight();
  74248. this.blurKernelX = this._adaptiveBlurKernel * dw;
  74249. this.blurKernelY = this._adaptiveBlurKernel * dh;
  74250. };
  74251. MirrorTexture.prototype._onRatioRescale = function () {
  74252. if (this._sizeRatio) {
  74253. this.resize(this._initialSizeParameter);
  74254. if (!this._adaptiveBlurKernel) {
  74255. this._preparePostProcesses();
  74256. }
  74257. }
  74258. if (this._adaptiveBlurKernel) {
  74259. this._autoComputeBlurKernel();
  74260. }
  74261. };
  74262. MirrorTexture.prototype._updateGammaSpace = function () {
  74263. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  74264. };
  74265. MirrorTexture.prototype._preparePostProcesses = function () {
  74266. this.clearPostProcesses(true);
  74267. if (this._blurKernelX && this._blurKernelY) {
  74268. var engine = this.getScene().getEngine();
  74269. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74270. 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);
  74271. this._blurX.autoClear = false;
  74272. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  74273. this._blurX.inputTexture = this._texture;
  74274. }
  74275. else {
  74276. this._blurX.alwaysForcePOT = true;
  74277. }
  74278. 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);
  74279. this._blurY.autoClear = false;
  74280. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  74281. this.addPostProcess(this._blurX);
  74282. this.addPostProcess(this._blurY);
  74283. }
  74284. else {
  74285. if (this._blurY) {
  74286. this.removePostProcess(this._blurY);
  74287. this._blurY.dispose();
  74288. this._blurY = null;
  74289. }
  74290. if (this._blurX) {
  74291. this.removePostProcess(this._blurX);
  74292. this._blurX.dispose();
  74293. this._blurX = null;
  74294. }
  74295. }
  74296. };
  74297. /**
  74298. * Clone the mirror texture.
  74299. * @returns the cloned texture
  74300. */
  74301. MirrorTexture.prototype.clone = function () {
  74302. var scene = this.getScene();
  74303. if (!scene) {
  74304. return this;
  74305. }
  74306. var textureSize = this.getSize();
  74307. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  74308. // Base texture
  74309. newTexture.hasAlpha = this.hasAlpha;
  74310. newTexture.level = this.level;
  74311. // Mirror Texture
  74312. newTexture.mirrorPlane = this.mirrorPlane.clone();
  74313. if (this.renderList) {
  74314. newTexture.renderList = this.renderList.slice(0);
  74315. }
  74316. return newTexture;
  74317. };
  74318. /**
  74319. * Serialize the texture to a JSON representation you could use in Parse later on
  74320. * @returns the serialized JSON representation
  74321. */
  74322. MirrorTexture.prototype.serialize = function () {
  74323. if (!this.name) {
  74324. return null;
  74325. }
  74326. var serializationObject = _super.prototype.serialize.call(this);
  74327. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  74328. return serializationObject;
  74329. };
  74330. /**
  74331. * Dispose the texture and release its associated resources.
  74332. */
  74333. MirrorTexture.prototype.dispose = function () {
  74334. _super.prototype.dispose.call(this);
  74335. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  74336. };
  74337. return MirrorTexture;
  74338. }(BABYLON.RenderTargetTexture));
  74339. BABYLON.MirrorTexture = MirrorTexture;
  74340. })(BABYLON || (BABYLON = {}));
  74341. //# sourceMappingURL=mirrorTexture.js.map
  74342. var BABYLON;
  74343. (function (BABYLON) {
  74344. /**
  74345. * Creates a refraction texture used by refraction channel of the standard material.
  74346. * It is like a mirror but to see through a material.
  74347. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  74348. */
  74349. var RefractionTexture = /** @class */ (function (_super) {
  74350. __extends(RefractionTexture, _super);
  74351. /**
  74352. * Creates a refraction texture used by refraction channel of the standard material.
  74353. * It is like a mirror but to see through a material.
  74354. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  74355. * @param name Define the texture name
  74356. * @param size Define the size of the underlying texture
  74357. * @param scene Define the scene the refraction belongs to
  74358. * @param generateMipMaps Define if we need to generate mips level for the refraction
  74359. */
  74360. function RefractionTexture(name, size, scene, generateMipMaps) {
  74361. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  74362. /**
  74363. * Define the reflection plane we want to use. The refractionPlane is usually set to the constructed refractor.
  74364. * It is possible to directly set the refractionPlane by directly using a BABYLON.Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the refractionPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the refractor as stated in the doc.
  74365. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  74366. */
  74367. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  74368. /**
  74369. * Define how deep under the surface we should see.
  74370. */
  74371. _this.depth = 2.0;
  74372. _this.onBeforeRenderObservable.add(function () {
  74373. scene.clipPlane = _this.refractionPlane;
  74374. });
  74375. _this.onAfterRenderObservable.add(function () {
  74376. delete scene.clipPlane;
  74377. });
  74378. return _this;
  74379. }
  74380. /**
  74381. * Clone the refraction texture.
  74382. * @returns the cloned texture
  74383. */
  74384. RefractionTexture.prototype.clone = function () {
  74385. var scene = this.getScene();
  74386. if (!scene) {
  74387. return this;
  74388. }
  74389. var textureSize = this.getSize();
  74390. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  74391. // Base texture
  74392. newTexture.hasAlpha = this.hasAlpha;
  74393. newTexture.level = this.level;
  74394. // Refraction Texture
  74395. newTexture.refractionPlane = this.refractionPlane.clone();
  74396. if (this.renderList) {
  74397. newTexture.renderList = this.renderList.slice(0);
  74398. }
  74399. newTexture.depth = this.depth;
  74400. return newTexture;
  74401. };
  74402. /**
  74403. * Serialize the texture to a JSON representation you could use in Parse later on
  74404. * @returns the serialized JSON representation
  74405. */
  74406. RefractionTexture.prototype.serialize = function () {
  74407. if (!this.name) {
  74408. return null;
  74409. }
  74410. var serializationObject = _super.prototype.serialize.call(this);
  74411. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  74412. serializationObject.depth = this.depth;
  74413. return serializationObject;
  74414. };
  74415. return RefractionTexture;
  74416. }(BABYLON.RenderTargetTexture));
  74417. BABYLON.RefractionTexture = RefractionTexture;
  74418. })(BABYLON || (BABYLON = {}));
  74419. //# sourceMappingURL=refractionTexture.js.map
  74420. var BABYLON;
  74421. (function (BABYLON) {
  74422. /**
  74423. * A class extending Texture allowing drawing on a texture
  74424. * @see http://doc.babylonjs.com/how_to/dynamictexture
  74425. */
  74426. var DynamicTexture = /** @class */ (function (_super) {
  74427. __extends(DynamicTexture, _super);
  74428. /**
  74429. * Creates a DynamicTexture
  74430. * @param name defines the name of the texture
  74431. * @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
  74432. * @param scene defines the scene where you want the texture
  74433. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  74434. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  74435. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  74436. */
  74437. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  74438. if (scene === void 0) { scene = null; }
  74439. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74440. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  74441. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  74442. _this.name = name;
  74443. _this._engine = _this.getScene().getEngine();
  74444. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74445. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74446. _this._generateMipMaps = generateMipMaps;
  74447. if (options.getContext) {
  74448. _this._canvas = options;
  74449. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  74450. }
  74451. else {
  74452. _this._canvas = document.createElement("canvas");
  74453. if (options.width || options.width === 0) {
  74454. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  74455. }
  74456. else {
  74457. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  74458. }
  74459. }
  74460. var textureSize = _this.getSize();
  74461. _this._canvas.width = textureSize.width;
  74462. _this._canvas.height = textureSize.height;
  74463. _this._context = _this._canvas.getContext("2d");
  74464. return _this;
  74465. }
  74466. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  74467. /**
  74468. * Gets the current state of canRescale
  74469. */
  74470. get: function () {
  74471. return true;
  74472. },
  74473. enumerable: true,
  74474. configurable: true
  74475. });
  74476. DynamicTexture.prototype._recreate = function (textureSize) {
  74477. this._canvas.width = textureSize.width;
  74478. this._canvas.height = textureSize.height;
  74479. this.releaseInternalTexture();
  74480. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  74481. };
  74482. /**
  74483. * Scales the texture
  74484. * @param ratio the scale factor to apply to both width and height
  74485. */
  74486. DynamicTexture.prototype.scale = function (ratio) {
  74487. var textureSize = this.getSize();
  74488. textureSize.width *= ratio;
  74489. textureSize.height *= ratio;
  74490. this._recreate(textureSize);
  74491. };
  74492. /**
  74493. * Resizes the texture
  74494. * @param width the new width
  74495. * @param height the new height
  74496. */
  74497. DynamicTexture.prototype.scaleTo = function (width, height) {
  74498. var textureSize = this.getSize();
  74499. textureSize.width = width;
  74500. textureSize.height = height;
  74501. this._recreate(textureSize);
  74502. };
  74503. /**
  74504. * Gets the context of the canvas used by the texture
  74505. * @returns the canvas context of the dynamic texture
  74506. */
  74507. DynamicTexture.prototype.getContext = function () {
  74508. return this._context;
  74509. };
  74510. /**
  74511. * Clears the texture
  74512. */
  74513. DynamicTexture.prototype.clear = function () {
  74514. var size = this.getSize();
  74515. this._context.fillRect(0, 0, size.width, size.height);
  74516. };
  74517. /**
  74518. * Updates the texture
  74519. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  74520. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  74521. */
  74522. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  74523. if (premulAlpha === void 0) { premulAlpha = false; }
  74524. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  74525. };
  74526. /**
  74527. * Draws text onto the texture
  74528. * @param text defines the text to be drawn
  74529. * @param x defines the placement of the text from the left
  74530. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  74531. * @param font defines the font to be used with font-style, font-size, font-name
  74532. * @param color defines the color used for the text
  74533. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  74534. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  74535. * @param update defines whether texture is immediately update (default is true)
  74536. */
  74537. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  74538. if (update === void 0) { update = true; }
  74539. var size = this.getSize();
  74540. if (clearColor) {
  74541. this._context.fillStyle = clearColor;
  74542. this._context.fillRect(0, 0, size.width, size.height);
  74543. }
  74544. this._context.font = font;
  74545. if (x === null || x === undefined) {
  74546. var textSize = this._context.measureText(text);
  74547. x = (size.width - textSize.width) / 2;
  74548. }
  74549. if (y === null || y === undefined) {
  74550. var fontSize = parseInt((font.replace(/\D/g, '')));
  74551. y = (size.height / 2) + (fontSize / 3.65);
  74552. }
  74553. this._context.fillStyle = color;
  74554. this._context.fillText(text, x, y);
  74555. if (update) {
  74556. this.update(invertY);
  74557. }
  74558. };
  74559. /**
  74560. * Clones the texture
  74561. * @returns the clone of the texture.
  74562. */
  74563. DynamicTexture.prototype.clone = function () {
  74564. var scene = this.getScene();
  74565. if (!scene) {
  74566. return this;
  74567. }
  74568. var textureSize = this.getSize();
  74569. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  74570. // Base texture
  74571. newTexture.hasAlpha = this.hasAlpha;
  74572. newTexture.level = this.level;
  74573. // Dynamic Texture
  74574. newTexture.wrapU = this.wrapU;
  74575. newTexture.wrapV = this.wrapV;
  74576. return newTexture;
  74577. };
  74578. /**
  74579. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  74580. * @returns a serialized dynamic texture object
  74581. */
  74582. DynamicTexture.prototype.serialize = function () {
  74583. var scene = this.getScene();
  74584. if (scene && !scene.isReady()) {
  74585. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  74586. }
  74587. var serializationObject = _super.prototype.serialize.call(this);
  74588. serializationObject.base64String = this._canvas.toDataURL();
  74589. serializationObject.invertY = this._invertY;
  74590. serializationObject.samplingMode = this.samplingMode;
  74591. return serializationObject;
  74592. };
  74593. /** @hidden */
  74594. DynamicTexture.prototype._rebuild = function () {
  74595. this.update();
  74596. };
  74597. return DynamicTexture;
  74598. }(BABYLON.Texture));
  74599. BABYLON.DynamicTexture = DynamicTexture;
  74600. })(BABYLON || (BABYLON = {}));
  74601. //# sourceMappingURL=dynamicTexture.js.map
  74602. var BABYLON;
  74603. (function (BABYLON) {
  74604. /**
  74605. * If you want to display a video in your scene, this is the special texture for that.
  74606. * This special texture works similar to other textures, with the exception of a few parameters.
  74607. * @see https://doc.babylonjs.com/how_to/video_texture
  74608. */
  74609. var VideoTexture = /** @class */ (function (_super) {
  74610. __extends(VideoTexture, _super);
  74611. /**
  74612. * Creates a video texture.
  74613. * If you want to display a video in your scene, this is the special texture for that.
  74614. * This special texture works similar to other textures, with the exception of a few parameters.
  74615. * @see https://doc.babylonjs.com/how_to/video_texture
  74616. * @param name optional name, will detect from video source, if not defined
  74617. * @param src can be used to provide an url, array of urls or an already setup HTML video element.
  74618. * @param scene is obviously the current scene.
  74619. * @param generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  74620. * @param invertY is false by default but can be used to invert video on Y axis
  74621. * @param samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  74622. * @param settings allows finer control over video usage
  74623. */
  74624. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  74625. if (generateMipMaps === void 0) { generateMipMaps = false; }
  74626. if (invertY === void 0) { invertY = false; }
  74627. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74628. if (settings === void 0) { settings = {
  74629. autoPlay: true,
  74630. loop: true,
  74631. autoUpdateTexture: true,
  74632. }; }
  74633. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  74634. _this._onUserActionRequestedObservable = null;
  74635. _this._stillImageCaptured = false;
  74636. _this._poster = false;
  74637. _this._createInternalTexture = function () {
  74638. if (_this._texture != null) {
  74639. if (_this._poster) {
  74640. _this._texture.dispose();
  74641. _this._poster = false;
  74642. }
  74643. else {
  74644. return;
  74645. }
  74646. }
  74647. if (!_this._engine.needPOTTextures ||
  74648. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  74649. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74650. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74651. }
  74652. else {
  74653. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74654. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74655. _this._generateMipMaps = false;
  74656. }
  74657. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  74658. if (!_this.video.autoplay) {
  74659. var oldHandler_1 = _this.video.onplaying;
  74660. var error_1 = false;
  74661. _this.video.onplaying = function () {
  74662. _this.video.onplaying = oldHandler_1;
  74663. _this._texture.isReady = true;
  74664. _this._updateInternalTexture();
  74665. if (!error_1) {
  74666. _this.video.pause();
  74667. }
  74668. if (_this.onLoadObservable.hasObservers()) {
  74669. _this.onLoadObservable.notifyObservers(_this);
  74670. }
  74671. };
  74672. var playing = _this.video.play();
  74673. if (playing) {
  74674. playing.then(function () {
  74675. // Everything is good.
  74676. })
  74677. .catch(function () {
  74678. error_1 = true;
  74679. // On Chrome for instance, new policies might prevent playing without user interaction.
  74680. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  74681. _this._onUserActionRequestedObservable.notifyObservers(_this);
  74682. }
  74683. });
  74684. }
  74685. else {
  74686. _this.video.onplaying = oldHandler_1;
  74687. _this._texture.isReady = true;
  74688. _this._updateInternalTexture();
  74689. if (_this.onLoadObservable.hasObservers()) {
  74690. _this.onLoadObservable.notifyObservers(_this);
  74691. }
  74692. }
  74693. }
  74694. else {
  74695. _this._texture.isReady = true;
  74696. _this._updateInternalTexture();
  74697. if (_this.onLoadObservable.hasObservers()) {
  74698. _this.onLoadObservable.notifyObservers(_this);
  74699. }
  74700. }
  74701. };
  74702. _this.reset = function () {
  74703. if (_this._texture == null) {
  74704. return;
  74705. }
  74706. if (!_this._poster) {
  74707. _this._texture.dispose();
  74708. _this._texture = null;
  74709. }
  74710. };
  74711. _this._updateInternalTexture = function (e) {
  74712. if (_this._texture == null || !_this._texture.isReady) {
  74713. return;
  74714. }
  74715. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  74716. return;
  74717. }
  74718. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  74719. };
  74720. _this._engine = _this.getScene().getEngine();
  74721. _this._generateMipMaps = generateMipMaps;
  74722. _this._samplingMode = samplingMode;
  74723. _this.autoUpdateTexture = settings.autoUpdateTexture;
  74724. _this.name = name || _this._getName(src);
  74725. _this.video = _this._getVideo(src);
  74726. if (settings.poster) {
  74727. _this.video.poster = settings.poster;
  74728. }
  74729. if (settings.autoPlay !== undefined) {
  74730. _this.video.autoplay = settings.autoPlay;
  74731. }
  74732. if (settings.loop !== undefined) {
  74733. _this.video.loop = settings.loop;
  74734. }
  74735. _this.video.setAttribute("playsinline", "");
  74736. _this.video.addEventListener("canplay", _this._createInternalTexture);
  74737. _this.video.addEventListener("paused", _this._updateInternalTexture);
  74738. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  74739. _this.video.addEventListener("emptied", _this.reset);
  74740. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  74741. _this._createInternalTexture();
  74742. }
  74743. if (settings.poster) {
  74744. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  74745. _this._poster = true;
  74746. }
  74747. return _this;
  74748. }
  74749. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  74750. /**
  74751. * Event triggerd when a dom action is required by the user to play the video.
  74752. * This happens due to recent changes in browser policies preventing video to auto start.
  74753. */
  74754. get: function () {
  74755. if (!this._onUserActionRequestedObservable) {
  74756. this._onUserActionRequestedObservable = new BABYLON.Observable();
  74757. }
  74758. return this._onUserActionRequestedObservable;
  74759. },
  74760. enumerable: true,
  74761. configurable: true
  74762. });
  74763. VideoTexture.prototype._getName = function (src) {
  74764. if (src instanceof HTMLVideoElement) {
  74765. return src.currentSrc;
  74766. }
  74767. if (typeof src === "object") {
  74768. return src.toString();
  74769. }
  74770. return src;
  74771. };
  74772. VideoTexture.prototype._getVideo = function (src) {
  74773. if (src instanceof HTMLVideoElement) {
  74774. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  74775. return src;
  74776. }
  74777. var video = document.createElement("video");
  74778. if (typeof src === "string") {
  74779. BABYLON.Tools.SetCorsBehavior(src, video);
  74780. video.src = src;
  74781. }
  74782. else {
  74783. BABYLON.Tools.SetCorsBehavior(src[0], video);
  74784. src.forEach(function (url) {
  74785. var source = document.createElement("source");
  74786. source.src = url;
  74787. video.appendChild(source);
  74788. });
  74789. }
  74790. return video;
  74791. };
  74792. /**
  74793. * @hidden Internal method to initiate `update`.
  74794. */
  74795. VideoTexture.prototype._rebuild = function () {
  74796. this.update();
  74797. };
  74798. /**
  74799. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  74800. */
  74801. VideoTexture.prototype.update = function () {
  74802. if (!this.autoUpdateTexture) {
  74803. // Expecting user to call `updateTexture` manually
  74804. return;
  74805. }
  74806. this.updateTexture(true);
  74807. };
  74808. /**
  74809. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  74810. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  74811. */
  74812. VideoTexture.prototype.updateTexture = function (isVisible) {
  74813. if (!isVisible) {
  74814. return;
  74815. }
  74816. if (this.video.paused && this._stillImageCaptured) {
  74817. return;
  74818. }
  74819. this._stillImageCaptured = true;
  74820. this._updateInternalTexture();
  74821. };
  74822. /**
  74823. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  74824. * @param url New url.
  74825. */
  74826. VideoTexture.prototype.updateURL = function (url) {
  74827. this.video.src = url;
  74828. };
  74829. /**
  74830. * Dispose the texture and release its associated resources.
  74831. */
  74832. VideoTexture.prototype.dispose = function () {
  74833. _super.prototype.dispose.call(this);
  74834. if (this._onUserActionRequestedObservable) {
  74835. this._onUserActionRequestedObservable.clear();
  74836. this._onUserActionRequestedObservable = null;
  74837. }
  74838. this.video.removeEventListener("canplay", this._createInternalTexture);
  74839. this.video.removeEventListener("paused", this._updateInternalTexture);
  74840. this.video.removeEventListener("seeked", this._updateInternalTexture);
  74841. this.video.removeEventListener("emptied", this.reset);
  74842. this.video.pause();
  74843. };
  74844. /**
  74845. * Creates a video texture straight from your WebCam video feed.
  74846. * @param scene Define the scene the texture should be created in
  74847. * @param onReady Define a callback to triggered once the texture will be ready
  74848. * @param constraints Define the constraints to use to create the web cam feed from WebRTC
  74849. */
  74850. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  74851. var video = document.createElement("video");
  74852. video.setAttribute('autoplay', '');
  74853. video.setAttribute('muted', '');
  74854. video.setAttribute('playsinline', '');
  74855. var constraintsDeviceId;
  74856. if (constraints && constraints.deviceId) {
  74857. constraintsDeviceId = {
  74858. exact: constraints.deviceId,
  74859. };
  74860. }
  74861. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  74862. if (navigator.mediaDevices) {
  74863. navigator.mediaDevices.getUserMedia({ video: constraints })
  74864. .then(function (stream) {
  74865. if (video.mozSrcObject !== undefined) {
  74866. // hack for Firefox < 19
  74867. video.mozSrcObject = stream;
  74868. }
  74869. else {
  74870. video.srcObject = stream;
  74871. }
  74872. var onPlaying = function () {
  74873. if (onReady) {
  74874. onReady(new VideoTexture("video", video, scene, true, true));
  74875. }
  74876. video.removeEventListener("playing", onPlaying);
  74877. };
  74878. video.addEventListener("playing", onPlaying);
  74879. video.play();
  74880. })
  74881. .catch(function (err) {
  74882. BABYLON.Tools.Error(err.name);
  74883. });
  74884. }
  74885. else {
  74886. navigator.getUserMedia =
  74887. navigator.getUserMedia ||
  74888. navigator.webkitGetUserMedia ||
  74889. navigator.mozGetUserMedia ||
  74890. navigator.msGetUserMedia;
  74891. if (navigator.getUserMedia) {
  74892. navigator.getUserMedia({
  74893. video: {
  74894. deviceId: constraintsDeviceId,
  74895. width: {
  74896. min: (constraints && constraints.minWidth) || 256,
  74897. max: (constraints && constraints.maxWidth) || 640,
  74898. },
  74899. height: {
  74900. min: (constraints && constraints.minHeight) || 256,
  74901. max: (constraints && constraints.maxHeight) || 480,
  74902. },
  74903. },
  74904. }, function (stream) {
  74905. if (video.mozSrcObject !== undefined) {
  74906. // hack for Firefox < 19
  74907. video.mozSrcObject = stream;
  74908. }
  74909. else {
  74910. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  74911. }
  74912. video.play();
  74913. if (onReady) {
  74914. onReady(new VideoTexture("video", video, scene, true, true));
  74915. }
  74916. }, function (e) {
  74917. BABYLON.Tools.Error(e.name);
  74918. });
  74919. }
  74920. }
  74921. };
  74922. return VideoTexture;
  74923. }(BABYLON.Texture));
  74924. BABYLON.VideoTexture = VideoTexture;
  74925. })(BABYLON || (BABYLON = {}));
  74926. //# sourceMappingURL=videoTexture.js.map
  74927. var BABYLON;
  74928. (function (BABYLON) {
  74929. /**
  74930. * Raw texture can help creating a texture directly from an array of data.
  74931. * This can be super useful if you either get the data from an uncompressed source or
  74932. * if you wish to create your texture pixel by pixel.
  74933. */
  74934. var RawTexture = /** @class */ (function (_super) {
  74935. __extends(RawTexture, _super);
  74936. /**
  74937. * Instantiates a new RawTexture.
  74938. * Raw texture can help creating a texture directly from an array of data.
  74939. * This can be super useful if you either get the data from an uncompressed source or
  74940. * if you wish to create your texture pixel by pixel.
  74941. * @param data define the array of data to use to create the texture
  74942. * @param width define the width of the texture
  74943. * @param height define the height of the texture
  74944. * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  74945. * @param scene define the scene the texture belongs to
  74946. * @param generateMipMaps define whether mip maps should be generated or not
  74947. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74948. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74949. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  74950. */
  74951. function RawTexture(data, width, height,
  74952. /**
  74953. * Define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  74954. */
  74955. format, scene, generateMipMaps, invertY, samplingMode, type) {
  74956. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74957. if (invertY === void 0) { invertY = false; }
  74958. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74959. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74960. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  74961. _this.format = format;
  74962. _this._engine = scene.getEngine();
  74963. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  74964. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74965. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74966. return _this;
  74967. }
  74968. /**
  74969. * Updates the texture underlying data.
  74970. * @param data Define the new data of the texture
  74971. */
  74972. RawTexture.prototype.update = function (data) {
  74973. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  74974. };
  74975. /**
  74976. * Creates a luminance texture from some data.
  74977. * @param data Define the texture data
  74978. * @param width Define the width of the texture
  74979. * @param height Define the height of the texture
  74980. * @param scene Define the scene the texture belongs to
  74981. * @param generateMipMaps Define whether or not to create mip maps for the texture
  74982. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  74983. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  74984. * @returns the luminance texture
  74985. */
  74986. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  74987. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74988. if (invertY === void 0) { invertY = false; }
  74989. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74990. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  74991. };
  74992. /**
  74993. * Creates a luminance alpha texture from some data.
  74994. * @param data Define the texture data
  74995. * @param width Define the width of the texture
  74996. * @param height Define the height of the texture
  74997. * @param scene Define the scene the texture belongs to
  74998. * @param generateMipMaps Define whether or not to create mip maps for the texture
  74999. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  75000. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  75001. * @returns the luminance alpha texture
  75002. */
  75003. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  75004. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75005. if (invertY === void 0) { invertY = false; }
  75006. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75007. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  75008. };
  75009. /**
  75010. * Creates an alpha texture from some data.
  75011. * @param data Define the texture data
  75012. * @param width Define the width of the texture
  75013. * @param height Define the height of the texture
  75014. * @param scene Define the scene the texture belongs to
  75015. * @param generateMipMaps Define whether or not to create mip maps for the texture
  75016. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  75017. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  75018. * @returns the alpha texture
  75019. */
  75020. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  75021. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75022. if (invertY === void 0) { invertY = false; }
  75023. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75024. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  75025. };
  75026. /**
  75027. * Creates a RGB texture from some data.
  75028. * @param data Define the texture data
  75029. * @param width Define the width of the texture
  75030. * @param height Define the height of the texture
  75031. * @param scene Define the scene the texture belongs to
  75032. * @param generateMipMaps Define whether or not to create mip maps for the texture
  75033. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  75034. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  75035. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  75036. * @returns the RGB alpha texture
  75037. */
  75038. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  75039. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75040. if (invertY === void 0) { invertY = false; }
  75041. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75042. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75043. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  75044. };
  75045. /**
  75046. * Creates a RGBA texture from some data.
  75047. * @param data Define the texture data
  75048. * @param width Define the width of the texture
  75049. * @param height Define the height of the texture
  75050. * @param scene Define the scene the texture belongs to
  75051. * @param generateMipMaps Define whether or not to create mip maps for the texture
  75052. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  75053. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  75054. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  75055. * @returns the RGBA texture
  75056. */
  75057. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  75058. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75059. if (invertY === void 0) { invertY = false; }
  75060. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75061. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75062. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  75063. };
  75064. /**
  75065. * Creates a R texture from some data.
  75066. * @param data Define the texture data
  75067. * @param width Define the width of the texture
  75068. * @param height Define the height of the texture
  75069. * @param scene Define the scene the texture belongs to
  75070. * @param generateMipMaps Define whether or not to create mip maps for the texture
  75071. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  75072. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  75073. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  75074. * @returns the R texture
  75075. */
  75076. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  75077. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75078. if (invertY === void 0) { invertY = false; }
  75079. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75080. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  75081. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  75082. };
  75083. return RawTexture;
  75084. }(BABYLON.Texture));
  75085. BABYLON.RawTexture = RawTexture;
  75086. })(BABYLON || (BABYLON = {}));
  75087. //# sourceMappingURL=rawTexture.js.map
  75088. var BABYLON;
  75089. (function (BABYLON) {
  75090. /**
  75091. * Class used to store 3D textures containing user data
  75092. */
  75093. var RawTexture3D = /** @class */ (function (_super) {
  75094. __extends(RawTexture3D, _super);
  75095. /**
  75096. * Create a new RawTexture3D
  75097. * @param data defines the data of the texture
  75098. * @param width defines the width of the texture
  75099. * @param height defines the height of the texture
  75100. * @param depth defines the depth of the texture
  75101. * @param format defines the texture format to use
  75102. * @param scene defines the hosting scene
  75103. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  75104. * @param invertY defines if texture must be stored with Y axis inverted
  75105. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  75106. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  75107. */
  75108. function RawTexture3D(data, width, height, depth,
  75109. /** Gets or sets the texture format to use */
  75110. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  75111. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75112. if (invertY === void 0) { invertY = false; }
  75113. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75114. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75115. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  75116. _this.format = format;
  75117. _this._engine = scene.getEngine();
  75118. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  75119. _this.is3D = true;
  75120. return _this;
  75121. }
  75122. /**
  75123. * Update the texture with new data
  75124. * @param data defines the data to store in the texture
  75125. */
  75126. RawTexture3D.prototype.update = function (data) {
  75127. if (!this._texture) {
  75128. return;
  75129. }
  75130. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  75131. };
  75132. return RawTexture3D;
  75133. }(BABYLON.Texture));
  75134. BABYLON.RawTexture3D = RawTexture3D;
  75135. })(BABYLON || (BABYLON = {}));
  75136. //# sourceMappingURL=rawTexture3D.js.map
  75137. var BABYLON;
  75138. (function (BABYLON) {
  75139. /**
  75140. * PostProcessManager is used to manage one or more post processes or post process pipelines
  75141. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  75142. */
  75143. var PostProcessManager = /** @class */ (function () {
  75144. /**
  75145. * Creates a new instance PostProcess
  75146. * @param scene The scene that the post process is associated with.
  75147. */
  75148. function PostProcessManager(scene) {
  75149. this._vertexBuffers = {};
  75150. this._scene = scene;
  75151. }
  75152. PostProcessManager.prototype._prepareBuffers = function () {
  75153. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  75154. return;
  75155. }
  75156. // VBO
  75157. var vertices = [];
  75158. vertices.push(1, 1);
  75159. vertices.push(-1, 1);
  75160. vertices.push(-1, -1);
  75161. vertices.push(1, -1);
  75162. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  75163. this._buildIndexBuffer();
  75164. };
  75165. PostProcessManager.prototype._buildIndexBuffer = function () {
  75166. // Indices
  75167. var indices = [];
  75168. indices.push(0);
  75169. indices.push(1);
  75170. indices.push(2);
  75171. indices.push(0);
  75172. indices.push(2);
  75173. indices.push(3);
  75174. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  75175. };
  75176. /**
  75177. * Rebuilds the vertex buffers of the manager.
  75178. * @hidden
  75179. */
  75180. PostProcessManager.prototype._rebuild = function () {
  75181. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75182. if (!vb) {
  75183. return;
  75184. }
  75185. vb._rebuild();
  75186. this._buildIndexBuffer();
  75187. };
  75188. // Methods
  75189. /**
  75190. * Prepares a frame to be run through a post process.
  75191. * @param sourceTexture The input texture to the post procesess. (default: null)
  75192. * @param postProcesses An array of post processes to be run. (default: null)
  75193. * @returns True if the post processes were able to be run.
  75194. * @hidden
  75195. */
  75196. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  75197. if (sourceTexture === void 0) { sourceTexture = null; }
  75198. if (postProcesses === void 0) { postProcesses = null; }
  75199. var camera = this._scene.activeCamera;
  75200. if (!camera) {
  75201. return false;
  75202. }
  75203. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  75204. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  75205. return false;
  75206. }
  75207. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  75208. return true;
  75209. };
  75210. /**
  75211. * Manually render a set of post processes to a texture.
  75212. * @param postProcesses An array of post processes to be run.
  75213. * @param targetTexture The target texture to render to.
  75214. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  75215. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  75216. * @param lodLevel defines which lod of the texture to render to
  75217. */
  75218. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  75219. if (targetTexture === void 0) { targetTexture = null; }
  75220. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  75221. if (faceIndex === void 0) { faceIndex = 0; }
  75222. if (lodLevel === void 0) { lodLevel = 0; }
  75223. var engine = this._scene.getEngine();
  75224. for (var index = 0; index < postProcesses.length; index++) {
  75225. if (index < postProcesses.length - 1) {
  75226. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  75227. }
  75228. else {
  75229. if (targetTexture) {
  75230. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  75231. }
  75232. else {
  75233. engine.restoreDefaultFramebuffer();
  75234. }
  75235. }
  75236. var pp = postProcesses[index];
  75237. var effect = pp.apply();
  75238. if (effect) {
  75239. pp.onBeforeRenderObservable.notifyObservers(effect);
  75240. // VBOs
  75241. this._prepareBuffers();
  75242. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  75243. // Draw order
  75244. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75245. pp.onAfterRenderObservable.notifyObservers(effect);
  75246. }
  75247. }
  75248. // Restore depth buffer
  75249. engine.setDepthBuffer(true);
  75250. engine.setDepthWrite(true);
  75251. };
  75252. /**
  75253. * Finalize the result of the output of the postprocesses.
  75254. * @param doNotPresent If true the result will not be displayed to the screen.
  75255. * @param targetTexture The target texture to render to.
  75256. * @param faceIndex The index of the face to bind the target texture to.
  75257. * @param postProcesses The array of post processes to render.
  75258. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  75259. * @hidden
  75260. */
  75261. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  75262. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  75263. var camera = this._scene.activeCamera;
  75264. if (!camera) {
  75265. return;
  75266. }
  75267. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  75268. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  75269. return;
  75270. }
  75271. var engine = this._scene.getEngine();
  75272. for (var index = 0, len = postProcesses.length; index < len; index++) {
  75273. var pp = postProcesses[index];
  75274. if (index < len - 1) {
  75275. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  75276. }
  75277. else {
  75278. if (targetTexture) {
  75279. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  75280. pp._outputTexture = targetTexture;
  75281. }
  75282. else {
  75283. engine.restoreDefaultFramebuffer();
  75284. pp._outputTexture = null;
  75285. }
  75286. }
  75287. if (doNotPresent) {
  75288. break;
  75289. }
  75290. var effect = pp.apply();
  75291. if (effect) {
  75292. pp.onBeforeRenderObservable.notifyObservers(effect);
  75293. // VBOs
  75294. this._prepareBuffers();
  75295. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  75296. // Draw order
  75297. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75298. pp.onAfterRenderObservable.notifyObservers(effect);
  75299. }
  75300. }
  75301. // Restore states
  75302. engine.setDepthBuffer(true);
  75303. engine.setDepthWrite(true);
  75304. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75305. };
  75306. /**
  75307. * Disposes of the post process manager.
  75308. */
  75309. PostProcessManager.prototype.dispose = function () {
  75310. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75311. if (buffer) {
  75312. buffer.dispose();
  75313. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75314. }
  75315. if (this._indexBuffer) {
  75316. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75317. this._indexBuffer = null;
  75318. }
  75319. };
  75320. return PostProcessManager;
  75321. }());
  75322. BABYLON.PostProcessManager = PostProcessManager;
  75323. })(BABYLON || (BABYLON = {}));
  75324. //# sourceMappingURL=postProcessManager.js.map
  75325. var BABYLON;
  75326. (function (BABYLON) {
  75327. /**
  75328. * PostProcess can be used to apply a shader to a texture after it has been rendered
  75329. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  75330. */
  75331. var PostProcess = /** @class */ (function () {
  75332. /**
  75333. * Creates a new instance PostProcess
  75334. * @param name The name of the PostProcess.
  75335. * @param fragmentUrl The url of the fragment shader to be used.
  75336. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  75337. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  75338. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75339. * @param camera The camera to apply the render pass to.
  75340. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75341. * @param engine The engine which the post process will be applied. (default: current engine)
  75342. * @param reusable If the post process can be reused on the same frame. (default: false)
  75343. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  75344. * @param textureType Type of textures used when performing the post process. (default: 0)
  75345. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  75346. * @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
  75347. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  75348. */
  75349. function PostProcess(
  75350. /** Name of the PostProcess. */
  75351. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  75352. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  75353. if (defines === void 0) { defines = null; }
  75354. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75355. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  75356. if (blockCompilation === void 0) { blockCompilation = false; }
  75357. this.name = name;
  75358. /**
  75359. * Width of the texture to apply the post process on
  75360. */
  75361. this.width = -1;
  75362. /**
  75363. * Height of the texture to apply the post process on
  75364. */
  75365. this.height = -1;
  75366. /**
  75367. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  75368. * @hidden
  75369. */
  75370. this._outputTexture = null;
  75371. /**
  75372. * If the buffer needs to be cleared before applying the post process. (default: true)
  75373. * Should be set to false if shader will overwrite all previous pixels.
  75374. */
  75375. this.autoClear = true;
  75376. /**
  75377. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  75378. */
  75379. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  75380. /**
  75381. * Animations to be used for the post processing
  75382. */
  75383. this.animations = new Array();
  75384. /**
  75385. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  75386. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  75387. */
  75388. this.enablePixelPerfectMode = false;
  75389. /**
  75390. * Force the postprocess to be applied without taking in account viewport
  75391. */
  75392. this.forceFullscreenViewport = true;
  75393. /**
  75394. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  75395. *
  75396. * | Value | Type | Description |
  75397. * | ----- | ----------------------------------- | ----------- |
  75398. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  75399. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  75400. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  75401. *
  75402. */
  75403. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  75404. /**
  75405. * Force textures to be a power of two (default: false)
  75406. */
  75407. this.alwaysForcePOT = false;
  75408. this._samples = 1;
  75409. /**
  75410. * Modify the scale of the post process to be the same as the viewport (default: false)
  75411. */
  75412. this.adaptScaleToCurrentViewport = false;
  75413. this._reusable = false;
  75414. /**
  75415. * Smart array of input and output textures for the post process.
  75416. * @hidden
  75417. */
  75418. this._textures = new BABYLON.SmartArray(2);
  75419. /**
  75420. * The index in _textures that corresponds to the output texture.
  75421. * @hidden
  75422. */
  75423. this._currentRenderTextureInd = 0;
  75424. this._scaleRatio = new BABYLON.Vector2(1, 1);
  75425. this._texelSize = BABYLON.Vector2.Zero();
  75426. // Events
  75427. /**
  75428. * An event triggered when the postprocess is activated.
  75429. */
  75430. this.onActivateObservable = new BABYLON.Observable();
  75431. /**
  75432. * An event triggered when the postprocess changes its size.
  75433. */
  75434. this.onSizeChangedObservable = new BABYLON.Observable();
  75435. /**
  75436. * An event triggered when the postprocess applies its effect.
  75437. */
  75438. this.onApplyObservable = new BABYLON.Observable();
  75439. /**
  75440. * An event triggered before rendering the postprocess
  75441. */
  75442. this.onBeforeRenderObservable = new BABYLON.Observable();
  75443. /**
  75444. * An event triggered after rendering the postprocess
  75445. */
  75446. this.onAfterRenderObservable = new BABYLON.Observable();
  75447. if (camera != null) {
  75448. this._camera = camera;
  75449. this._scene = camera.getScene();
  75450. camera.attachPostProcess(this);
  75451. this._engine = this._scene.getEngine();
  75452. this._scene.postProcesses.push(this);
  75453. }
  75454. else if (engine) {
  75455. this._engine = engine;
  75456. this._engine.postProcesses.push(this);
  75457. }
  75458. this._options = options;
  75459. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  75460. this._reusable = reusable || false;
  75461. this._textureType = textureType;
  75462. this._samplers = samplers || [];
  75463. this._samplers.push("textureSampler");
  75464. this._fragmentUrl = fragmentUrl;
  75465. this._vertexUrl = vertexUrl;
  75466. this._parameters = parameters || [];
  75467. this._parameters.push("scale");
  75468. this._indexParameters = indexParameters;
  75469. if (!blockCompilation) {
  75470. this.updateEffect(defines);
  75471. }
  75472. }
  75473. Object.defineProperty(PostProcess.prototype, "samples", {
  75474. /**
  75475. * Number of sample textures (default: 1)
  75476. */
  75477. get: function () {
  75478. return this._samples;
  75479. },
  75480. set: function (n) {
  75481. var _this = this;
  75482. this._samples = n;
  75483. this._textures.forEach(function (texture) {
  75484. if (texture.samples !== _this._samples) {
  75485. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  75486. }
  75487. });
  75488. },
  75489. enumerable: true,
  75490. configurable: true
  75491. });
  75492. Object.defineProperty(PostProcess.prototype, "onActivate", {
  75493. /**
  75494. * A function that is added to the onActivateObservable
  75495. */
  75496. set: function (callback) {
  75497. if (this._onActivateObserver) {
  75498. this.onActivateObservable.remove(this._onActivateObserver);
  75499. }
  75500. if (callback) {
  75501. this._onActivateObserver = this.onActivateObservable.add(callback);
  75502. }
  75503. },
  75504. enumerable: true,
  75505. configurable: true
  75506. });
  75507. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  75508. /**
  75509. * A function that is added to the onSizeChangedObservable
  75510. */
  75511. set: function (callback) {
  75512. if (this._onSizeChangedObserver) {
  75513. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  75514. }
  75515. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  75516. },
  75517. enumerable: true,
  75518. configurable: true
  75519. });
  75520. Object.defineProperty(PostProcess.prototype, "onApply", {
  75521. /**
  75522. * A function that is added to the onApplyObservable
  75523. */
  75524. set: function (callback) {
  75525. if (this._onApplyObserver) {
  75526. this.onApplyObservable.remove(this._onApplyObserver);
  75527. }
  75528. this._onApplyObserver = this.onApplyObservable.add(callback);
  75529. },
  75530. enumerable: true,
  75531. configurable: true
  75532. });
  75533. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  75534. /**
  75535. * A function that is added to the onBeforeRenderObservable
  75536. */
  75537. set: function (callback) {
  75538. if (this._onBeforeRenderObserver) {
  75539. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  75540. }
  75541. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  75542. },
  75543. enumerable: true,
  75544. configurable: true
  75545. });
  75546. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  75547. /**
  75548. * A function that is added to the onAfterRenderObservable
  75549. */
  75550. set: function (callback) {
  75551. if (this._onAfterRenderObserver) {
  75552. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  75553. }
  75554. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  75555. },
  75556. enumerable: true,
  75557. configurable: true
  75558. });
  75559. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  75560. /**
  75561. * 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
  75562. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  75563. */
  75564. get: function () {
  75565. return this._textures.data[this._currentRenderTextureInd];
  75566. },
  75567. set: function (value) {
  75568. this._forcedOutputTexture = value;
  75569. },
  75570. enumerable: true,
  75571. configurable: true
  75572. });
  75573. /**
  75574. * Gets the camera which post process is applied to.
  75575. * @returns The camera the post process is applied to.
  75576. */
  75577. PostProcess.prototype.getCamera = function () {
  75578. return this._camera;
  75579. };
  75580. Object.defineProperty(PostProcess.prototype, "texelSize", {
  75581. /**
  75582. * Gets the texel size of the postprocess.
  75583. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  75584. */
  75585. get: function () {
  75586. if (this._shareOutputWithPostProcess) {
  75587. return this._shareOutputWithPostProcess.texelSize;
  75588. }
  75589. if (this._forcedOutputTexture) {
  75590. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  75591. }
  75592. return this._texelSize;
  75593. },
  75594. enumerable: true,
  75595. configurable: true
  75596. });
  75597. /**
  75598. * Gets the engine which this post process belongs to.
  75599. * @returns The engine the post process was enabled with.
  75600. */
  75601. PostProcess.prototype.getEngine = function () {
  75602. return this._engine;
  75603. };
  75604. /**
  75605. * The effect that is created when initializing the post process.
  75606. * @returns The created effect corrisponding the the postprocess.
  75607. */
  75608. PostProcess.prototype.getEffect = function () {
  75609. return this._effect;
  75610. };
  75611. /**
  75612. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  75613. * @param postProcess The post process to share the output with.
  75614. * @returns This post process.
  75615. */
  75616. PostProcess.prototype.shareOutputWith = function (postProcess) {
  75617. this._disposeTextures();
  75618. this._shareOutputWithPostProcess = postProcess;
  75619. return this;
  75620. };
  75621. /**
  75622. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  75623. * This should be called if the post process that shares output with this post process is disabled/disposed.
  75624. */
  75625. PostProcess.prototype.useOwnOutput = function () {
  75626. if (this._textures.length == 0) {
  75627. this._textures = new BABYLON.SmartArray(2);
  75628. }
  75629. this._shareOutputWithPostProcess = null;
  75630. };
  75631. /**
  75632. * Updates the effect with the current post process compile time values and recompiles the shader.
  75633. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75634. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75635. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75636. * @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
  75637. * @param onCompiled Called when the shader has been compiled.
  75638. * @param onError Called if there is an error when compiling a shader.
  75639. */
  75640. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75641. if (defines === void 0) { defines = null; }
  75642. if (uniforms === void 0) { uniforms = null; }
  75643. if (samplers === void 0) { samplers = null; }
  75644. 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);
  75645. };
  75646. /**
  75647. * The post process is reusable if it can be used multiple times within one frame.
  75648. * @returns If the post process is reusable
  75649. */
  75650. PostProcess.prototype.isReusable = function () {
  75651. return this._reusable;
  75652. };
  75653. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  75654. PostProcess.prototype.markTextureDirty = function () {
  75655. this.width = -1;
  75656. };
  75657. /**
  75658. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  75659. * 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.
  75660. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  75661. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  75662. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  75663. * @returns The target texture that was bound to be written to.
  75664. */
  75665. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  75666. var _this = this;
  75667. if (sourceTexture === void 0) { sourceTexture = null; }
  75668. camera = camera || this._camera;
  75669. var scene = camera.getScene();
  75670. var engine = scene.getEngine();
  75671. var maxSize = engine.getCaps().maxTextureSize;
  75672. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  75673. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  75674. // 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
  75675. var webVRCamera = camera.parent;
  75676. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  75677. requiredWidth /= 2;
  75678. }
  75679. var desiredWidth = (this._options.width || requiredWidth);
  75680. var desiredHeight = this._options.height || requiredHeight;
  75681. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  75682. if (this.adaptScaleToCurrentViewport) {
  75683. var currentViewport = engine.currentViewport;
  75684. if (currentViewport) {
  75685. desiredWidth *= currentViewport.width;
  75686. desiredHeight *= currentViewport.height;
  75687. }
  75688. }
  75689. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  75690. if (!this._options.width) {
  75691. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  75692. }
  75693. if (!this._options.height) {
  75694. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  75695. }
  75696. }
  75697. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  75698. if (this._textures.length > 0) {
  75699. for (var i = 0; i < this._textures.length; i++) {
  75700. this._engine._releaseTexture(this._textures.data[i]);
  75701. }
  75702. this._textures.reset();
  75703. }
  75704. this.width = desiredWidth;
  75705. this.height = desiredHeight;
  75706. var textureSize = { width: this.width, height: this.height };
  75707. var textureOptions = {
  75708. generateMipMaps: false,
  75709. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  75710. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  75711. samplingMode: this.renderTargetSamplingMode,
  75712. type: this._textureType
  75713. };
  75714. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  75715. if (this._reusable) {
  75716. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  75717. }
  75718. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  75719. this.onSizeChangedObservable.notifyObservers(this);
  75720. }
  75721. this._textures.forEach(function (texture) {
  75722. if (texture.samples !== _this.samples) {
  75723. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  75724. }
  75725. });
  75726. }
  75727. var target;
  75728. if (this._shareOutputWithPostProcess) {
  75729. target = this._shareOutputWithPostProcess.inputTexture;
  75730. }
  75731. else if (this._forcedOutputTexture) {
  75732. target = this._forcedOutputTexture;
  75733. this.width = this._forcedOutputTexture.width;
  75734. this.height = this._forcedOutputTexture.height;
  75735. }
  75736. else {
  75737. target = this.inputTexture;
  75738. }
  75739. // Bind the input of this post process to be used as the output of the previous post process.
  75740. if (this.enablePixelPerfectMode) {
  75741. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  75742. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  75743. }
  75744. else {
  75745. this._scaleRatio.copyFromFloats(1, 1);
  75746. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  75747. }
  75748. this.onActivateObservable.notifyObservers(camera);
  75749. // Clear
  75750. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  75751. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  75752. }
  75753. if (this._reusable) {
  75754. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  75755. }
  75756. return target;
  75757. };
  75758. Object.defineProperty(PostProcess.prototype, "isSupported", {
  75759. /**
  75760. * If the post process is supported.
  75761. */
  75762. get: function () {
  75763. return this._effect.isSupported;
  75764. },
  75765. enumerable: true,
  75766. configurable: true
  75767. });
  75768. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  75769. /**
  75770. * The aspect ratio of the output texture.
  75771. */
  75772. get: function () {
  75773. if (this._shareOutputWithPostProcess) {
  75774. return this._shareOutputWithPostProcess.aspectRatio;
  75775. }
  75776. if (this._forcedOutputTexture) {
  75777. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  75778. }
  75779. return this.width / this.height;
  75780. },
  75781. enumerable: true,
  75782. configurable: true
  75783. });
  75784. /**
  75785. * Get a value indicating if the post-process is ready to be used
  75786. * @returns true if the post-process is ready (shader is compiled)
  75787. */
  75788. PostProcess.prototype.isReady = function () {
  75789. return this._effect && this._effect.isReady();
  75790. };
  75791. /**
  75792. * Binds all textures and uniforms to the shader, this will be run on every pass.
  75793. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  75794. */
  75795. PostProcess.prototype.apply = function () {
  75796. // Check
  75797. if (!this._effect || !this._effect.isReady()) {
  75798. return null;
  75799. }
  75800. // States
  75801. this._engine.enableEffect(this._effect);
  75802. this._engine.setState(false);
  75803. this._engine.setDepthBuffer(false);
  75804. this._engine.setDepthWrite(false);
  75805. // Alpha
  75806. this._engine.setAlphaMode(this.alphaMode);
  75807. if (this.alphaConstants) {
  75808. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  75809. }
  75810. // Bind the output texture of the preivous post process as the input to this post process.
  75811. var source;
  75812. if (this._shareOutputWithPostProcess) {
  75813. source = this._shareOutputWithPostProcess.inputTexture;
  75814. }
  75815. else if (this._forcedOutputTexture) {
  75816. source = this._forcedOutputTexture;
  75817. }
  75818. else {
  75819. source = this.inputTexture;
  75820. }
  75821. this._effect._bindTexture("textureSampler", source);
  75822. // Parameters
  75823. this._effect.setVector2("scale", this._scaleRatio);
  75824. this.onApplyObservable.notifyObservers(this._effect);
  75825. return this._effect;
  75826. };
  75827. PostProcess.prototype._disposeTextures = function () {
  75828. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  75829. return;
  75830. }
  75831. if (this._textures.length > 0) {
  75832. for (var i = 0; i < this._textures.length; i++) {
  75833. this._engine._releaseTexture(this._textures.data[i]);
  75834. }
  75835. }
  75836. this._textures.dispose();
  75837. };
  75838. /**
  75839. * Disposes the post process.
  75840. * @param camera The camera to dispose the post process on.
  75841. */
  75842. PostProcess.prototype.dispose = function (camera) {
  75843. camera = camera || this._camera;
  75844. this._disposeTextures();
  75845. if (this._scene) {
  75846. var index_1 = this._scene.postProcesses.indexOf(this);
  75847. if (index_1 !== -1) {
  75848. this._scene.postProcesses.splice(index_1, 1);
  75849. }
  75850. }
  75851. else {
  75852. var index_2 = this._engine.postProcesses.indexOf(this);
  75853. if (index_2 !== -1) {
  75854. this._engine.postProcesses.splice(index_2, 1);
  75855. }
  75856. }
  75857. if (!camera) {
  75858. return;
  75859. }
  75860. camera.detachPostProcess(this);
  75861. var index = camera._postProcesses.indexOf(this);
  75862. if (index === 0 && camera._postProcesses.length > 0) {
  75863. var firstPostProcess = this._camera._getFirstPostProcess();
  75864. if (firstPostProcess) {
  75865. firstPostProcess.markTextureDirty();
  75866. }
  75867. }
  75868. this.onActivateObservable.clear();
  75869. this.onAfterRenderObservable.clear();
  75870. this.onApplyObservable.clear();
  75871. this.onBeforeRenderObservable.clear();
  75872. this.onSizeChangedObservable.clear();
  75873. };
  75874. return PostProcess;
  75875. }());
  75876. BABYLON.PostProcess = PostProcess;
  75877. })(BABYLON || (BABYLON = {}));
  75878. //# sourceMappingURL=postProcess.js.map
  75879. var BABYLON;
  75880. (function (BABYLON) {
  75881. /**
  75882. * PassPostProcess which produces an output the same as it's input
  75883. */
  75884. var PassPostProcess = /** @class */ (function (_super) {
  75885. __extends(PassPostProcess, _super);
  75886. /**
  75887. * Creates the PassPostProcess
  75888. * @param name The name of the effect.
  75889. * @param options The required width/height ratio to downsize to before computing the render pass.
  75890. * @param camera The camera to apply the render pass to.
  75891. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75892. * @param engine The engine which the post process will be applied. (default: current engine)
  75893. * @param reusable If the post process can be reused on the same frame. (default: false)
  75894. * @param textureType The type of texture to be used when performing the post processing.
  75895. * @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)
  75896. */
  75897. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75898. if (camera === void 0) { camera = null; }
  75899. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75900. if (blockCompilation === void 0) { blockCompilation = false; }
  75901. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  75902. }
  75903. return PassPostProcess;
  75904. }(BABYLON.PostProcess));
  75905. BABYLON.PassPostProcess = PassPostProcess;
  75906. })(BABYLON || (BABYLON = {}));
  75907. //# sourceMappingURL=passPostProcess.js.map
  75908. var __assign = (this && this.__assign) || function () {
  75909. __assign = Object.assign || function(t) {
  75910. for (var s, i = 1, n = arguments.length; i < n; i++) {
  75911. s = arguments[i];
  75912. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  75913. t[p] = s[p];
  75914. }
  75915. return t;
  75916. };
  75917. return __assign.apply(this, arguments);
  75918. };
  75919. var BABYLON;
  75920. (function (BABYLON) {
  75921. /**
  75922. * Default implementation IShadowGenerator.
  75923. * This is the main object responsible of generating shadows in the framework.
  75924. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  75925. */
  75926. var ShadowGenerator = /** @class */ (function () {
  75927. /**
  75928. * Creates a ShadowGenerator object.
  75929. * A ShadowGenerator is the required tool to use the shadows.
  75930. * Each light casting shadows needs to use its own ShadowGenerator.
  75931. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  75932. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  75933. * @param light The light object generating the shadows.
  75934. * @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.
  75935. */
  75936. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  75937. this._bias = 0.00005;
  75938. this._normalBias = 0;
  75939. this._blurBoxOffset = 1;
  75940. this._blurScale = 2;
  75941. this._blurKernel = 1;
  75942. this._useKernelBlur = false;
  75943. this._filter = ShadowGenerator.FILTER_NONE;
  75944. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  75945. this._contactHardeningLightSizeUVRatio = 0.1;
  75946. this._darkness = 0;
  75947. this._transparencyShadow = false;
  75948. /**
  75949. * Controls the extent to which the shadows fade out at the edge of the frustum
  75950. * Used only by directionals and spots
  75951. */
  75952. this.frustumEdgeFalloff = 0;
  75953. /**
  75954. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  75955. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  75956. * It might on the other hand introduce peter panning.
  75957. */
  75958. this.forceBackFacesOnly = false;
  75959. this._lightDirection = BABYLON.Vector3.Zero();
  75960. this._viewMatrix = BABYLON.Matrix.Zero();
  75961. this._projectionMatrix = BABYLON.Matrix.Zero();
  75962. this._transformMatrix = BABYLON.Matrix.Zero();
  75963. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  75964. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  75965. this._currentFaceIndex = 0;
  75966. this._currentFaceIndexCache = 0;
  75967. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  75968. this._mapSize = mapSize;
  75969. this._light = light;
  75970. this._scene = light.getScene();
  75971. light._shadowGenerator = this;
  75972. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  75973. if (!component) {
  75974. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  75975. this._scene._addComponent(component);
  75976. }
  75977. // Texture type fallback from float to int if not supported.
  75978. var caps = this._scene.getEngine().getCaps();
  75979. if (!useFullFloatFirst) {
  75980. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  75981. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75982. }
  75983. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  75984. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75985. }
  75986. else {
  75987. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75988. }
  75989. }
  75990. else {
  75991. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  75992. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75993. }
  75994. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  75995. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75996. }
  75997. else {
  75998. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75999. }
  76000. }
  76001. this._initializeGenerator();
  76002. this._applyFilterValues();
  76003. }
  76004. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  76005. /**
  76006. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  76007. */
  76008. get: function () {
  76009. return this._bias;
  76010. },
  76011. /**
  76012. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  76013. */
  76014. set: function (bias) {
  76015. this._bias = bias;
  76016. },
  76017. enumerable: true,
  76018. configurable: true
  76019. });
  76020. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  76021. /**
  76022. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  76023. */
  76024. get: function () {
  76025. return this._normalBias;
  76026. },
  76027. /**
  76028. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  76029. */
  76030. set: function (normalBias) {
  76031. this._normalBias = normalBias;
  76032. },
  76033. enumerable: true,
  76034. configurable: true
  76035. });
  76036. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  76037. /**
  76038. * Gets the blur box offset: offset applied during the blur pass.
  76039. * Only usefull if useKernelBlur = false
  76040. */
  76041. get: function () {
  76042. return this._blurBoxOffset;
  76043. },
  76044. /**
  76045. * Sets the blur box offset: offset applied during the blur pass.
  76046. * Only usefull if useKernelBlur = false
  76047. */
  76048. set: function (value) {
  76049. if (this._blurBoxOffset === value) {
  76050. return;
  76051. }
  76052. this._blurBoxOffset = value;
  76053. this._disposeBlurPostProcesses();
  76054. },
  76055. enumerable: true,
  76056. configurable: true
  76057. });
  76058. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  76059. /**
  76060. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  76061. * 2 means half of the size.
  76062. */
  76063. get: function () {
  76064. return this._blurScale;
  76065. },
  76066. /**
  76067. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  76068. * 2 means half of the size.
  76069. */
  76070. set: function (value) {
  76071. if (this._blurScale === value) {
  76072. return;
  76073. }
  76074. this._blurScale = value;
  76075. this._disposeBlurPostProcesses();
  76076. },
  76077. enumerable: true,
  76078. configurable: true
  76079. });
  76080. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  76081. /**
  76082. * Gets the blur kernel: kernel size of the blur pass.
  76083. * Only usefull if useKernelBlur = true
  76084. */
  76085. get: function () {
  76086. return this._blurKernel;
  76087. },
  76088. /**
  76089. * Sets the blur kernel: kernel size of the blur pass.
  76090. * Only usefull if useKernelBlur = true
  76091. */
  76092. set: function (value) {
  76093. if (this._blurKernel === value) {
  76094. return;
  76095. }
  76096. this._blurKernel = value;
  76097. this._disposeBlurPostProcesses();
  76098. },
  76099. enumerable: true,
  76100. configurable: true
  76101. });
  76102. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  76103. /**
  76104. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  76105. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  76106. */
  76107. get: function () {
  76108. return this._useKernelBlur;
  76109. },
  76110. /**
  76111. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  76112. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  76113. */
  76114. set: function (value) {
  76115. if (this._useKernelBlur === value) {
  76116. return;
  76117. }
  76118. this._useKernelBlur = value;
  76119. this._disposeBlurPostProcesses();
  76120. },
  76121. enumerable: true,
  76122. configurable: true
  76123. });
  76124. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  76125. /**
  76126. * Gets the depth scale used in ESM mode.
  76127. */
  76128. get: function () {
  76129. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  76130. },
  76131. /**
  76132. * Sets the depth scale used in ESM mode.
  76133. * This can override the scale stored on the light.
  76134. */
  76135. set: function (value) {
  76136. this._depthScale = value;
  76137. },
  76138. enumerable: true,
  76139. configurable: true
  76140. });
  76141. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  76142. /**
  76143. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  76144. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  76145. */
  76146. get: function () {
  76147. return this._filter;
  76148. },
  76149. /**
  76150. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  76151. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  76152. */
  76153. set: function (value) {
  76154. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  76155. if (this._light.needCube()) {
  76156. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  76157. this.useExponentialShadowMap = true;
  76158. return;
  76159. }
  76160. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  76161. this.useCloseExponentialShadowMap = true;
  76162. return;
  76163. }
  76164. // PCF on cubemap would also be expensive
  76165. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  76166. this.usePoissonSampling = true;
  76167. return;
  76168. }
  76169. }
  76170. // Weblg1 fallback for PCF.
  76171. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  76172. if (this._scene.getEngine().webGLVersion === 1) {
  76173. this.usePoissonSampling = true;
  76174. return;
  76175. }
  76176. }
  76177. if (this._filter === value) {
  76178. return;
  76179. }
  76180. this._filter = value;
  76181. this._disposeBlurPostProcesses();
  76182. this._applyFilterValues();
  76183. this._light._markMeshesAsLightDirty();
  76184. },
  76185. enumerable: true,
  76186. configurable: true
  76187. });
  76188. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  76189. /**
  76190. * Gets if the current filter is set to Poisson Sampling.
  76191. */
  76192. get: function () {
  76193. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  76194. },
  76195. /**
  76196. * Sets the current filter to Poisson Sampling.
  76197. */
  76198. set: function (value) {
  76199. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  76200. return;
  76201. }
  76202. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  76203. },
  76204. enumerable: true,
  76205. configurable: true
  76206. });
  76207. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  76208. /**
  76209. * Gets if the current filter is set to ESM.
  76210. */
  76211. get: function () {
  76212. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  76213. },
  76214. /**
  76215. * Sets the current filter is to ESM.
  76216. */
  76217. set: function (value) {
  76218. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  76219. return;
  76220. }
  76221. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  76222. },
  76223. enumerable: true,
  76224. configurable: true
  76225. });
  76226. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  76227. /**
  76228. * Gets if the current filter is set to filtered ESM.
  76229. */
  76230. get: function () {
  76231. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  76232. },
  76233. /**
  76234. * Gets if the current filter is set to filtered ESM.
  76235. */
  76236. set: function (value) {
  76237. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  76238. return;
  76239. }
  76240. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  76241. },
  76242. enumerable: true,
  76243. configurable: true
  76244. });
  76245. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  76246. /**
  76247. * Gets if the current filter is set to "close ESM" (using the inverse of the
  76248. * exponential to prevent steep falloff artifacts).
  76249. */
  76250. get: function () {
  76251. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  76252. },
  76253. /**
  76254. * Sets the current filter to "close ESM" (using the inverse of the
  76255. * exponential to prevent steep falloff artifacts).
  76256. */
  76257. set: function (value) {
  76258. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  76259. return;
  76260. }
  76261. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  76262. },
  76263. enumerable: true,
  76264. configurable: true
  76265. });
  76266. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  76267. /**
  76268. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  76269. * exponential to prevent steep falloff artifacts).
  76270. */
  76271. get: function () {
  76272. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  76273. },
  76274. /**
  76275. * Sets the current filter to filtered "close ESM" (using the inverse of the
  76276. * exponential to prevent steep falloff artifacts).
  76277. */
  76278. set: function (value) {
  76279. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  76280. return;
  76281. }
  76282. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  76283. },
  76284. enumerable: true,
  76285. configurable: true
  76286. });
  76287. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  76288. /**
  76289. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  76290. */
  76291. get: function () {
  76292. return this.filter === ShadowGenerator.FILTER_PCF;
  76293. },
  76294. /**
  76295. * Sets the current filter to "PCF" (percentage closer filtering).
  76296. */
  76297. set: function (value) {
  76298. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  76299. return;
  76300. }
  76301. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  76302. },
  76303. enumerable: true,
  76304. configurable: true
  76305. });
  76306. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  76307. /**
  76308. * Gets the PCF or PCSS Quality.
  76309. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  76310. */
  76311. get: function () {
  76312. return this._filteringQuality;
  76313. },
  76314. /**
  76315. * Sets the PCF or PCSS Quality.
  76316. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  76317. */
  76318. set: function (filteringQuality) {
  76319. this._filteringQuality = filteringQuality;
  76320. },
  76321. enumerable: true,
  76322. configurable: true
  76323. });
  76324. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  76325. /**
  76326. * Gets if the current filter is set to "PCSS" (contact hardening).
  76327. */
  76328. get: function () {
  76329. return this.filter === ShadowGenerator.FILTER_PCSS;
  76330. },
  76331. /**
  76332. * Sets the current filter to "PCSS" (contact hardening).
  76333. */
  76334. set: function (value) {
  76335. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  76336. return;
  76337. }
  76338. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  76339. },
  76340. enumerable: true,
  76341. configurable: true
  76342. });
  76343. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  76344. /**
  76345. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  76346. * Using a ratio helps keeping shape stability independently of the map size.
  76347. *
  76348. * It does not account for the light projection as it was having too much
  76349. * instability during the light setup or during light position changes.
  76350. *
  76351. * Only valid if useContactHardeningShadow is true.
  76352. */
  76353. get: function () {
  76354. return this._contactHardeningLightSizeUVRatio;
  76355. },
  76356. /**
  76357. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  76358. * Using a ratio helps keeping shape stability independently of the map size.
  76359. *
  76360. * It does not account for the light projection as it was having too much
  76361. * instability during the light setup or during light position changes.
  76362. *
  76363. * Only valid if useContactHardeningShadow is true.
  76364. */
  76365. set: function (contactHardeningLightSizeUVRatio) {
  76366. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  76367. },
  76368. enumerable: true,
  76369. configurable: true
  76370. });
  76371. /**
  76372. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  76373. * 0 means strongest and 1 would means no shadow.
  76374. * @returns the darkness.
  76375. */
  76376. ShadowGenerator.prototype.getDarkness = function () {
  76377. return this._darkness;
  76378. };
  76379. /**
  76380. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  76381. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  76382. * @returns the shadow generator allowing fluent coding.
  76383. */
  76384. ShadowGenerator.prototype.setDarkness = function (darkness) {
  76385. if (darkness >= 1.0) {
  76386. this._darkness = 1.0;
  76387. }
  76388. else if (darkness <= 0.0) {
  76389. this._darkness = 0.0;
  76390. }
  76391. else {
  76392. this._darkness = darkness;
  76393. }
  76394. return this;
  76395. };
  76396. /**
  76397. * Sets the ability to have transparent shadow (boolean).
  76398. * @param transparent True if transparent else False
  76399. * @returns the shadow generator allowing fluent coding
  76400. */
  76401. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  76402. this._transparencyShadow = transparent;
  76403. return this;
  76404. };
  76405. /**
  76406. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  76407. * @returns The render target texture if present otherwise, null
  76408. */
  76409. ShadowGenerator.prototype.getShadowMap = function () {
  76410. return this._shadowMap;
  76411. };
  76412. /**
  76413. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  76414. * @returns The render target texture if the shadow map is present otherwise, null
  76415. */
  76416. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  76417. if (this._shadowMap2) {
  76418. return this._shadowMap2;
  76419. }
  76420. return this._shadowMap;
  76421. };
  76422. /**
  76423. * Helper function to add a mesh and its descendants to the list of shadow casters.
  76424. * @param mesh Mesh to add
  76425. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  76426. * @returns the Shadow Generator itself
  76427. */
  76428. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  76429. if (includeDescendants === void 0) { includeDescendants = true; }
  76430. var _a;
  76431. if (!this._shadowMap) {
  76432. return this;
  76433. }
  76434. if (!this._shadowMap.renderList) {
  76435. this._shadowMap.renderList = [];
  76436. }
  76437. this._shadowMap.renderList.push(mesh);
  76438. if (includeDescendants) {
  76439. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  76440. }
  76441. return this;
  76442. };
  76443. /**
  76444. * Helper function to remove a mesh and its descendants from the list of shadow casters
  76445. * @param mesh Mesh to remove
  76446. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  76447. * @returns the Shadow Generator itself
  76448. */
  76449. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  76450. if (includeDescendants === void 0) { includeDescendants = true; }
  76451. if (!this._shadowMap || !this._shadowMap.renderList) {
  76452. return this;
  76453. }
  76454. var index = this._shadowMap.renderList.indexOf(mesh);
  76455. if (index !== -1) {
  76456. this._shadowMap.renderList.splice(index, 1);
  76457. }
  76458. if (includeDescendants) {
  76459. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  76460. var child = _a[_i];
  76461. this.removeShadowCaster(child);
  76462. }
  76463. }
  76464. return this;
  76465. };
  76466. /**
  76467. * Returns the associated light object.
  76468. * @returns the light generating the shadow
  76469. */
  76470. ShadowGenerator.prototype.getLight = function () {
  76471. return this._light;
  76472. };
  76473. ShadowGenerator.prototype._initializeGenerator = function () {
  76474. this._light._markMeshesAsLightDirty();
  76475. this._initializeShadowMap();
  76476. };
  76477. ShadowGenerator.prototype._initializeShadowMap = function () {
  76478. var _this = this;
  76479. // Render target
  76480. var engine = this._scene.getEngine();
  76481. if (engine.webGLVersion > 1) {
  76482. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  76483. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  76484. }
  76485. else {
  76486. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  76487. }
  76488. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76489. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76490. this._shadowMap.anisotropicFilteringLevel = 1;
  76491. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76492. this._shadowMap.renderParticles = false;
  76493. this._shadowMap.ignoreCameraViewport = true;
  76494. // Record Face Index before render.
  76495. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  76496. _this._currentFaceIndex = faceIndex;
  76497. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  76498. engine.setColorWrite(false);
  76499. }
  76500. });
  76501. // Custom render function.
  76502. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  76503. // Blur if required afer render.
  76504. this._shadowMap.onAfterUnbindObservable.add(function () {
  76505. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  76506. engine.setColorWrite(true);
  76507. }
  76508. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  76509. return;
  76510. }
  76511. var shadowMap = _this.getShadowMapForRendering();
  76512. if (shadowMap) {
  76513. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  76514. }
  76515. });
  76516. // Clear according to the chosen filter.
  76517. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  76518. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  76519. this._shadowMap.onClearObservable.add(function (engine) {
  76520. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  76521. engine.clear(clearOne, false, true, false);
  76522. }
  76523. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  76524. engine.clear(clearZero, true, true, false);
  76525. }
  76526. else {
  76527. engine.clear(clearOne, true, true, false);
  76528. }
  76529. });
  76530. };
  76531. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  76532. var _this = this;
  76533. var engine = this._scene.getEngine();
  76534. var targetSize = this._mapSize / this.blurScale;
  76535. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  76536. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  76537. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76538. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76539. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76540. }
  76541. if (this.useKernelBlur) {
  76542. 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);
  76543. this._kernelBlurXPostprocess.width = targetSize;
  76544. this._kernelBlurXPostprocess.height = targetSize;
  76545. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  76546. effect.setTexture("textureSampler", _this._shadowMap);
  76547. });
  76548. 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);
  76549. this._kernelBlurXPostprocess.autoClear = false;
  76550. this._kernelBlurYPostprocess.autoClear = false;
  76551. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  76552. this._kernelBlurXPostprocess.packedFloat = true;
  76553. this._kernelBlurYPostprocess.packedFloat = true;
  76554. }
  76555. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  76556. }
  76557. else {
  76558. 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);
  76559. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  76560. effect.setFloat2("screenSize", targetSize, targetSize);
  76561. effect.setTexture("textureSampler", _this._shadowMap);
  76562. });
  76563. this._boxBlurPostprocess.autoClear = false;
  76564. this._blurPostProcesses = [this._boxBlurPostprocess];
  76565. }
  76566. };
  76567. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76568. var index;
  76569. var engine = this._scene.getEngine();
  76570. if (depthOnlySubMeshes.length) {
  76571. engine.setColorWrite(false);
  76572. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76573. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  76574. }
  76575. engine.setColorWrite(true);
  76576. }
  76577. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76578. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  76579. }
  76580. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76581. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  76582. }
  76583. if (this._transparencyShadow) {
  76584. for (index = 0; index < transparentSubMeshes.length; index++) {
  76585. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  76586. }
  76587. }
  76588. };
  76589. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  76590. var _this = this;
  76591. var mesh = subMesh.getRenderingMesh();
  76592. var scene = this._scene;
  76593. var engine = scene.getEngine();
  76594. var material = subMesh.getMaterial();
  76595. if (!material || subMesh.verticesCount === 0) {
  76596. return;
  76597. }
  76598. // Culling
  76599. engine.setState(material.backFaceCulling);
  76600. // Managing instances
  76601. var batch = mesh._getInstancesRenderList(subMesh._id);
  76602. if (batch.mustReturn) {
  76603. return;
  76604. }
  76605. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  76606. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  76607. engine.enableEffect(this._effect);
  76608. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  76609. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  76610. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  76611. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  76612. this._effect.setVector3("lightData", this._cachedDirection);
  76613. }
  76614. else {
  76615. this._effect.setVector3("lightData", this._cachedPosition);
  76616. }
  76617. if (scene.activeCamera) {
  76618. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  76619. }
  76620. // Alpha test
  76621. if (material && material.needAlphaTesting()) {
  76622. var alphaTexture = material.getAlphaTestTexture();
  76623. if (alphaTexture) {
  76624. this._effect.setTexture("diffuseSampler", alphaTexture);
  76625. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  76626. }
  76627. }
  76628. // Bones
  76629. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76630. var skeleton = mesh.skeleton;
  76631. if (skeleton.isUsingTextureForMatrices) {
  76632. var boneTexture = skeleton.getTransformMatrixTexture();
  76633. if (!boneTexture) {
  76634. return;
  76635. }
  76636. this._effect.setTexture("boneSampler", boneTexture);
  76637. this._effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
  76638. }
  76639. else {
  76640. this._effect.setMatrices("mBones", skeleton.getTransformMatrices((mesh)));
  76641. }
  76642. }
  76643. // Morph targets
  76644. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  76645. if (this.forceBackFacesOnly) {
  76646. engine.setState(true, 0, false, true);
  76647. }
  76648. // Draw
  76649. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76650. if (this.forceBackFacesOnly) {
  76651. engine.setState(true, 0, false, false);
  76652. }
  76653. }
  76654. else {
  76655. // Need to reset refresh rate of the shadowMap
  76656. if (this._shadowMap) {
  76657. this._shadowMap.resetRefreshCounter();
  76658. }
  76659. }
  76660. };
  76661. ShadowGenerator.prototype._applyFilterValues = function () {
  76662. if (!this._shadowMap) {
  76663. return;
  76664. }
  76665. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  76666. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  76667. }
  76668. else {
  76669. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76670. }
  76671. };
  76672. /**
  76673. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  76674. * @param onCompiled Callback triggered at the and of the effects compilation
  76675. * @param options Sets of optional options forcing the compilation with different modes
  76676. */
  76677. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  76678. var _this = this;
  76679. var localOptions = __assign({ useInstances: false }, options);
  76680. var shadowMap = this.getShadowMap();
  76681. if (!shadowMap) {
  76682. if (onCompiled) {
  76683. onCompiled(this);
  76684. }
  76685. return;
  76686. }
  76687. var renderList = shadowMap.renderList;
  76688. if (!renderList) {
  76689. if (onCompiled) {
  76690. onCompiled(this);
  76691. }
  76692. return;
  76693. }
  76694. var subMeshes = new Array();
  76695. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  76696. var mesh = renderList_1[_i];
  76697. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  76698. }
  76699. if (subMeshes.length === 0) {
  76700. if (onCompiled) {
  76701. onCompiled(this);
  76702. }
  76703. return;
  76704. }
  76705. var currentIndex = 0;
  76706. var checkReady = function () {
  76707. if (!_this._scene || !_this._scene.getEngine()) {
  76708. return;
  76709. }
  76710. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  76711. currentIndex++;
  76712. if (currentIndex >= subMeshes.length) {
  76713. if (onCompiled) {
  76714. onCompiled(_this);
  76715. }
  76716. return;
  76717. }
  76718. }
  76719. setTimeout(checkReady, 16);
  76720. };
  76721. checkReady();
  76722. };
  76723. /**
  76724. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  76725. * @param options Sets of optional options forcing the compilation with different modes
  76726. * @returns A promise that resolves when the compilation completes
  76727. */
  76728. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  76729. var _this = this;
  76730. return new Promise(function (resolve) {
  76731. _this.forceCompilation(function () {
  76732. resolve();
  76733. }, options);
  76734. });
  76735. };
  76736. /**
  76737. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  76738. * @param subMesh The submesh we want to render in the shadow map
  76739. * @param useInstances Defines wether will draw in the map using instances
  76740. * @returns true if ready otherwise, false
  76741. */
  76742. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  76743. var defines = [];
  76744. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  76745. defines.push("#define FLOAT");
  76746. }
  76747. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  76748. defines.push("#define ESM");
  76749. }
  76750. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  76751. defines.push("#define DEPTHTEXTURE");
  76752. }
  76753. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76754. var mesh = subMesh.getMesh();
  76755. var material = subMesh.getMaterial();
  76756. // Normal bias.
  76757. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  76758. attribs.push(BABYLON.VertexBuffer.NormalKind);
  76759. defines.push("#define NORMAL");
  76760. if (mesh.nonUniformScaling) {
  76761. defines.push("#define NONUNIFORMSCALING");
  76762. }
  76763. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  76764. defines.push("#define DIRECTIONINLIGHTDATA");
  76765. }
  76766. }
  76767. // Alpha test
  76768. if (material && material.needAlphaTesting()) {
  76769. var alphaTexture = material.getAlphaTestTexture();
  76770. if (alphaTexture) {
  76771. defines.push("#define ALPHATEST");
  76772. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76773. attribs.push(BABYLON.VertexBuffer.UVKind);
  76774. defines.push("#define UV1");
  76775. }
  76776. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76777. if (alphaTexture.coordinatesIndex === 1) {
  76778. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76779. defines.push("#define UV2");
  76780. }
  76781. }
  76782. }
  76783. }
  76784. // Bones
  76785. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76786. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76787. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76788. if (mesh.numBoneInfluencers > 4) {
  76789. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76790. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76791. }
  76792. var skeleton = mesh.skeleton;
  76793. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76794. if (skeleton.isUsingTextureForMatrices) {
  76795. defines.push("#define BONETEXTURE");
  76796. }
  76797. else {
  76798. defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1));
  76799. }
  76800. }
  76801. else {
  76802. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76803. }
  76804. // Morph targets
  76805. var manager = mesh.morphTargetManager;
  76806. var morphInfluencers = 0;
  76807. if (manager) {
  76808. if (manager.numInfluencers > 0) {
  76809. defines.push("#define MORPHTARGETS");
  76810. morphInfluencers = manager.numInfluencers;
  76811. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  76812. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  76813. }
  76814. }
  76815. // Instances
  76816. if (useInstances) {
  76817. defines.push("#define INSTANCES");
  76818. attribs.push("world0");
  76819. attribs.push("world1");
  76820. attribs.push("world2");
  76821. attribs.push("world3");
  76822. }
  76823. // Get correct effect
  76824. var join = defines.join("\n");
  76825. if (this._cachedDefines !== join) {
  76826. this._cachedDefines = join;
  76827. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences", "boneTextureWidth"], ["diffuseSampler", "boneSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  76828. }
  76829. if (!this._effect.isReady()) {
  76830. return false;
  76831. }
  76832. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  76833. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  76834. this._initializeBlurRTTAndPostProcesses();
  76835. }
  76836. }
  76837. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  76838. return false;
  76839. }
  76840. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  76841. return false;
  76842. }
  76843. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  76844. return false;
  76845. }
  76846. return true;
  76847. };
  76848. /**
  76849. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  76850. * @param defines Defines of the material we want to update
  76851. * @param lightIndex Index of the light in the enabled light list of the material
  76852. */
  76853. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  76854. var scene = this._scene;
  76855. var light = this._light;
  76856. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  76857. return;
  76858. }
  76859. defines["SHADOW" + lightIndex] = true;
  76860. if (this.useContactHardeningShadow) {
  76861. defines["SHADOWPCSS" + lightIndex] = true;
  76862. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  76863. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  76864. }
  76865. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  76866. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  76867. }
  76868. // else default to high.
  76869. }
  76870. if (this.usePercentageCloserFiltering) {
  76871. defines["SHADOWPCF" + lightIndex] = true;
  76872. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  76873. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  76874. }
  76875. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  76876. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  76877. }
  76878. // else default to high.
  76879. }
  76880. else if (this.usePoissonSampling) {
  76881. defines["SHADOWPOISSON" + lightIndex] = true;
  76882. }
  76883. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  76884. defines["SHADOWESM" + lightIndex] = true;
  76885. }
  76886. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  76887. defines["SHADOWCLOSEESM" + lightIndex] = true;
  76888. }
  76889. if (light.needCube()) {
  76890. defines["SHADOWCUBE" + lightIndex] = true;
  76891. }
  76892. };
  76893. /**
  76894. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  76895. * defined in the generator but impacting the effect).
  76896. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  76897. * @param effect The effect we are binfing the information for
  76898. */
  76899. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  76900. var light = this._light;
  76901. var scene = this._scene;
  76902. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  76903. return;
  76904. }
  76905. var camera = scene.activeCamera;
  76906. if (!camera) {
  76907. return;
  76908. }
  76909. var shadowMap = this.getShadowMap();
  76910. if (!shadowMap) {
  76911. return;
  76912. }
  76913. if (!light.needCube()) {
  76914. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  76915. }
  76916. // Only PCF uses depth stencil texture.
  76917. if (this._filter === ShadowGenerator.FILTER_PCF) {
  76918. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  76919. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  76920. }
  76921. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  76922. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  76923. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  76924. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  76925. }
  76926. else {
  76927. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  76928. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  76929. }
  76930. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  76931. };
  76932. /**
  76933. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  76934. * (eq to shadow prjection matrix * light transform matrix)
  76935. * @returns The transform matrix used to create the shadow map
  76936. */
  76937. ShadowGenerator.prototype.getTransformMatrix = function () {
  76938. var scene = this._scene;
  76939. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  76940. return this._transformMatrix;
  76941. }
  76942. this._currentRenderID = scene.getRenderId();
  76943. this._currentFaceIndexCache = this._currentFaceIndex;
  76944. var lightPosition = this._light.position;
  76945. if (this._light.computeTransformedInformation()) {
  76946. lightPosition = this._light.transformedPosition;
  76947. }
  76948. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  76949. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  76950. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  76951. }
  76952. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  76953. this._cachedPosition.copyFrom(lightPosition);
  76954. this._cachedDirection.copyFrom(this._lightDirection);
  76955. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  76956. var shadowMap = this.getShadowMap();
  76957. if (shadowMap) {
  76958. var renderList = shadowMap.renderList;
  76959. if (renderList) {
  76960. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  76961. }
  76962. }
  76963. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  76964. }
  76965. return this._transformMatrix;
  76966. };
  76967. /**
  76968. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  76969. * Cube and 2D textures for instance.
  76970. */
  76971. ShadowGenerator.prototype.recreateShadowMap = function () {
  76972. var shadowMap = this._shadowMap;
  76973. if (!shadowMap) {
  76974. return;
  76975. }
  76976. // Track render list.
  76977. var renderList = shadowMap.renderList;
  76978. // Clean up existing data.
  76979. this._disposeRTTandPostProcesses();
  76980. // Reinitializes.
  76981. this._initializeGenerator();
  76982. // Reaffect the filter to ensure a correct fallback if necessary.
  76983. this.filter = this.filter;
  76984. // Reaffect the filter.
  76985. this._applyFilterValues();
  76986. // Reaffect Render List.
  76987. this._shadowMap.renderList = renderList;
  76988. };
  76989. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  76990. if (this._shadowMap2) {
  76991. this._shadowMap2.dispose();
  76992. this._shadowMap2 = null;
  76993. }
  76994. if (this._boxBlurPostprocess) {
  76995. this._boxBlurPostprocess.dispose();
  76996. this._boxBlurPostprocess = null;
  76997. }
  76998. if (this._kernelBlurXPostprocess) {
  76999. this._kernelBlurXPostprocess.dispose();
  77000. this._kernelBlurXPostprocess = null;
  77001. }
  77002. if (this._kernelBlurYPostprocess) {
  77003. this._kernelBlurYPostprocess.dispose();
  77004. this._kernelBlurYPostprocess = null;
  77005. }
  77006. this._blurPostProcesses = [];
  77007. };
  77008. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  77009. if (this._shadowMap) {
  77010. this._shadowMap.dispose();
  77011. this._shadowMap = null;
  77012. }
  77013. this._disposeBlurPostProcesses();
  77014. };
  77015. /**
  77016. * Disposes the ShadowGenerator.
  77017. * Returns nothing.
  77018. */
  77019. ShadowGenerator.prototype.dispose = function () {
  77020. this._disposeRTTandPostProcesses();
  77021. if (this._light) {
  77022. this._light._shadowGenerator = null;
  77023. this._light._markMeshesAsLightDirty();
  77024. }
  77025. };
  77026. /**
  77027. * Serializes the shadow generator setup to a json object.
  77028. * @returns The serialized JSON object
  77029. */
  77030. ShadowGenerator.prototype.serialize = function () {
  77031. var serializationObject = {};
  77032. var shadowMap = this.getShadowMap();
  77033. if (!shadowMap) {
  77034. return serializationObject;
  77035. }
  77036. serializationObject.lightId = this._light.id;
  77037. serializationObject.mapSize = shadowMap.getRenderSize();
  77038. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  77039. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  77040. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  77041. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  77042. serializationObject.usePoissonSampling = this.usePoissonSampling;
  77043. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  77044. serializationObject.depthScale = this.depthScale;
  77045. serializationObject.darkness = this.getDarkness();
  77046. serializationObject.blurBoxOffset = this.blurBoxOffset;
  77047. serializationObject.blurKernel = this.blurKernel;
  77048. serializationObject.blurScale = this.blurScale;
  77049. serializationObject.useKernelBlur = this.useKernelBlur;
  77050. serializationObject.transparencyShadow = this._transparencyShadow;
  77051. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  77052. serializationObject.bias = this.bias;
  77053. serializationObject.normalBias = this.normalBias;
  77054. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  77055. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  77056. serializationObject.filteringQuality = this.filteringQuality;
  77057. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  77058. serializationObject.renderList = [];
  77059. if (shadowMap.renderList) {
  77060. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  77061. var mesh = shadowMap.renderList[meshIndex];
  77062. serializationObject.renderList.push(mesh.id);
  77063. }
  77064. }
  77065. return serializationObject;
  77066. };
  77067. /**
  77068. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  77069. * @param parsedShadowGenerator The JSON object to parse
  77070. * @param scene The scene to create the shadow map for
  77071. * @returns The parsed shadow generator
  77072. */
  77073. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  77074. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  77075. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  77076. var shadowMap = shadowGenerator.getShadowMap();
  77077. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  77078. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  77079. meshes.forEach(function (mesh) {
  77080. if (!shadowMap) {
  77081. return;
  77082. }
  77083. if (!shadowMap.renderList) {
  77084. shadowMap.renderList = [];
  77085. }
  77086. shadowMap.renderList.push(mesh);
  77087. });
  77088. }
  77089. if (parsedShadowGenerator.usePoissonSampling) {
  77090. shadowGenerator.usePoissonSampling = true;
  77091. }
  77092. else if (parsedShadowGenerator.useExponentialShadowMap) {
  77093. shadowGenerator.useExponentialShadowMap = true;
  77094. }
  77095. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  77096. shadowGenerator.useBlurExponentialShadowMap = true;
  77097. }
  77098. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  77099. shadowGenerator.useCloseExponentialShadowMap = true;
  77100. }
  77101. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  77102. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  77103. }
  77104. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  77105. shadowGenerator.usePercentageCloserFiltering = true;
  77106. }
  77107. else if (parsedShadowGenerator.useContactHardeningShadow) {
  77108. shadowGenerator.useContactHardeningShadow = true;
  77109. }
  77110. if (parsedShadowGenerator.filteringQuality) {
  77111. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  77112. }
  77113. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  77114. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  77115. }
  77116. // Backward compat
  77117. else if (parsedShadowGenerator.useVarianceShadowMap) {
  77118. shadowGenerator.useExponentialShadowMap = true;
  77119. }
  77120. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  77121. shadowGenerator.useBlurExponentialShadowMap = true;
  77122. }
  77123. if (parsedShadowGenerator.depthScale) {
  77124. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  77125. }
  77126. if (parsedShadowGenerator.blurScale) {
  77127. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  77128. }
  77129. if (parsedShadowGenerator.blurBoxOffset) {
  77130. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  77131. }
  77132. if (parsedShadowGenerator.useKernelBlur) {
  77133. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  77134. }
  77135. if (parsedShadowGenerator.blurKernel) {
  77136. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  77137. }
  77138. if (parsedShadowGenerator.bias !== undefined) {
  77139. shadowGenerator.bias = parsedShadowGenerator.bias;
  77140. }
  77141. if (parsedShadowGenerator.normalBias !== undefined) {
  77142. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  77143. }
  77144. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  77145. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  77146. }
  77147. if (parsedShadowGenerator.darkness) {
  77148. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  77149. }
  77150. if (parsedShadowGenerator.transparencyShadow) {
  77151. shadowGenerator.setTransparencyShadow(true);
  77152. }
  77153. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  77154. return shadowGenerator;
  77155. };
  77156. /**
  77157. * Shadow generator mode None: no filtering applied.
  77158. */
  77159. ShadowGenerator.FILTER_NONE = 0;
  77160. /**
  77161. * Shadow generator mode ESM: Exponential Shadow Mapping.
  77162. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  77163. */
  77164. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  77165. /**
  77166. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  77167. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  77168. */
  77169. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  77170. /**
  77171. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  77172. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  77173. */
  77174. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  77175. /**
  77176. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  77177. * edge artifacts on steep falloff.
  77178. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  77179. */
  77180. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  77181. /**
  77182. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  77183. * edge artifacts on steep falloff.
  77184. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  77185. */
  77186. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  77187. /**
  77188. * Shadow generator mode PCF: Percentage Closer Filtering
  77189. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  77190. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  77191. */
  77192. ShadowGenerator.FILTER_PCF = 6;
  77193. /**
  77194. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  77195. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  77196. * Contact Hardening
  77197. */
  77198. ShadowGenerator.FILTER_PCSS = 7;
  77199. /**
  77200. * Reserved for PCF and PCSS
  77201. * Highest Quality.
  77202. *
  77203. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  77204. *
  77205. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  77206. */
  77207. ShadowGenerator.QUALITY_HIGH = 0;
  77208. /**
  77209. * Reserved for PCF and PCSS
  77210. * Good tradeoff for quality/perf cross devices
  77211. *
  77212. * Execute PCF on a 3*3 kernel.
  77213. *
  77214. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  77215. */
  77216. ShadowGenerator.QUALITY_MEDIUM = 1;
  77217. /**
  77218. * Reserved for PCF and PCSS
  77219. * The lowest quality but the fastest.
  77220. *
  77221. * Execute PCF on a 1*1 kernel.
  77222. *
  77223. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  77224. */
  77225. ShadowGenerator.QUALITY_LOW = 2;
  77226. return ShadowGenerator;
  77227. }());
  77228. BABYLON.ShadowGenerator = ShadowGenerator;
  77229. })(BABYLON || (BABYLON = {}));
  77230. //# sourceMappingURL=shadowGenerator.js.map
  77231. var BABYLON;
  77232. (function (BABYLON) {
  77233. // Adds the parser to the scene parsers.
  77234. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  77235. // Shadows
  77236. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  77237. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  77238. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  77239. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  77240. // SG would be available on their associated lights
  77241. }
  77242. }
  77243. });
  77244. /**
  77245. * Defines the shadow generator component responsible to manage any shadow generators
  77246. * in a given scene.
  77247. */
  77248. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  77249. /**
  77250. * Creates a new instance of the component for the given scene
  77251. * @param scene Defines the scene to register the component in
  77252. */
  77253. function ShadowGeneratorSceneComponent(scene) {
  77254. /**
  77255. * The component name helpfull to identify the component in the list of scene components.
  77256. */
  77257. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  77258. this.scene = scene;
  77259. }
  77260. /**
  77261. * Registers the component in a given scene
  77262. */
  77263. ShadowGeneratorSceneComponent.prototype.register = function () {
  77264. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  77265. };
  77266. /**
  77267. * Rebuilds the elements related to this component in case of
  77268. * context lost for instance.
  77269. */
  77270. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  77271. // Nothing To Do Here.
  77272. };
  77273. /**
  77274. * Serializes the component data to the specified json object
  77275. * @param serializationObject The object to serialize to
  77276. */
  77277. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  77278. // Shadows
  77279. serializationObject.shadowGenerators = [];
  77280. var lights = this.scene.lights;
  77281. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  77282. var light = lights_1[_i];
  77283. var shadowGenerator = light.getShadowGenerator();
  77284. if (shadowGenerator) {
  77285. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  77286. }
  77287. }
  77288. };
  77289. /**
  77290. * Adds all the element from the container to the scene
  77291. * @param container the container holding the elements
  77292. */
  77293. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  77294. // Nothing To Do Here. (directly attached to a light)
  77295. };
  77296. /**
  77297. * Removes all the elements in the container from the scene
  77298. * @param container contains the elements to remove
  77299. */
  77300. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  77301. // Nothing To Do Here. (directly attached to a light)
  77302. };
  77303. /**
  77304. * Rebuilds the elements related to this component in case of
  77305. * context lost for instance.
  77306. */
  77307. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  77308. // Nothing To Do Here.
  77309. };
  77310. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77311. // Shadows
  77312. var scene = this.scene;
  77313. if (this.scene.shadowsEnabled) {
  77314. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  77315. var light = scene.lights[lightIndex];
  77316. var shadowGenerator = light.getShadowGenerator();
  77317. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  77318. var shadowMap = (shadowGenerator.getShadowMap());
  77319. if (scene.textures.indexOf(shadowMap) !== -1) {
  77320. renderTargets.push(shadowMap);
  77321. }
  77322. }
  77323. }
  77324. }
  77325. };
  77326. return ShadowGeneratorSceneComponent;
  77327. }());
  77328. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  77329. })(BABYLON || (BABYLON = {}));
  77330. //# sourceMappingURL=shadowGeneratorSceneComponent.js.map
  77331. var BABYLON;
  77332. (function (BABYLON) {
  77333. /**
  77334. * Class used for the default loading screen
  77335. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  77336. */
  77337. var DefaultLoadingScreen = /** @class */ (function () {
  77338. /**
  77339. * Creates a new default loading screen
  77340. * @param _renderingCanvas defines the canvas used to render the scene
  77341. * @param _loadingText defines the default text to display
  77342. * @param _loadingDivBackgroundColor defines the default background color
  77343. */
  77344. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  77345. if (_loadingText === void 0) { _loadingText = ""; }
  77346. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  77347. var _this = this;
  77348. this._renderingCanvas = _renderingCanvas;
  77349. this._loadingText = _loadingText;
  77350. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  77351. // Resize
  77352. this._resizeLoadingUI = function () {
  77353. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  77354. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  77355. if (!_this._loadingDiv) {
  77356. return;
  77357. }
  77358. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  77359. _this._loadingDiv.style.left = canvasRect.left + "px";
  77360. _this._loadingDiv.style.top = canvasRect.top + "px";
  77361. _this._loadingDiv.style.width = canvasRect.width + "px";
  77362. _this._loadingDiv.style.height = canvasRect.height + "px";
  77363. };
  77364. }
  77365. /**
  77366. * Function called to display the loading screen
  77367. */
  77368. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  77369. if (this._loadingDiv) {
  77370. // Do not add a loading screen if there is already one
  77371. return;
  77372. }
  77373. this._loadingDiv = document.createElement("div");
  77374. this._loadingDiv.id = "babylonjsLoadingDiv";
  77375. this._loadingDiv.style.opacity = "0";
  77376. this._loadingDiv.style.transition = "opacity 1.5s ease";
  77377. this._loadingDiv.style.pointerEvents = "none";
  77378. // Loading text
  77379. this._loadingTextDiv = document.createElement("div");
  77380. this._loadingTextDiv.style.position = "absolute";
  77381. this._loadingTextDiv.style.left = "0";
  77382. this._loadingTextDiv.style.top = "50%";
  77383. this._loadingTextDiv.style.marginTop = "80px";
  77384. this._loadingTextDiv.style.width = "100%";
  77385. this._loadingTextDiv.style.height = "20px";
  77386. this._loadingTextDiv.style.fontFamily = "Arial";
  77387. this._loadingTextDiv.style.fontSize = "14px";
  77388. this._loadingTextDiv.style.color = "white";
  77389. this._loadingTextDiv.style.textAlign = "center";
  77390. this._loadingTextDiv.innerHTML = "Loading";
  77391. this._loadingDiv.appendChild(this._loadingTextDiv);
  77392. //set the predefined text
  77393. this._loadingTextDiv.innerHTML = this._loadingText;
  77394. // Generating keyframes
  77395. var style = document.createElement('style');
  77396. style.type = 'text/css';
  77397. 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 }";
  77398. style.innerHTML = keyFrames;
  77399. document.getElementsByTagName('head')[0].appendChild(style);
  77400. // Loading img
  77401. var imgBack = new Image();
  77402. 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";
  77403. imgBack.style.position = "absolute";
  77404. imgBack.style.left = "50%";
  77405. imgBack.style.top = "50%";
  77406. imgBack.style.marginLeft = "-60px";
  77407. imgBack.style.marginTop = "-60px";
  77408. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  77409. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  77410. imgBack.style.transformOrigin = "50% 50%";
  77411. imgBack.style.webkitTransformOrigin = "50% 50%";
  77412. this._loadingDiv.appendChild(imgBack);
  77413. this._resizeLoadingUI();
  77414. window.addEventListener("resize", this._resizeLoadingUI);
  77415. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  77416. document.body.appendChild(this._loadingDiv);
  77417. this._loadingDiv.style.opacity = "1";
  77418. };
  77419. /**
  77420. * Function called to hide the loading screen
  77421. */
  77422. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  77423. var _this = this;
  77424. if (!this._loadingDiv) {
  77425. return;
  77426. }
  77427. var onTransitionEnd = function () {
  77428. if (!_this._loadingDiv) {
  77429. return;
  77430. }
  77431. document.body.removeChild(_this._loadingDiv);
  77432. window.removeEventListener("resize", _this._resizeLoadingUI);
  77433. _this._loadingDiv = null;
  77434. };
  77435. this._loadingDiv.style.opacity = "0";
  77436. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  77437. };
  77438. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  77439. get: function () {
  77440. return this._loadingText;
  77441. },
  77442. /**
  77443. * Gets or sets the text to display while loading
  77444. */
  77445. set: function (text) {
  77446. this._loadingText = text;
  77447. if (this._loadingTextDiv) {
  77448. this._loadingTextDiv.innerHTML = this._loadingText;
  77449. }
  77450. },
  77451. enumerable: true,
  77452. configurable: true
  77453. });
  77454. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  77455. /**
  77456. * Gets or sets the color to use for the background
  77457. */
  77458. get: function () {
  77459. return this._loadingDivBackgroundColor;
  77460. },
  77461. set: function (color) {
  77462. this._loadingDivBackgroundColor = color;
  77463. if (!this._loadingDiv) {
  77464. return;
  77465. }
  77466. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  77467. },
  77468. enumerable: true,
  77469. configurable: true
  77470. });
  77471. return DefaultLoadingScreen;
  77472. }());
  77473. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  77474. })(BABYLON || (BABYLON = {}));
  77475. //# sourceMappingURL=loadingScreen.js.map
  77476. var BABYLON;
  77477. (function (BABYLON) {
  77478. /**
  77479. * Class used to represent data loading progression
  77480. */
  77481. var SceneLoaderProgressEvent = /** @class */ (function () {
  77482. /**
  77483. * Create a new progress event
  77484. * @param lengthComputable defines if data length to load can be evaluated
  77485. * @param loaded defines the loaded data length
  77486. * @param total defines the data length to load
  77487. */
  77488. function SceneLoaderProgressEvent(
  77489. /** defines if data length to load can be evaluated */
  77490. lengthComputable,
  77491. /** defines the loaded data length */
  77492. loaded,
  77493. /** defines the data length to load */
  77494. total) {
  77495. this.lengthComputable = lengthComputable;
  77496. this.loaded = loaded;
  77497. this.total = total;
  77498. }
  77499. /**
  77500. * Creates a new SceneLoaderProgressEvent from a ProgressEvent
  77501. * @param event defines the source event
  77502. * @returns a new SceneLoaderProgressEvent
  77503. */
  77504. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  77505. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  77506. };
  77507. return SceneLoaderProgressEvent;
  77508. }());
  77509. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  77510. /**
  77511. * Class used to load scene from various file formats using registered plugins
  77512. * @see http://doc.babylonjs.com/how_to/load_from_any_file_type
  77513. */
  77514. var SceneLoader = /** @class */ (function () {
  77515. function SceneLoader() {
  77516. }
  77517. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  77518. /**
  77519. * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data
  77520. */
  77521. get: function () {
  77522. return SceneLoader._ForceFullSceneLoadingForIncremental;
  77523. },
  77524. set: function (value) {
  77525. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  77526. },
  77527. enumerable: true,
  77528. configurable: true
  77529. });
  77530. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  77531. /**
  77532. * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene
  77533. */
  77534. get: function () {
  77535. return SceneLoader._ShowLoadingScreen;
  77536. },
  77537. set: function (value) {
  77538. SceneLoader._ShowLoadingScreen = value;
  77539. },
  77540. enumerable: true,
  77541. configurable: true
  77542. });
  77543. Object.defineProperty(SceneLoader, "loggingLevel", {
  77544. /**
  77545. * Defines the current logging level (while loading the scene)
  77546. * @ignorenaming
  77547. */
  77548. get: function () {
  77549. return SceneLoader._loggingLevel;
  77550. },
  77551. set: function (value) {
  77552. SceneLoader._loggingLevel = value;
  77553. },
  77554. enumerable: true,
  77555. configurable: true
  77556. });
  77557. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  77558. /**
  77559. * Gets or set a boolean indicating if matrix weights must be cleaned upon loading
  77560. */
  77561. get: function () {
  77562. return SceneLoader._CleanBoneMatrixWeights;
  77563. },
  77564. set: function (value) {
  77565. SceneLoader._CleanBoneMatrixWeights = value;
  77566. },
  77567. enumerable: true,
  77568. configurable: true
  77569. });
  77570. SceneLoader._getDefaultPlugin = function () {
  77571. return SceneLoader._registeredPlugins[".babylon"];
  77572. };
  77573. SceneLoader._getPluginForExtension = function (extension) {
  77574. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  77575. if (registeredPlugin) {
  77576. return registeredPlugin;
  77577. }
  77578. 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");
  77579. return SceneLoader._getDefaultPlugin();
  77580. };
  77581. SceneLoader._getPluginForDirectLoad = function (data) {
  77582. for (var extension in SceneLoader._registeredPlugins) {
  77583. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  77584. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  77585. return SceneLoader._registeredPlugins[extension];
  77586. }
  77587. }
  77588. return SceneLoader._getDefaultPlugin();
  77589. };
  77590. SceneLoader._getPluginForFilename = function (sceneFilename) {
  77591. var queryStringPosition = sceneFilename.indexOf("?");
  77592. if (queryStringPosition !== -1) {
  77593. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  77594. }
  77595. var dotPosition = sceneFilename.lastIndexOf(".");
  77596. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  77597. return SceneLoader._getPluginForExtension(extension);
  77598. };
  77599. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  77600. SceneLoader._getDirectLoad = function (sceneFilename) {
  77601. if (sceneFilename.substr(0, 5) === "data:") {
  77602. return sceneFilename.substr(5);
  77603. }
  77604. return null;
  77605. };
  77606. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  77607. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  77608. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  77609. var plugin;
  77610. if (registeredPlugin.plugin.createPlugin) {
  77611. plugin = registeredPlugin.plugin.createPlugin();
  77612. }
  77613. else {
  77614. plugin = registeredPlugin.plugin;
  77615. }
  77616. var useArrayBuffer = registeredPlugin.isBinary;
  77617. var offlineProvider;
  77618. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  77619. var dataCallback = function (data, responseURL) {
  77620. if (scene.isDisposed) {
  77621. onError("Scene has been disposed");
  77622. return;
  77623. }
  77624. scene.offlineProvider = offlineProvider;
  77625. onSuccess(plugin, data, responseURL);
  77626. };
  77627. var request = null;
  77628. var pluginDisposed = false;
  77629. var onDisposeObservable = plugin.onDisposeObservable;
  77630. if (onDisposeObservable) {
  77631. onDisposeObservable.add(function () {
  77632. pluginDisposed = true;
  77633. if (request) {
  77634. request.abort();
  77635. request = null;
  77636. }
  77637. onDispose();
  77638. });
  77639. }
  77640. var manifestChecked = function () {
  77641. if (pluginDisposed) {
  77642. return;
  77643. }
  77644. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  77645. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  77646. } : undefined, offlineProvider, useArrayBuffer, function (request, exception) {
  77647. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  77648. });
  77649. };
  77650. if (directLoad) {
  77651. dataCallback(directLoad);
  77652. return plugin;
  77653. }
  77654. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  77655. var engine = scene.getEngine();
  77656. var canUseOfflineSupport = engine.enableOfflineSupport;
  77657. if (canUseOfflineSupport) {
  77658. // Also check for exceptions
  77659. var exceptionFound = false;
  77660. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  77661. var regex = _a[_i];
  77662. if (regex.test(fileInfo.url)) {
  77663. exceptionFound = true;
  77664. break;
  77665. }
  77666. }
  77667. canUseOfflineSupport = !exceptionFound;
  77668. }
  77669. if (canUseOfflineSupport && BABYLON.Engine.OfflineProviderFactory) {
  77670. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  77671. offlineProvider = BABYLON.Engine.OfflineProviderFactory(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  77672. }
  77673. else {
  77674. manifestChecked();
  77675. }
  77676. }
  77677. // Loading file from disk via input file or drag'n'drop
  77678. else {
  77679. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  77680. if (file) {
  77681. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  77682. }
  77683. else {
  77684. onError("Unable to find file named " + fileInfo.name);
  77685. }
  77686. }
  77687. return plugin;
  77688. };
  77689. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  77690. var url;
  77691. var name;
  77692. if (!sceneFilename) {
  77693. url = rootUrl;
  77694. name = BABYLON.Tools.GetFilename(rootUrl);
  77695. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  77696. }
  77697. else {
  77698. if (sceneFilename.substr(0, 1) === "/") {
  77699. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  77700. return null;
  77701. }
  77702. url = rootUrl + sceneFilename;
  77703. name = sceneFilename;
  77704. }
  77705. return {
  77706. url: url,
  77707. rootUrl: rootUrl,
  77708. name: name
  77709. };
  77710. };
  77711. // Public functions
  77712. /**
  77713. * Gets a plugin that can load the given extension
  77714. * @param extension defines the extension to load
  77715. * @returns a plugin or null if none works
  77716. */
  77717. SceneLoader.GetPluginForExtension = function (extension) {
  77718. return SceneLoader._getPluginForExtension(extension).plugin;
  77719. };
  77720. /**
  77721. * Gets a boolean indicating that the given extension can be loaded
  77722. * @param extension defines the extension to load
  77723. * @returns true if the extension is supported
  77724. */
  77725. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  77726. return !!SceneLoader._registeredPlugins[extension];
  77727. };
  77728. /**
  77729. * Adds a new plugin to the list of registered plugins
  77730. * @param plugin defines the plugin to add
  77731. */
  77732. SceneLoader.RegisterPlugin = function (plugin) {
  77733. if (typeof plugin.extensions === "string") {
  77734. var extension = plugin.extensions;
  77735. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  77736. plugin: plugin,
  77737. isBinary: false
  77738. };
  77739. }
  77740. else {
  77741. var extensions = plugin.extensions;
  77742. Object.keys(extensions).forEach(function (extension) {
  77743. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  77744. plugin: plugin,
  77745. isBinary: extensions[extension].isBinary
  77746. };
  77747. });
  77748. }
  77749. };
  77750. /**
  77751. * Import meshes into a scene
  77752. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  77753. * @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)
  77754. * @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)
  77755. * @param scene the instance of BABYLON.Scene to append to
  77756. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  77757. * @param onProgress a callback with a progress event for each file being loaded
  77758. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  77759. * @param pluginExtension the extension used to determine the plugin
  77760. * @returns The loaded plugin
  77761. */
  77762. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  77763. if (sceneFilename === void 0) { sceneFilename = ""; }
  77764. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77765. if (onSuccess === void 0) { onSuccess = null; }
  77766. if (onProgress === void 0) { onProgress = null; }
  77767. if (onError === void 0) { onError = null; }
  77768. if (pluginExtension === void 0) { pluginExtension = null; }
  77769. if (!scene) {
  77770. BABYLON.Tools.Error("No scene available to import mesh to");
  77771. return null;
  77772. }
  77773. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  77774. if (!fileInfo) {
  77775. return null;
  77776. }
  77777. var loadingToken = {};
  77778. scene._addPendingData(loadingToken);
  77779. var disposeHandler = function () {
  77780. scene._removePendingData(loadingToken);
  77781. };
  77782. var errorHandler = function (message, exception) {
  77783. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  77784. if (onError) {
  77785. onError(scene, errorMessage, exception);
  77786. }
  77787. else {
  77788. BABYLON.Tools.Error(errorMessage);
  77789. // should the exception be thrown?
  77790. }
  77791. disposeHandler();
  77792. };
  77793. var progressHandler = onProgress ? function (event) {
  77794. try {
  77795. onProgress(event);
  77796. }
  77797. catch (e) {
  77798. errorHandler("Error in onProgress callback", e);
  77799. }
  77800. } : undefined;
  77801. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  77802. scene.importedMeshesFiles.push(fileInfo.url);
  77803. if (onSuccess) {
  77804. try {
  77805. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  77806. }
  77807. catch (e) {
  77808. errorHandler("Error in onSuccess callback", e);
  77809. }
  77810. }
  77811. scene._removePendingData(loadingToken);
  77812. };
  77813. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  77814. if (plugin.rewriteRootURL) {
  77815. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  77816. }
  77817. if (plugin.importMesh) {
  77818. var syncedPlugin = plugin;
  77819. var meshes = new Array();
  77820. var particleSystems = new Array();
  77821. var skeletons = new Array();
  77822. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  77823. return;
  77824. }
  77825. scene.loadingPluginName = plugin.name;
  77826. successHandler(meshes, particleSystems, skeletons, []);
  77827. }
  77828. else {
  77829. var asyncedPlugin = plugin;
  77830. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  77831. scene.loadingPluginName = plugin.name;
  77832. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  77833. }).catch(function (error) {
  77834. errorHandler(error.message, error);
  77835. });
  77836. }
  77837. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  77838. };
  77839. /**
  77840. * Import meshes into a scene
  77841. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  77842. * @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)
  77843. * @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)
  77844. * @param scene the instance of BABYLON.Scene to append to
  77845. * @param onProgress a callback with a progress event for each file being loaded
  77846. * @param pluginExtension the extension used to determine the plugin
  77847. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  77848. */
  77849. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  77850. if (sceneFilename === void 0) { sceneFilename = ""; }
  77851. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77852. if (onProgress === void 0) { onProgress = null; }
  77853. if (pluginExtension === void 0) { pluginExtension = null; }
  77854. return new Promise(function (resolve, reject) {
  77855. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  77856. resolve({
  77857. meshes: meshes,
  77858. particleSystems: particleSystems,
  77859. skeletons: skeletons,
  77860. animationGroups: animationGroups
  77861. });
  77862. }, onProgress, function (scene, message, exception) {
  77863. reject(exception || new Error(message));
  77864. }, pluginExtension);
  77865. });
  77866. };
  77867. /**
  77868. * Load a scene
  77869. * @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)
  77870. * @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)
  77871. * @param engine is the instance of BABYLON.Engine to use to create the scene
  77872. * @param onSuccess a callback with the scene when import succeeds
  77873. * @param onProgress a callback with a progress event for each file being loaded
  77874. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  77875. * @param pluginExtension the extension used to determine the plugin
  77876. * @returns The loaded plugin
  77877. */
  77878. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  77879. if (onSuccess === void 0) { onSuccess = null; }
  77880. if (onProgress === void 0) { onProgress = null; }
  77881. if (onError === void 0) { onError = null; }
  77882. if (pluginExtension === void 0) { pluginExtension = null; }
  77883. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  77884. };
  77885. /**
  77886. * Load a scene
  77887. * @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)
  77888. * @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)
  77889. * @param engine is the instance of BABYLON.Engine to use to create the scene
  77890. * @param onProgress a callback with a progress event for each file being loaded
  77891. * @param pluginExtension the extension used to determine the plugin
  77892. * @returns The loaded scene
  77893. */
  77894. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  77895. if (onProgress === void 0) { onProgress = null; }
  77896. if (pluginExtension === void 0) { pluginExtension = null; }
  77897. return new Promise(function (resolve, reject) {
  77898. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  77899. resolve(scene);
  77900. }, onProgress, function (scene, message, exception) {
  77901. reject(exception || new Error(message));
  77902. }, pluginExtension);
  77903. });
  77904. };
  77905. /**
  77906. * Append a scene
  77907. * @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)
  77908. * @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)
  77909. * @param scene is the instance of BABYLON.Scene to append to
  77910. * @param onSuccess a callback with the scene when import succeeds
  77911. * @param onProgress a callback with a progress event for each file being loaded
  77912. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  77913. * @param pluginExtension the extension used to determine the plugin
  77914. * @returns The loaded plugin
  77915. */
  77916. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  77917. if (sceneFilename === void 0) { sceneFilename = ""; }
  77918. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77919. if (onSuccess === void 0) { onSuccess = null; }
  77920. if (onProgress === void 0) { onProgress = null; }
  77921. if (onError === void 0) { onError = null; }
  77922. if (pluginExtension === void 0) { pluginExtension = null; }
  77923. if (!scene) {
  77924. BABYLON.Tools.Error("No scene available to append to");
  77925. return null;
  77926. }
  77927. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  77928. if (!fileInfo) {
  77929. return null;
  77930. }
  77931. if (SceneLoader.ShowLoadingScreen) {
  77932. scene.getEngine().displayLoadingUI();
  77933. }
  77934. var loadingToken = {};
  77935. scene._addPendingData(loadingToken);
  77936. var disposeHandler = function () {
  77937. scene._removePendingData(loadingToken);
  77938. scene.getEngine().hideLoadingUI();
  77939. };
  77940. var errorHandler = function (message, exception) {
  77941. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  77942. if (onError) {
  77943. onError(scene, errorMessage, exception);
  77944. }
  77945. else {
  77946. BABYLON.Tools.Error(errorMessage);
  77947. // should the exception be thrown?
  77948. }
  77949. disposeHandler();
  77950. };
  77951. var progressHandler = onProgress ? function (event) {
  77952. try {
  77953. onProgress(event);
  77954. }
  77955. catch (e) {
  77956. errorHandler("Error in onProgress callback", e);
  77957. }
  77958. } : undefined;
  77959. var successHandler = function () {
  77960. if (onSuccess) {
  77961. try {
  77962. onSuccess(scene);
  77963. }
  77964. catch (e) {
  77965. errorHandler("Error in onSuccess callback", e);
  77966. }
  77967. }
  77968. scene._removePendingData(loadingToken);
  77969. };
  77970. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  77971. if (plugin.load) {
  77972. var syncedPlugin = plugin;
  77973. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  77974. return;
  77975. }
  77976. scene.loadingPluginName = plugin.name;
  77977. successHandler();
  77978. }
  77979. else {
  77980. var asyncedPlugin = plugin;
  77981. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  77982. scene.loadingPluginName = plugin.name;
  77983. successHandler();
  77984. }).catch(function (error) {
  77985. errorHandler(error.message, error);
  77986. });
  77987. }
  77988. if (SceneLoader.ShowLoadingScreen) {
  77989. scene.executeWhenReady(function () {
  77990. scene.getEngine().hideLoadingUI();
  77991. });
  77992. }
  77993. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  77994. };
  77995. /**
  77996. * Append a scene
  77997. * @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)
  77998. * @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)
  77999. * @param scene is the instance of BABYLON.Scene to append to
  78000. * @param onProgress a callback with a progress event for each file being loaded
  78001. * @param pluginExtension the extension used to determine the plugin
  78002. * @returns The given scene
  78003. */
  78004. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  78005. if (sceneFilename === void 0) { sceneFilename = ""; }
  78006. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  78007. if (onProgress === void 0) { onProgress = null; }
  78008. if (pluginExtension === void 0) { pluginExtension = null; }
  78009. return new Promise(function (resolve, reject) {
  78010. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  78011. resolve(scene);
  78012. }, onProgress, function (scene, message, exception) {
  78013. reject(exception || new Error(message));
  78014. }, pluginExtension);
  78015. });
  78016. };
  78017. /**
  78018. * Load a scene into an asset container
  78019. * @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)
  78020. * @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)
  78021. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  78022. * @param onSuccess a callback with the scene when import succeeds
  78023. * @param onProgress a callback with a progress event for each file being loaded
  78024. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  78025. * @param pluginExtension the extension used to determine the plugin
  78026. * @returns The loaded plugin
  78027. */
  78028. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  78029. if (sceneFilename === void 0) { sceneFilename = ""; }
  78030. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  78031. if (onSuccess === void 0) { onSuccess = null; }
  78032. if (onProgress === void 0) { onProgress = null; }
  78033. if (onError === void 0) { onError = null; }
  78034. if (pluginExtension === void 0) { pluginExtension = null; }
  78035. if (!scene) {
  78036. BABYLON.Tools.Error("No scene available to load asset container to");
  78037. return null;
  78038. }
  78039. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  78040. if (!fileInfo) {
  78041. return null;
  78042. }
  78043. var loadingToken = {};
  78044. scene._addPendingData(loadingToken);
  78045. var disposeHandler = function () {
  78046. scene._removePendingData(loadingToken);
  78047. };
  78048. var errorHandler = function (message, exception) {
  78049. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  78050. if (onError) {
  78051. onError(scene, errorMessage, exception);
  78052. }
  78053. else {
  78054. BABYLON.Tools.Error(errorMessage);
  78055. // should the exception be thrown?
  78056. }
  78057. disposeHandler();
  78058. };
  78059. var progressHandler = onProgress ? function (event) {
  78060. try {
  78061. onProgress(event);
  78062. }
  78063. catch (e) {
  78064. errorHandler("Error in onProgress callback", e);
  78065. }
  78066. } : undefined;
  78067. var successHandler = function (assets) {
  78068. if (onSuccess) {
  78069. try {
  78070. onSuccess(assets);
  78071. }
  78072. catch (e) {
  78073. errorHandler("Error in onSuccess callback", e);
  78074. }
  78075. }
  78076. scene._removePendingData(loadingToken);
  78077. };
  78078. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  78079. if (plugin.loadAssetContainer) {
  78080. var syncedPlugin = plugin;
  78081. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  78082. if (!assetContainer) {
  78083. return;
  78084. }
  78085. scene.loadingPluginName = plugin.name;
  78086. successHandler(assetContainer);
  78087. }
  78088. else if (plugin.loadAssetContainerAsync) {
  78089. var asyncedPlugin = plugin;
  78090. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  78091. scene.loadingPluginName = plugin.name;
  78092. successHandler(assetContainer);
  78093. }).catch(function (error) {
  78094. errorHandler(error.message, error);
  78095. });
  78096. }
  78097. else {
  78098. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  78099. }
  78100. if (SceneLoader.ShowLoadingScreen) {
  78101. scene.executeWhenReady(function () {
  78102. scene.getEngine().hideLoadingUI();
  78103. });
  78104. }
  78105. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  78106. };
  78107. /**
  78108. * Load a scene into an asset container
  78109. * @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)
  78110. * @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)
  78111. * @param scene is the instance of BABYLON.Scene to append to
  78112. * @param onProgress a callback with a progress event for each file being loaded
  78113. * @param pluginExtension the extension used to determine the plugin
  78114. * @returns The loaded asset container
  78115. */
  78116. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  78117. if (sceneFilename === void 0) { sceneFilename = ""; }
  78118. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  78119. if (onProgress === void 0) { onProgress = null; }
  78120. if (pluginExtension === void 0) { pluginExtension = null; }
  78121. return new Promise(function (resolve, reject) {
  78122. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  78123. resolve(assetContainer);
  78124. }, onProgress, function (scene, message, exception) {
  78125. reject(exception || new Error(message));
  78126. }, pluginExtension);
  78127. });
  78128. };
  78129. // Flags
  78130. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  78131. SceneLoader._ShowLoadingScreen = true;
  78132. SceneLoader._CleanBoneMatrixWeights = false;
  78133. /**
  78134. * No logging while loading
  78135. */
  78136. SceneLoader.NO_LOGGING = 0;
  78137. /**
  78138. * Minimal logging while loading
  78139. */
  78140. SceneLoader.MINIMAL_LOGGING = 1;
  78141. /**
  78142. * Summary logging while loading
  78143. */
  78144. SceneLoader.SUMMARY_LOGGING = 2;
  78145. /**
  78146. * Detailled logging while loading
  78147. */
  78148. SceneLoader.DETAILED_LOGGING = 3;
  78149. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  78150. // Members
  78151. /**
  78152. * Event raised when a plugin is used to load a scene
  78153. */
  78154. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  78155. SceneLoader._registeredPlugins = {};
  78156. return SceneLoader;
  78157. }());
  78158. BABYLON.SceneLoader = SceneLoader;
  78159. })(BABYLON || (BABYLON = {}));
  78160. //# sourceMappingURL=sceneLoader.js.map
  78161. var BABYLON;
  78162. (function (BABYLON) {
  78163. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  78164. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  78165. var parsedMaterial = parsedData.materials[index];
  78166. if (parsedMaterial.id === id) {
  78167. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  78168. }
  78169. }
  78170. return null;
  78171. };
  78172. var isDescendantOf = function (mesh, names, hierarchyIds) {
  78173. for (var i in names) {
  78174. if (mesh.name === names[i]) {
  78175. hierarchyIds.push(mesh.id);
  78176. return true;
  78177. }
  78178. }
  78179. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  78180. hierarchyIds.push(mesh.id);
  78181. return true;
  78182. }
  78183. return false;
  78184. };
  78185. var logOperation = function (operation, producer) {
  78186. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  78187. };
  78188. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  78189. if (addToScene === void 0) { addToScene = false; }
  78190. var container = new BABYLON.AssetContainer(scene);
  78191. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  78192. // when SceneLoader.debugLogging = true (default), or exception encountered.
  78193. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  78194. // and avoid problems with multiple concurrent .babylon loads.
  78195. var log = "importScene has failed JSON parse";
  78196. try {
  78197. var parsedData = JSON.parse(data);
  78198. log = "";
  78199. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  78200. var index;
  78201. var cache;
  78202. // Lights
  78203. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  78204. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  78205. var parsedLight = parsedData.lights[index];
  78206. var light = BABYLON.Light.Parse(parsedLight, scene);
  78207. if (light) {
  78208. container.lights.push(light);
  78209. log += (index === 0 ? "\n\tLights:" : "");
  78210. log += "\n\t\t" + light.toString(fullDetails);
  78211. }
  78212. }
  78213. }
  78214. // Animations
  78215. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  78216. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  78217. var parsedAnimation = parsedData.animations[index];
  78218. var animation = BABYLON.Animation.Parse(parsedAnimation);
  78219. scene.animations.push(animation);
  78220. container.animations.push(animation);
  78221. log += (index === 0 ? "\n\tAnimations:" : "");
  78222. log += "\n\t\t" + animation.toString(fullDetails);
  78223. }
  78224. }
  78225. // Materials
  78226. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  78227. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  78228. var parsedMaterial = parsedData.materials[index];
  78229. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  78230. container.materials.push(mat);
  78231. log += (index === 0 ? "\n\tMaterials:" : "");
  78232. log += "\n\t\t" + mat.toString(fullDetails);
  78233. }
  78234. }
  78235. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  78236. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  78237. var parsedMultiMaterial = parsedData.multiMaterials[index];
  78238. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  78239. container.multiMaterials.push(mmat);
  78240. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  78241. log += "\n\t\t" + mmat.toString(fullDetails);
  78242. }
  78243. }
  78244. // Morph targets
  78245. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  78246. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  78247. var managerData = _a[_i];
  78248. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  78249. }
  78250. }
  78251. // Skeletons
  78252. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  78253. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  78254. var parsedSkeleton = parsedData.skeletons[index];
  78255. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  78256. container.skeletons.push(skeleton);
  78257. log += (index === 0 ? "\n\tSkeletons:" : "");
  78258. log += "\n\t\t" + skeleton.toString(fullDetails);
  78259. }
  78260. }
  78261. // Geometries
  78262. var geometries = parsedData.geometries;
  78263. if (geometries !== undefined && geometries !== null) {
  78264. var addedGeometry = new Array();
  78265. // Boxes
  78266. var boxes = geometries.boxes;
  78267. if (boxes !== undefined && boxes !== null) {
  78268. for (index = 0, cache = boxes.length; index < cache; index++) {
  78269. var parsedBox = boxes[index];
  78270. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  78271. }
  78272. }
  78273. // Spheres
  78274. var spheres = geometries.spheres;
  78275. if (spheres !== undefined && spheres !== null) {
  78276. for (index = 0, cache = spheres.length; index < cache; index++) {
  78277. var parsedSphere = spheres[index];
  78278. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  78279. }
  78280. }
  78281. // Cylinders
  78282. var cylinders = geometries.cylinders;
  78283. if (cylinders !== undefined && cylinders !== null) {
  78284. for (index = 0, cache = cylinders.length; index < cache; index++) {
  78285. var parsedCylinder = cylinders[index];
  78286. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  78287. }
  78288. }
  78289. // Toruses
  78290. var toruses = geometries.toruses;
  78291. if (toruses !== undefined && toruses !== null) {
  78292. for (index = 0, cache = toruses.length; index < cache; index++) {
  78293. var parsedTorus = toruses[index];
  78294. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  78295. }
  78296. }
  78297. // Grounds
  78298. var grounds = geometries.grounds;
  78299. if (grounds !== undefined && grounds !== null) {
  78300. for (index = 0, cache = grounds.length; index < cache; index++) {
  78301. var parsedGround = grounds[index];
  78302. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  78303. }
  78304. }
  78305. // Planes
  78306. var planes = geometries.planes;
  78307. if (planes !== undefined && planes !== null) {
  78308. for (index = 0, cache = planes.length; index < cache; index++) {
  78309. var parsedPlane = planes[index];
  78310. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  78311. }
  78312. }
  78313. // TorusKnots
  78314. var torusKnots = geometries.torusKnots;
  78315. if (torusKnots !== undefined && torusKnots !== null) {
  78316. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  78317. var parsedTorusKnot = torusKnots[index];
  78318. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  78319. }
  78320. }
  78321. // VertexData
  78322. var vertexData = geometries.vertexData;
  78323. if (vertexData !== undefined && vertexData !== null) {
  78324. for (index = 0, cache = vertexData.length; index < cache; index++) {
  78325. var parsedVertexData = vertexData[index];
  78326. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  78327. }
  78328. }
  78329. addedGeometry.forEach(function (g) {
  78330. if (g) {
  78331. container.geometries.push(g);
  78332. }
  78333. });
  78334. }
  78335. // Transform nodes
  78336. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  78337. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  78338. var parsedTransformNode = parsedData.transformNodes[index];
  78339. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  78340. container.transformNodes.push(node);
  78341. }
  78342. }
  78343. // Meshes
  78344. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  78345. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  78346. var parsedMesh = parsedData.meshes[index];
  78347. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  78348. container.meshes.push(mesh);
  78349. log += (index === 0 ? "\n\tMeshes:" : "");
  78350. log += "\n\t\t" + mesh.toString(fullDetails);
  78351. }
  78352. }
  78353. // Cameras
  78354. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  78355. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  78356. var parsedCamera = parsedData.cameras[index];
  78357. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  78358. container.cameras.push(camera);
  78359. log += (index === 0 ? "\n\tCameras:" : "");
  78360. log += "\n\t\t" + camera.toString(fullDetails);
  78361. }
  78362. }
  78363. // Animation Groups
  78364. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  78365. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  78366. var parsedAnimationGroup = parsedData.animationGroups[index];
  78367. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  78368. container.animationGroups.push(animationGroup);
  78369. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  78370. log += "\n\t\t" + animationGroup.toString(fullDetails);
  78371. }
  78372. }
  78373. // Browsing all the graph to connect the dots
  78374. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  78375. var camera = scene.cameras[index];
  78376. if (camera._waitingParentId) {
  78377. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  78378. camera._waitingParentId = null;
  78379. }
  78380. }
  78381. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  78382. var light_1 = scene.lights[index];
  78383. if (light_1 && light_1._waitingParentId) {
  78384. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  78385. light_1._waitingParentId = null;
  78386. }
  78387. }
  78388. // Connect parents & children and parse actions
  78389. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  78390. var transformNode = scene.transformNodes[index];
  78391. if (transformNode._waitingParentId) {
  78392. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  78393. transformNode._waitingParentId = null;
  78394. }
  78395. }
  78396. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78397. var mesh = scene.meshes[index];
  78398. if (mesh._waitingParentId) {
  78399. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  78400. mesh._waitingParentId = null;
  78401. }
  78402. }
  78403. // freeze world matrix application
  78404. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78405. var currentMesh = scene.meshes[index];
  78406. if (currentMesh._waitingFreezeWorldMatrix) {
  78407. currentMesh.freezeWorldMatrix();
  78408. currentMesh._waitingFreezeWorldMatrix = null;
  78409. }
  78410. else {
  78411. currentMesh.computeWorldMatrix(true);
  78412. }
  78413. }
  78414. // Lights exclusions / inclusions
  78415. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  78416. var light_2 = scene.lights[index];
  78417. // Excluded check
  78418. if (light_2._excludedMeshesIds.length > 0) {
  78419. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  78420. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  78421. if (excludedMesh) {
  78422. light_2.excludedMeshes.push(excludedMesh);
  78423. }
  78424. }
  78425. light_2._excludedMeshesIds = [];
  78426. }
  78427. // Included check
  78428. if (light_2._includedOnlyMeshesIds.length > 0) {
  78429. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  78430. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  78431. if (includedOnlyMesh) {
  78432. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  78433. }
  78434. }
  78435. light_2._includedOnlyMeshesIds = [];
  78436. }
  78437. }
  78438. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  78439. // Actions (scene) Done last as it can access other objects.
  78440. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78441. var mesh = scene.meshes[index];
  78442. if (mesh._waitingActions) {
  78443. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  78444. mesh._waitingActions = null;
  78445. }
  78446. }
  78447. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  78448. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  78449. }
  78450. if (!addToScene) {
  78451. container.removeAllFromScene();
  78452. }
  78453. }
  78454. catch (err) {
  78455. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  78456. if (onError) {
  78457. onError(msg, err);
  78458. }
  78459. else {
  78460. BABYLON.Tools.Log(msg);
  78461. throw err;
  78462. }
  78463. }
  78464. finally {
  78465. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  78466. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  78467. }
  78468. }
  78469. return container;
  78470. };
  78471. BABYLON.SceneLoader.RegisterPlugin({
  78472. name: "babylon.js",
  78473. extensions: ".babylon",
  78474. canDirectLoad: function (data) {
  78475. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  78476. return true;
  78477. }
  78478. return false;
  78479. },
  78480. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  78481. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  78482. // when SceneLoader.debugLogging = true (default), or exception encountered.
  78483. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  78484. // and avoid problems with multiple concurrent .babylon loads.
  78485. var log = "importMesh has failed JSON parse";
  78486. try {
  78487. var parsedData = JSON.parse(data);
  78488. log = "";
  78489. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  78490. if (!meshesNames) {
  78491. meshesNames = null;
  78492. }
  78493. else if (!Array.isArray(meshesNames)) {
  78494. meshesNames = [meshesNames];
  78495. }
  78496. var hierarchyIds = new Array();
  78497. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  78498. var loadedSkeletonsIds = [];
  78499. var loadedMaterialsIds = [];
  78500. var index;
  78501. var cache;
  78502. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  78503. var parsedMesh = parsedData.meshes[index];
  78504. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  78505. if (meshesNames !== null) {
  78506. // Remove found mesh name from list.
  78507. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  78508. }
  78509. //Geometry?
  78510. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  78511. //does the file contain geometries?
  78512. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  78513. //find the correct geometry and add it to the scene
  78514. var found = false;
  78515. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  78516. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  78517. return;
  78518. }
  78519. else {
  78520. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  78521. if (parsedGeometryData.id === parsedMesh.geometryId) {
  78522. switch (geometryType) {
  78523. case "boxes":
  78524. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  78525. break;
  78526. case "spheres":
  78527. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  78528. break;
  78529. case "cylinders":
  78530. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  78531. break;
  78532. case "toruses":
  78533. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  78534. break;
  78535. case "grounds":
  78536. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  78537. break;
  78538. case "planes":
  78539. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  78540. break;
  78541. case "torusKnots":
  78542. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  78543. break;
  78544. case "vertexData":
  78545. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  78546. break;
  78547. }
  78548. found = true;
  78549. }
  78550. });
  78551. }
  78552. });
  78553. if (found === false) {
  78554. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  78555. }
  78556. }
  78557. }
  78558. // Material ?
  78559. if (parsedMesh.materialId) {
  78560. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  78561. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  78562. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  78563. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  78564. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  78565. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  78566. var subMatId = parsedMultiMaterial.materials[matIndex];
  78567. loadedMaterialsIds.push(subMatId);
  78568. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  78569. if (mat) {
  78570. log += "\n\tMaterial " + mat.toString(fullDetails);
  78571. }
  78572. }
  78573. loadedMaterialsIds.push(parsedMultiMaterial.id);
  78574. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  78575. if (mmat) {
  78576. materialFound = true;
  78577. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  78578. }
  78579. break;
  78580. }
  78581. }
  78582. }
  78583. if (materialFound === false) {
  78584. loadedMaterialsIds.push(parsedMesh.materialId);
  78585. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  78586. if (!mat) {
  78587. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  78588. }
  78589. else {
  78590. log += "\n\tMaterial " + mat.toString(fullDetails);
  78591. }
  78592. }
  78593. }
  78594. // Skeleton ?
  78595. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  78596. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  78597. if (skeletonAlreadyLoaded === false) {
  78598. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  78599. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  78600. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  78601. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  78602. skeletons.push(skeleton);
  78603. loadedSkeletonsIds.push(parsedSkeleton.id);
  78604. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  78605. }
  78606. }
  78607. }
  78608. }
  78609. // Morph targets ?
  78610. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  78611. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  78612. var managerData = _a[_i];
  78613. BABYLON.MorphTargetManager.Parse(managerData, scene);
  78614. }
  78615. }
  78616. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  78617. meshes.push(mesh);
  78618. log += "\n\tMesh " + mesh.toString(fullDetails);
  78619. }
  78620. }
  78621. // Connecting parents
  78622. var currentMesh;
  78623. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78624. currentMesh = scene.meshes[index];
  78625. if (currentMesh._waitingParentId) {
  78626. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  78627. currentMesh._waitingParentId = null;
  78628. }
  78629. }
  78630. // freeze and compute world matrix application
  78631. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  78632. currentMesh = scene.meshes[index];
  78633. if (currentMesh._waitingFreezeWorldMatrix) {
  78634. currentMesh.freezeWorldMatrix();
  78635. currentMesh._waitingFreezeWorldMatrix = null;
  78636. }
  78637. else {
  78638. currentMesh.computeWorldMatrix(true);
  78639. }
  78640. }
  78641. }
  78642. // Particles
  78643. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  78644. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  78645. if (parser) {
  78646. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  78647. var parsedParticleSystem = parsedData.particleSystems[index];
  78648. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  78649. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  78650. }
  78651. }
  78652. }
  78653. }
  78654. return true;
  78655. }
  78656. catch (err) {
  78657. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  78658. if (onError) {
  78659. onError(msg, err);
  78660. }
  78661. else {
  78662. BABYLON.Tools.Log(msg);
  78663. throw err;
  78664. }
  78665. }
  78666. finally {
  78667. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  78668. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  78669. }
  78670. }
  78671. return false;
  78672. },
  78673. load: function (scene, data, rootUrl, onError) {
  78674. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  78675. // when SceneLoader.debugLogging = true (default), or exception encountered.
  78676. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  78677. // and avoid problems with multiple concurrent .babylon loads.
  78678. var log = "importScene has failed JSON parse";
  78679. try {
  78680. var parsedData = JSON.parse(data);
  78681. log = "";
  78682. // Scene
  78683. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  78684. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  78685. }
  78686. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  78687. scene.autoClear = parsedData.autoClear;
  78688. }
  78689. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  78690. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  78691. }
  78692. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  78693. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  78694. }
  78695. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  78696. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  78697. }
  78698. // Fog
  78699. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  78700. scene.fogMode = parsedData.fogMode;
  78701. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  78702. scene.fogStart = parsedData.fogStart;
  78703. scene.fogEnd = parsedData.fogEnd;
  78704. scene.fogDensity = parsedData.fogDensity;
  78705. log += "\tFog mode for scene: ";
  78706. switch (scene.fogMode) {
  78707. // getters not compiling, so using hardcoded
  78708. case 1:
  78709. log += "exp\n";
  78710. break;
  78711. case 2:
  78712. log += "exp2\n";
  78713. break;
  78714. case 3:
  78715. log += "linear\n";
  78716. break;
  78717. }
  78718. }
  78719. //Physics
  78720. if (parsedData.physicsEnabled) {
  78721. var physicsPlugin;
  78722. if (parsedData.physicsEngine === "cannon") {
  78723. physicsPlugin = new BABYLON.CannonJSPlugin();
  78724. }
  78725. else if (parsedData.physicsEngine === "oimo") {
  78726. physicsPlugin = new BABYLON.OimoJSPlugin();
  78727. }
  78728. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  78729. //else - default engine, which is currently oimo
  78730. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  78731. scene.enablePhysics(physicsGravity, physicsPlugin);
  78732. }
  78733. // Metadata
  78734. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  78735. scene.metadata = parsedData.metadata;
  78736. }
  78737. //collisions, if defined. otherwise, default is true
  78738. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  78739. scene.collisionsEnabled = parsedData.collisionsEnabled;
  78740. }
  78741. scene.workerCollisions = !!parsedData.workerCollisions;
  78742. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  78743. if (!container) {
  78744. return false;
  78745. }
  78746. if (parsedData.autoAnimate) {
  78747. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  78748. }
  78749. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  78750. scene.setActiveCameraByID(parsedData.activeCameraID);
  78751. }
  78752. // Environment texture
  78753. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  78754. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  78755. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  78756. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  78757. if (parsedData.environmentTextureRotationY) {
  78758. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  78759. }
  78760. scene.environmentTexture = hdrTexture;
  78761. }
  78762. else {
  78763. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  78764. if (parsedData.environmentTextureRotationY) {
  78765. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  78766. }
  78767. scene.environmentTexture = cubeTexture;
  78768. }
  78769. if (parsedData.createDefaultSkybox === true) {
  78770. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  78771. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  78772. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  78773. }
  78774. }
  78775. // Finish
  78776. return true;
  78777. }
  78778. catch (err) {
  78779. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  78780. if (onError) {
  78781. onError(msg, err);
  78782. }
  78783. else {
  78784. BABYLON.Tools.Log(msg);
  78785. throw err;
  78786. }
  78787. }
  78788. finally {
  78789. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  78790. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  78791. }
  78792. }
  78793. return false;
  78794. },
  78795. loadAssetContainer: function (scene, data, rootUrl, onError) {
  78796. var container = loadAssetContainer(scene, data, rootUrl, onError);
  78797. return container;
  78798. }
  78799. });
  78800. })(BABYLON || (BABYLON = {}));
  78801. //# sourceMappingURL=babylonFileLoader.js.map
  78802. var BABYLON;
  78803. (function (BABYLON) {
  78804. /**
  78805. * Class used to help managing file picking and drag'n'drop
  78806. */
  78807. var FilesInput = /** @class */ (function () {
  78808. /**
  78809. * Creates a new FilesInput
  78810. * @param engine defines the rendering engine
  78811. * @param scene defines the hosting scene
  78812. * @param sceneLoadedCallback callback called when scene is loaded
  78813. * @param progressCallback callback called to track progress
  78814. * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop
  78815. * @param textureLoadingCallback callback called when a texture is loading
  78816. * @param startingProcessingFilesCallback callback called when the system is about to process all files
  78817. * @param onReloadCallback callback called when a reload is requested
  78818. * @param errorCallback callback call if an error occurs
  78819. */
  78820. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  78821. /**
  78822. * Callback called when a file is processed
  78823. */
  78824. this.onProcessFileCallback = function () { return true; };
  78825. this._engine = engine;
  78826. this._currentScene = scene;
  78827. this._sceneLoadedCallback = sceneLoadedCallback;
  78828. this._progressCallback = progressCallback;
  78829. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  78830. this._textureLoadingCallback = textureLoadingCallback;
  78831. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  78832. this._onReloadCallback = onReloadCallback;
  78833. this._errorCallback = errorCallback;
  78834. }
  78835. /**
  78836. * Calls this function to listen to drag'n'drop events on a specific DOM element
  78837. * @param elementToMonitor defines the DOM element to track
  78838. */
  78839. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  78840. var _this = this;
  78841. if (elementToMonitor) {
  78842. this._elementToMonitor = elementToMonitor;
  78843. this._dragEnterHandler = function (e) { _this.drag(e); };
  78844. this._dragOverHandler = function (e) { _this.drag(e); };
  78845. this._dropHandler = function (e) { _this.drop(e); };
  78846. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  78847. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  78848. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  78849. }
  78850. };
  78851. /**
  78852. * Release all associated resources
  78853. */
  78854. FilesInput.prototype.dispose = function () {
  78855. if (!this._elementToMonitor) {
  78856. return;
  78857. }
  78858. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  78859. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  78860. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  78861. };
  78862. FilesInput.prototype.renderFunction = function () {
  78863. if (this._additionalRenderLoopLogicCallback) {
  78864. this._additionalRenderLoopLogicCallback();
  78865. }
  78866. if (this._currentScene) {
  78867. if (this._textureLoadingCallback) {
  78868. var remaining = this._currentScene.getWaitingItemsCount();
  78869. if (remaining > 0) {
  78870. this._textureLoadingCallback(remaining);
  78871. }
  78872. }
  78873. this._currentScene.render();
  78874. }
  78875. };
  78876. FilesInput.prototype.drag = function (e) {
  78877. e.stopPropagation();
  78878. e.preventDefault();
  78879. };
  78880. FilesInput.prototype.drop = function (eventDrop) {
  78881. eventDrop.stopPropagation();
  78882. eventDrop.preventDefault();
  78883. this.loadFiles(eventDrop);
  78884. };
  78885. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  78886. var _this = this;
  78887. var reader = folder.createReader();
  78888. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  78889. reader.readEntries(function (entries) {
  78890. remaining.count += entries.length;
  78891. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  78892. var entry = entries_1[_i];
  78893. if (entry.isFile) {
  78894. entry.file(function (file) {
  78895. file.correctName = relativePath + file.name;
  78896. files.push(file);
  78897. if (--remaining.count === 0) {
  78898. callback();
  78899. }
  78900. });
  78901. }
  78902. else if (entry.isDirectory) {
  78903. _this._traverseFolder(entry, files, remaining, callback);
  78904. }
  78905. }
  78906. if (--remaining.count) {
  78907. callback();
  78908. }
  78909. });
  78910. };
  78911. FilesInput.prototype._processFiles = function (files) {
  78912. for (var i = 0; i < files.length; i++) {
  78913. var name = files[i].correctName.toLowerCase();
  78914. var extension = name.split('.').pop();
  78915. if (!this.onProcessFileCallback(files[i], name, extension)) {
  78916. continue;
  78917. }
  78918. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  78919. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  78920. this._sceneFileToLoad = files[i];
  78921. }
  78922. FilesInput.FilesToLoad[name] = files[i];
  78923. }
  78924. };
  78925. /**
  78926. * Load files from a drop event
  78927. * @param event defines the drop event to use as source
  78928. */
  78929. FilesInput.prototype.loadFiles = function (event) {
  78930. var _this = this;
  78931. // Handling data transfer via drag'n'drop
  78932. if (event && event.dataTransfer && event.dataTransfer.files) {
  78933. this._filesToLoad = event.dataTransfer.files;
  78934. }
  78935. // Handling files from input files
  78936. if (event && event.target && event.target.files) {
  78937. this._filesToLoad = event.target.files;
  78938. }
  78939. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  78940. return;
  78941. }
  78942. if (this._startingProcessingFilesCallback) {
  78943. this._startingProcessingFilesCallback(this._filesToLoad);
  78944. }
  78945. if (this._filesToLoad && this._filesToLoad.length > 0) {
  78946. var files_1 = new Array();
  78947. var folders = [];
  78948. var items = event.dataTransfer ? event.dataTransfer.items : null;
  78949. for (var i = 0; i < this._filesToLoad.length; i++) {
  78950. var fileToLoad = this._filesToLoad[i];
  78951. var name_1 = fileToLoad.name.toLowerCase();
  78952. var entry = void 0;
  78953. fileToLoad.correctName = name_1;
  78954. if (items) {
  78955. var item = items[i];
  78956. if (item.getAsEntry) {
  78957. entry = item.getAsEntry();
  78958. }
  78959. else if (item.webkitGetAsEntry) {
  78960. entry = item.webkitGetAsEntry();
  78961. }
  78962. }
  78963. if (!entry) {
  78964. files_1.push(fileToLoad);
  78965. }
  78966. else {
  78967. if (entry.isDirectory) {
  78968. folders.push(entry);
  78969. }
  78970. else {
  78971. files_1.push(fileToLoad);
  78972. }
  78973. }
  78974. }
  78975. if (folders.length === 0) {
  78976. this._processFiles(files_1);
  78977. this._processReload();
  78978. }
  78979. else {
  78980. var remaining = { count: folders.length };
  78981. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  78982. var folder = folders_1[_i];
  78983. this._traverseFolder(folder, files_1, remaining, function () {
  78984. _this._processFiles(files_1);
  78985. if (remaining.count === 0) {
  78986. _this._processReload();
  78987. }
  78988. });
  78989. }
  78990. }
  78991. }
  78992. };
  78993. FilesInput.prototype._processReload = function () {
  78994. if (this._onReloadCallback) {
  78995. this._onReloadCallback(this._sceneFileToLoad);
  78996. }
  78997. else {
  78998. this.reload();
  78999. }
  79000. };
  79001. /**
  79002. * Reload the current scene from the loaded files
  79003. */
  79004. FilesInput.prototype.reload = function () {
  79005. var _this = this;
  79006. // If a scene file has been provided
  79007. if (this._sceneFileToLoad) {
  79008. if (this._currentScene) {
  79009. if (BABYLON.Tools.errorsCount > 0) {
  79010. BABYLON.Tools.ClearLogCache();
  79011. }
  79012. this._engine.stopRenderLoop();
  79013. }
  79014. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  79015. if (_this._progressCallback) {
  79016. _this._progressCallback(progress);
  79017. }
  79018. }).then(function (scene) {
  79019. if (_this._currentScene) {
  79020. _this._currentScene.dispose();
  79021. }
  79022. _this._currentScene = scene;
  79023. if (_this._sceneLoadedCallback) {
  79024. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  79025. }
  79026. // Wait for textures and shaders to be ready
  79027. _this._currentScene.executeWhenReady(function () {
  79028. _this._engine.runRenderLoop(function () {
  79029. _this.renderFunction();
  79030. });
  79031. });
  79032. }).catch(function (error) {
  79033. if (_this._errorCallback) {
  79034. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  79035. }
  79036. });
  79037. }
  79038. else {
  79039. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  79040. }
  79041. };
  79042. /**
  79043. * List of files ready to be loaded
  79044. */
  79045. FilesInput.FilesToLoad = {};
  79046. return FilesInput;
  79047. }());
  79048. BABYLON.FilesInput = FilesInput;
  79049. })(BABYLON || (BABYLON = {}));
  79050. //# sourceMappingURL=filesInput.js.map
  79051. var BABYLON;
  79052. (function (BABYLON) {
  79053. /**
  79054. * Class used to store custom tags
  79055. */
  79056. var Tags = /** @class */ (function () {
  79057. function Tags() {
  79058. }
  79059. /**
  79060. * Adds support for tags on the given object
  79061. * @param obj defines the object to use
  79062. */
  79063. Tags.EnableFor = function (obj) {
  79064. obj._tags = obj._tags || {};
  79065. obj.hasTags = function () {
  79066. return Tags.HasTags(obj);
  79067. };
  79068. obj.addTags = function (tagsString) {
  79069. return Tags.AddTagsTo(obj, tagsString);
  79070. };
  79071. obj.removeTags = function (tagsString) {
  79072. return Tags.RemoveTagsFrom(obj, tagsString);
  79073. };
  79074. obj.matchesTagsQuery = function (tagsQuery) {
  79075. return Tags.MatchesQuery(obj, tagsQuery);
  79076. };
  79077. };
  79078. /**
  79079. * Removes tags support
  79080. * @param obj defines the object to use
  79081. */
  79082. Tags.DisableFor = function (obj) {
  79083. delete obj._tags;
  79084. delete obj.hasTags;
  79085. delete obj.addTags;
  79086. delete obj.removeTags;
  79087. delete obj.matchesTagsQuery;
  79088. };
  79089. /**
  79090. * Gets a boolean indicating if the given object has tags
  79091. * @param obj defines the object to use
  79092. * @returns a boolean
  79093. */
  79094. Tags.HasTags = function (obj) {
  79095. if (!obj._tags) {
  79096. return false;
  79097. }
  79098. return !BABYLON.Tools.IsEmpty(obj._tags);
  79099. };
  79100. /**
  79101. * Gets the tags available on a given object
  79102. * @param obj defines the object to use
  79103. * @param asString defines if the tags must be returned as a string instead of an array of strings
  79104. * @returns the tags
  79105. */
  79106. Tags.GetTags = function (obj, asString) {
  79107. if (asString === void 0) { asString = true; }
  79108. if (!obj._tags) {
  79109. return null;
  79110. }
  79111. if (asString) {
  79112. var tagsArray = [];
  79113. for (var tag in obj._tags) {
  79114. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  79115. tagsArray.push(tag);
  79116. }
  79117. }
  79118. return tagsArray.join(" ");
  79119. }
  79120. else {
  79121. return obj._tags;
  79122. }
  79123. };
  79124. /**
  79125. * Adds tags to an object
  79126. * @param obj defines the object to use
  79127. * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.
  79128. * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces
  79129. */
  79130. Tags.AddTagsTo = function (obj, tagsString) {
  79131. if (!tagsString) {
  79132. return;
  79133. }
  79134. if (typeof tagsString !== "string") {
  79135. return;
  79136. }
  79137. var tags = tagsString.split(" ");
  79138. tags.forEach(function (tag, index, array) {
  79139. Tags._AddTagTo(obj, tag);
  79140. });
  79141. };
  79142. /**
  79143. * @hidden
  79144. */
  79145. Tags._AddTagTo = function (obj, tag) {
  79146. tag = tag.trim();
  79147. if (tag === "" || tag === "true" || tag === "false") {
  79148. return;
  79149. }
  79150. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  79151. return;
  79152. }
  79153. Tags.EnableFor(obj);
  79154. obj._tags[tag] = true;
  79155. };
  79156. /**
  79157. * Removes specific tags from a specific object
  79158. * @param obj defines the object to use
  79159. * @param tagsString defines the tags to remove
  79160. */
  79161. Tags.RemoveTagsFrom = function (obj, tagsString) {
  79162. if (!Tags.HasTags(obj)) {
  79163. return;
  79164. }
  79165. var tags = tagsString.split(" ");
  79166. for (var t in tags) {
  79167. Tags._RemoveTagFrom(obj, tags[t]);
  79168. }
  79169. };
  79170. /**
  79171. * @hidden
  79172. */
  79173. Tags._RemoveTagFrom = function (obj, tag) {
  79174. delete obj._tags[tag];
  79175. };
  79176. /**
  79177. * Defines if tags hosted on an object match a given query
  79178. * @param obj defines the object to use
  79179. * @param tagsQuery defines the tag query
  79180. * @returns a boolean
  79181. */
  79182. Tags.MatchesQuery = function (obj, tagsQuery) {
  79183. if (tagsQuery === undefined) {
  79184. return true;
  79185. }
  79186. if (tagsQuery === "") {
  79187. return Tags.HasTags(obj);
  79188. }
  79189. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  79190. };
  79191. return Tags;
  79192. }());
  79193. BABYLON.Tags = Tags;
  79194. })(BABYLON || (BABYLON = {}));
  79195. //# sourceMappingURL=tags.js.map
  79196. var BABYLON;
  79197. (function (BABYLON) {
  79198. /**
  79199. * Class used to evalaute queries containing `and` and `or` operators
  79200. */
  79201. var AndOrNotEvaluator = /** @class */ (function () {
  79202. function AndOrNotEvaluator() {
  79203. }
  79204. /**
  79205. * Evaluate a query
  79206. * @param query defines the query to evaluate
  79207. * @param evaluateCallback defines the callback used to filter result
  79208. * @returns true if the query matches
  79209. */
  79210. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  79211. if (!query.match(/\([^\(\)]*\)/g)) {
  79212. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  79213. }
  79214. else {
  79215. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  79216. // remove parenthesis
  79217. r = r.slice(1, r.length - 1);
  79218. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  79219. });
  79220. }
  79221. if (query === "true") {
  79222. return true;
  79223. }
  79224. if (query === "false") {
  79225. return false;
  79226. }
  79227. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  79228. };
  79229. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  79230. evaluateCallback = evaluateCallback || (function (r) {
  79231. return r === "true" ? true : false;
  79232. });
  79233. var result;
  79234. var or = parenthesisContent.split("||");
  79235. for (var i in or) {
  79236. if (or.hasOwnProperty(i)) {
  79237. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  79238. var and = ori.split("&&");
  79239. if (and.length > 1) {
  79240. for (var j = 0; j < and.length; ++j) {
  79241. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  79242. if (andj !== "true" && andj !== "false") {
  79243. if (andj[0] === "!") {
  79244. result = !evaluateCallback(andj.substring(1));
  79245. }
  79246. else {
  79247. result = evaluateCallback(andj);
  79248. }
  79249. }
  79250. else {
  79251. result = andj === "true" ? true : false;
  79252. }
  79253. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  79254. ori = "false";
  79255. break;
  79256. }
  79257. }
  79258. }
  79259. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  79260. result = true;
  79261. break;
  79262. }
  79263. // result equals false (or undefined)
  79264. if (ori !== "true" && ori !== "false") {
  79265. if (ori[0] === "!") {
  79266. result = !evaluateCallback(ori.substring(1));
  79267. }
  79268. else {
  79269. result = evaluateCallback(ori);
  79270. }
  79271. }
  79272. else {
  79273. result = ori === "true" ? true : false;
  79274. }
  79275. }
  79276. }
  79277. // the whole parenthesis scope is replaced by 'true' or 'false'
  79278. return result ? "true" : "false";
  79279. };
  79280. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  79281. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  79282. // remove whitespaces
  79283. r = r.replace(/[\s]/g, function () { return ""; });
  79284. return r.length % 2 ? "!" : "";
  79285. });
  79286. booleanString = booleanString.trim();
  79287. if (booleanString === "!true") {
  79288. booleanString = "false";
  79289. }
  79290. else if (booleanString === "!false") {
  79291. booleanString = "true";
  79292. }
  79293. return booleanString;
  79294. };
  79295. return AndOrNotEvaluator;
  79296. }());
  79297. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  79298. })(BABYLON || (BABYLON = {}));
  79299. //# sourceMappingURL=andOrNotEvaluator.js.map
  79300. var BABYLON;
  79301. (function (BABYLON) {
  79302. // Sets the default offline provider to Babylon.js
  79303. BABYLON.Engine.OfflineProviderFactory = function (urlToScene, callbackManifestChecked, disableManifestCheck) {
  79304. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  79305. return new Database(urlToScene, callbackManifestChecked, disableManifestCheck);
  79306. };
  79307. /**
  79308. * Class used to enable access to IndexedDB
  79309. * @see http://doc.babylonjs.com/how_to/caching_resources_in_indexeddb
  79310. */
  79311. var Database = /** @class */ (function () {
  79312. /**
  79313. * Creates a new Database
  79314. * @param urlToScene defines the url to load the scene
  79315. * @param callbackManifestChecked defines the callback to use when manifest is checked
  79316. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  79317. */
  79318. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  79319. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  79320. var _this = this;
  79321. // Handling various flavors of prefixed version of IndexedDB
  79322. this._idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  79323. this._callbackManifestChecked = callbackManifestChecked;
  79324. this._currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  79325. this._db = null;
  79326. this._enableSceneOffline = false;
  79327. this._enableTexturesOffline = false;
  79328. this._manifestVersionFound = 0;
  79329. this._mustUpdateRessources = false;
  79330. this._hasReachedQuota = false;
  79331. if (!Database.IDBStorageEnabled) {
  79332. this._callbackManifestChecked(true);
  79333. }
  79334. else {
  79335. if (disableManifestCheck) {
  79336. this._enableSceneOffline = true;
  79337. this._enableTexturesOffline = true;
  79338. this._manifestVersionFound = 1;
  79339. BABYLON.Tools.SetImmediate(function () {
  79340. _this._callbackManifestChecked(true);
  79341. });
  79342. }
  79343. else {
  79344. this._checkManifestFile();
  79345. }
  79346. }
  79347. }
  79348. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  79349. /**
  79350. * Gets a boolean indicating if scene must be saved in the database
  79351. */
  79352. get: function () {
  79353. return this._enableSceneOffline;
  79354. },
  79355. enumerable: true,
  79356. configurable: true
  79357. });
  79358. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  79359. /**
  79360. * Gets a boolean indicating if textures must be saved in the database
  79361. */
  79362. get: function () {
  79363. return this._enableTexturesOffline;
  79364. },
  79365. enumerable: true,
  79366. configurable: true
  79367. });
  79368. Database.prototype._checkManifestFile = function () {
  79369. var _this = this;
  79370. var noManifestFile = function () {
  79371. _this._enableSceneOffline = false;
  79372. _this._enableTexturesOffline = false;
  79373. _this._callbackManifestChecked(false);
  79374. };
  79375. var timeStampUsed = false;
  79376. var manifestURL = this._currentSceneUrl + ".manifest";
  79377. var xhr = new XMLHttpRequest();
  79378. if (navigator.onLine) {
  79379. // Adding a timestamp to by-pass browsers' cache
  79380. timeStampUsed = true;
  79381. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  79382. }
  79383. xhr.open("GET", manifestURL, true);
  79384. xhr.addEventListener("load", function () {
  79385. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  79386. try {
  79387. var manifestFile = JSON.parse(xhr.response);
  79388. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  79389. _this._enableTexturesOffline = manifestFile.enableTexturesOffline && Database.IsUASupportingBlobStorage;
  79390. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  79391. _this._manifestVersionFound = manifestFile.version;
  79392. }
  79393. if (_this._callbackManifestChecked) {
  79394. _this._callbackManifestChecked(true);
  79395. }
  79396. }
  79397. catch (ex) {
  79398. noManifestFile();
  79399. }
  79400. }
  79401. else {
  79402. noManifestFile();
  79403. }
  79404. }, false);
  79405. xhr.addEventListener("error", function (event) {
  79406. if (timeStampUsed) {
  79407. timeStampUsed = false;
  79408. // Let's retry without the timeStamp
  79409. // It could fail when coupled with HTML5 Offline API
  79410. var retryManifestURL = _this._currentSceneUrl + ".manifest";
  79411. xhr.open("GET", retryManifestURL, true);
  79412. xhr.send();
  79413. }
  79414. else {
  79415. noManifestFile();
  79416. }
  79417. }, false);
  79418. try {
  79419. xhr.send();
  79420. }
  79421. catch (ex) {
  79422. BABYLON.Tools.Error("Error on XHR send request.");
  79423. this._callbackManifestChecked(false);
  79424. }
  79425. };
  79426. /**
  79427. * Open the database and make it available
  79428. * @param successCallback defines the callback to call on success
  79429. * @param errorCallback defines the callback to call on error
  79430. */
  79431. Database.prototype.open = function (successCallback, errorCallback) {
  79432. var _this = this;
  79433. var handleError = function () {
  79434. _this._isSupported = false;
  79435. if (errorCallback) {
  79436. errorCallback();
  79437. }
  79438. };
  79439. if (!this._idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  79440. // Your browser doesn't support IndexedDB
  79441. this._isSupported = false;
  79442. if (errorCallback) {
  79443. errorCallback();
  79444. }
  79445. }
  79446. else {
  79447. // If the DB hasn't been opened or created yet
  79448. if (!this._db) {
  79449. this._hasReachedQuota = false;
  79450. this._isSupported = true;
  79451. var request = this._idbFactory.open("babylonjs", 1);
  79452. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  79453. request.onerror = function (event) {
  79454. handleError();
  79455. };
  79456. // executes when a version change transaction cannot complete due to other active transactions
  79457. request.onblocked = function (event) {
  79458. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  79459. handleError();
  79460. };
  79461. // DB has been opened successfully
  79462. request.onsuccess = function (event) {
  79463. _this._db = request.result;
  79464. successCallback();
  79465. };
  79466. // Initialization of the DB. Creating Scenes & Textures stores
  79467. request.onupgradeneeded = function (event) {
  79468. _this._db = (event.target).result;
  79469. if (_this._db) {
  79470. try {
  79471. _this._db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  79472. _this._db.createObjectStore("versions", { keyPath: "sceneUrl" });
  79473. _this._db.createObjectStore("textures", { keyPath: "textureUrl" });
  79474. }
  79475. catch (ex) {
  79476. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  79477. handleError();
  79478. }
  79479. }
  79480. };
  79481. }
  79482. // DB has already been created and opened
  79483. else {
  79484. if (successCallback) {
  79485. successCallback();
  79486. }
  79487. }
  79488. }
  79489. };
  79490. /**
  79491. * Loads an image from the database
  79492. * @param url defines the url to load from
  79493. * @param image defines the target DOM image
  79494. */
  79495. Database.prototype.loadImage = function (url, image) {
  79496. var _this = this;
  79497. var completeURL = Database._ReturnFullUrlLocation(url);
  79498. var saveAndLoadImage = function () {
  79499. if (!_this._hasReachedQuota && _this._db !== null) {
  79500. // the texture is not yet in the DB, let's try to save it
  79501. _this._saveImageIntoDBAsync(completeURL, image);
  79502. }
  79503. // If the texture is not in the DB and we've reached the DB quota limit
  79504. // let's load it directly from the web
  79505. else {
  79506. image.src = url;
  79507. }
  79508. };
  79509. if (!this._mustUpdateRessources) {
  79510. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  79511. }
  79512. // First time we're download the images or update requested in the manifest file by a version change
  79513. else {
  79514. saveAndLoadImage();
  79515. }
  79516. };
  79517. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  79518. if (this._isSupported && this._db !== null) {
  79519. var texture;
  79520. var transaction = this._db.transaction(["textures"]);
  79521. transaction.onabort = function (event) {
  79522. image.src = url;
  79523. };
  79524. transaction.oncomplete = function (event) {
  79525. var blobTextureURL;
  79526. if (texture) {
  79527. var URL = window.URL || window.webkitURL;
  79528. blobTextureURL = URL.createObjectURL(texture.data);
  79529. image.onerror = function () {
  79530. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  79531. image.src = url;
  79532. };
  79533. image.src = blobTextureURL;
  79534. }
  79535. else {
  79536. notInDBCallback();
  79537. }
  79538. };
  79539. var getRequest = transaction.objectStore("textures").get(url);
  79540. getRequest.onsuccess = function (event) {
  79541. texture = (event.target).result;
  79542. };
  79543. getRequest.onerror = function (event) {
  79544. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  79545. image.src = url;
  79546. };
  79547. }
  79548. else {
  79549. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  79550. image.src = url;
  79551. }
  79552. };
  79553. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  79554. var _this = this;
  79555. if (this._isSupported) {
  79556. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  79557. var generateBlobUrl = function () {
  79558. var blobTextureURL;
  79559. if (blob) {
  79560. var URL = window.URL || window.webkitURL;
  79561. try {
  79562. blobTextureURL = URL.createObjectURL(blob);
  79563. }
  79564. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  79565. catch (ex) {
  79566. blobTextureURL = URL.createObjectURL(blob);
  79567. }
  79568. }
  79569. if (blobTextureURL) {
  79570. image.src = blobTextureURL;
  79571. }
  79572. };
  79573. if (Database.IsUASupportingBlobStorage) { // Create XHR
  79574. var xhr = new XMLHttpRequest(), blob;
  79575. xhr.open("GET", url, true);
  79576. xhr.responseType = "blob";
  79577. xhr.addEventListener("load", function () {
  79578. if (xhr.status === 200 && _this._db) {
  79579. // Blob as response (XHR2)
  79580. blob = xhr.response;
  79581. var transaction = _this._db.transaction(["textures"], "readwrite");
  79582. // the transaction could abort because of a QuotaExceededError error
  79583. transaction.onabort = function (event) {
  79584. try {
  79585. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  79586. var srcElement = (event.srcElement || event.target);
  79587. var error = srcElement.error;
  79588. if (error && error.name === "QuotaExceededError") {
  79589. _this._hasReachedQuota = true;
  79590. }
  79591. }
  79592. catch (ex) { }
  79593. generateBlobUrl();
  79594. };
  79595. transaction.oncomplete = function (event) {
  79596. generateBlobUrl();
  79597. };
  79598. var newTexture = { textureUrl: url, data: blob };
  79599. try {
  79600. // Put the blob into the dabase
  79601. var addRequest = transaction.objectStore("textures").put(newTexture);
  79602. addRequest.onsuccess = function (event) {
  79603. };
  79604. addRequest.onerror = function (event) {
  79605. generateBlobUrl();
  79606. };
  79607. }
  79608. catch (ex) {
  79609. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  79610. if (ex.code === 25) {
  79611. Database.IsUASupportingBlobStorage = false;
  79612. _this._enableTexturesOffline = false;
  79613. }
  79614. image.src = url;
  79615. }
  79616. }
  79617. else {
  79618. image.src = url;
  79619. }
  79620. }, false);
  79621. xhr.addEventListener("error", function (event) {
  79622. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  79623. image.src = url;
  79624. }, false);
  79625. xhr.send();
  79626. }
  79627. else {
  79628. image.src = url;
  79629. }
  79630. }
  79631. else {
  79632. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  79633. image.src = url;
  79634. }
  79635. };
  79636. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  79637. var _this = this;
  79638. var updateVersion = function () {
  79639. // the version is not yet in the DB or we need to update it
  79640. _this._saveVersionIntoDBAsync(url, versionLoaded);
  79641. };
  79642. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  79643. };
  79644. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  79645. var _this = this;
  79646. if (this._isSupported && this._db) {
  79647. var version;
  79648. try {
  79649. var transaction = this._db.transaction(["versions"]);
  79650. transaction.oncomplete = function (event) {
  79651. if (version) {
  79652. // If the version in the JSON file is different from the version in DB
  79653. if (_this._manifestVersionFound !== version.data) {
  79654. _this._mustUpdateRessources = true;
  79655. updateInDBCallback();
  79656. }
  79657. else {
  79658. callback(version.data);
  79659. }
  79660. }
  79661. // version was not found in DB
  79662. else {
  79663. _this._mustUpdateRessources = true;
  79664. updateInDBCallback();
  79665. }
  79666. };
  79667. transaction.onabort = function (event) {
  79668. callback(-1);
  79669. };
  79670. var getRequest = transaction.objectStore("versions").get(url);
  79671. getRequest.onsuccess = function (event) {
  79672. version = (event.target).result;
  79673. };
  79674. getRequest.onerror = function (event) {
  79675. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  79676. callback(-1);
  79677. };
  79678. }
  79679. catch (ex) {
  79680. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  79681. callback(-1);
  79682. }
  79683. }
  79684. else {
  79685. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  79686. callback(-1);
  79687. }
  79688. };
  79689. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  79690. var _this = this;
  79691. if (this._isSupported && !this._hasReachedQuota && this._db) {
  79692. try {
  79693. // Open a transaction to the database
  79694. var transaction = this._db.transaction(["versions"], "readwrite");
  79695. // the transaction could abort because of a QuotaExceededError error
  79696. transaction.onabort = function (event) {
  79697. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  79698. var error = event.srcElement['error'];
  79699. if (error && error.name === "QuotaExceededError") {
  79700. _this._hasReachedQuota = true;
  79701. }
  79702. }
  79703. catch (ex) { }
  79704. callback(-1);
  79705. };
  79706. transaction.oncomplete = function (event) {
  79707. callback(_this._manifestVersionFound);
  79708. };
  79709. var newVersion = { sceneUrl: url, data: this._manifestVersionFound };
  79710. // Put the scene into the database
  79711. var addRequest = transaction.objectStore("versions").put(newVersion);
  79712. addRequest.onsuccess = function (event) {
  79713. };
  79714. addRequest.onerror = function (event) {
  79715. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  79716. };
  79717. }
  79718. catch (ex) {
  79719. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  79720. callback(-1);
  79721. }
  79722. }
  79723. else {
  79724. callback(-1);
  79725. }
  79726. };
  79727. /**
  79728. * Loads a file from database
  79729. * @param url defines the URL to load from
  79730. * @param sceneLoaded defines a callback to call on success
  79731. * @param progressCallBack defines a callback to call when progress changed
  79732. * @param errorCallback defines a callback to call on error
  79733. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  79734. */
  79735. Database.prototype.loadFile = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  79736. var _this = this;
  79737. var completeUrl = Database._ReturnFullUrlLocation(url);
  79738. var saveAndLoadFile = function () {
  79739. // the scene is not yet in the DB, let's try to save it
  79740. _this._saveFileAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  79741. };
  79742. this._checkVersionFromDB(completeUrl, function (version) {
  79743. if (version !== -1) {
  79744. if (!_this._mustUpdateRessources) {
  79745. _this._loadFileAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  79746. }
  79747. else {
  79748. _this._saveFileAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  79749. }
  79750. }
  79751. else {
  79752. if (errorCallback) {
  79753. errorCallback();
  79754. }
  79755. }
  79756. });
  79757. };
  79758. Database.prototype._loadFileAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  79759. if (this._isSupported && this._db) {
  79760. var targetStore;
  79761. if (url.indexOf(".babylon") !== -1) {
  79762. targetStore = "scenes";
  79763. }
  79764. else {
  79765. targetStore = "textures";
  79766. }
  79767. var file;
  79768. var transaction = this._db.transaction([targetStore]);
  79769. transaction.oncomplete = function (event) {
  79770. if (file) {
  79771. callback(file.data);
  79772. }
  79773. // file was not found in DB
  79774. else {
  79775. notInDBCallback();
  79776. }
  79777. };
  79778. transaction.onabort = function (event) {
  79779. notInDBCallback();
  79780. };
  79781. var getRequest = transaction.objectStore(targetStore).get(url);
  79782. getRequest.onsuccess = function (event) {
  79783. file = (event.target).result;
  79784. };
  79785. getRequest.onerror = function (event) {
  79786. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  79787. notInDBCallback();
  79788. };
  79789. }
  79790. else {
  79791. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  79792. callback();
  79793. }
  79794. };
  79795. Database.prototype._saveFileAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  79796. var _this = this;
  79797. if (this._isSupported) {
  79798. var targetStore;
  79799. if (url.indexOf(".babylon") !== -1) {
  79800. targetStore = "scenes";
  79801. }
  79802. else {
  79803. targetStore = "textures";
  79804. }
  79805. // Create XHR
  79806. var xhr = new XMLHttpRequest();
  79807. var fileData;
  79808. xhr.open("GET", url + "?" + Date.now(), true);
  79809. if (useArrayBuffer) {
  79810. xhr.responseType = "arraybuffer";
  79811. }
  79812. if (progressCallback) {
  79813. xhr.onprogress = progressCallback;
  79814. }
  79815. xhr.addEventListener("load", function () {
  79816. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  79817. // Blob as response (XHR2)
  79818. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  79819. if (!_this._hasReachedQuota && _this._db) {
  79820. // Open a transaction to the database
  79821. var transaction = _this._db.transaction([targetStore], "readwrite");
  79822. // the transaction could abort because of a QuotaExceededError error
  79823. transaction.onabort = function (event) {
  79824. try {
  79825. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  79826. var error = event.srcElement['error'];
  79827. if (error && error.name === "QuotaExceededError") {
  79828. _this._hasReachedQuota = true;
  79829. }
  79830. }
  79831. catch (ex) { }
  79832. callback(fileData);
  79833. };
  79834. transaction.oncomplete = function (event) {
  79835. callback(fileData);
  79836. };
  79837. var newFile;
  79838. if (targetStore === "scenes") {
  79839. newFile = { sceneUrl: url, data: fileData, version: _this._manifestVersionFound };
  79840. }
  79841. else {
  79842. newFile = { textureUrl: url, data: fileData };
  79843. }
  79844. try {
  79845. // Put the scene into the database
  79846. var addRequest = transaction.objectStore(targetStore).put(newFile);
  79847. addRequest.onsuccess = function (event) {
  79848. };
  79849. addRequest.onerror = function (event) {
  79850. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  79851. };
  79852. }
  79853. catch (ex) {
  79854. callback(fileData);
  79855. }
  79856. }
  79857. else {
  79858. callback(fileData);
  79859. }
  79860. }
  79861. else {
  79862. if (xhr.status >= 400 && errorCallback) {
  79863. errorCallback(xhr);
  79864. }
  79865. else {
  79866. callback();
  79867. }
  79868. }
  79869. }, false);
  79870. xhr.addEventListener("error", function (event) {
  79871. BABYLON.Tools.Error("error on XHR request.");
  79872. callback();
  79873. }, false);
  79874. xhr.send();
  79875. }
  79876. else {
  79877. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or Babylon.js Database is not open.");
  79878. callback();
  79879. }
  79880. };
  79881. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  79882. Database.IsUASupportingBlobStorage = true;
  79883. /**
  79884. * Gets a boolean indicating if Database storate is enabled (off by default)
  79885. */
  79886. Database.IDBStorageEnabled = false;
  79887. Database._ParseURL = function (url) {
  79888. var a = document.createElement('a');
  79889. a.href = url;
  79890. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  79891. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  79892. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  79893. return absLocation;
  79894. };
  79895. Database._ReturnFullUrlLocation = function (url) {
  79896. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  79897. return (Database._ParseURL(window.location.href) + url);
  79898. }
  79899. else {
  79900. return url;
  79901. }
  79902. };
  79903. return Database;
  79904. }());
  79905. BABYLON.Database = Database;
  79906. })(BABYLON || (BABYLON = {}));
  79907. //# sourceMappingURL=database.js.map
  79908. var BABYLON;
  79909. (function (BABYLON) {
  79910. /**
  79911. * This represents all the required information to add a fresnel effect on a material:
  79912. * @see http://doc.babylonjs.com/how_to/how_to_use_fresnelparameters
  79913. */
  79914. var FresnelParameters = /** @class */ (function () {
  79915. function FresnelParameters() {
  79916. this._isEnabled = true;
  79917. /**
  79918. * Define the color used on edges (grazing angle)
  79919. */
  79920. this.leftColor = BABYLON.Color3.White();
  79921. /**
  79922. * Define the color used on center
  79923. */
  79924. this.rightColor = BABYLON.Color3.Black();
  79925. /**
  79926. * Define bias applied to computed fresnel term
  79927. */
  79928. this.bias = 0;
  79929. /**
  79930. * Defined the power exponent applied to fresnel term
  79931. */
  79932. this.power = 1;
  79933. }
  79934. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  79935. /**
  79936. * Define if the fresnel effect is enable or not.
  79937. */
  79938. get: function () {
  79939. return this._isEnabled;
  79940. },
  79941. set: function (value) {
  79942. if (this._isEnabled === value) {
  79943. return;
  79944. }
  79945. this._isEnabled = value;
  79946. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  79947. },
  79948. enumerable: true,
  79949. configurable: true
  79950. });
  79951. /**
  79952. * Clones the current fresnel and its valuues
  79953. * @returns a clone fresnel configuration
  79954. */
  79955. FresnelParameters.prototype.clone = function () {
  79956. var newFresnelParameters = new FresnelParameters();
  79957. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  79958. return newFresnelParameters;
  79959. };
  79960. /**
  79961. * Serializes the current fresnel parameters to a JSON representation.
  79962. * @return the JSON serialization
  79963. */
  79964. FresnelParameters.prototype.serialize = function () {
  79965. var serializationObject = {};
  79966. serializationObject.isEnabled = this.isEnabled;
  79967. serializationObject.leftColor = this.leftColor.asArray();
  79968. serializationObject.rightColor = this.rightColor.asArray();
  79969. serializationObject.bias = this.bias;
  79970. serializationObject.power = this.power;
  79971. return serializationObject;
  79972. };
  79973. /**
  79974. * Parse a JSON object and deserialize it to a new Fresnel parameter object.
  79975. * @param parsedFresnelParameters Define the JSON representation
  79976. * @returns the parsed parameters
  79977. */
  79978. FresnelParameters.Parse = function (parsedFresnelParameters) {
  79979. var fresnelParameters = new FresnelParameters();
  79980. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  79981. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  79982. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  79983. fresnelParameters.bias = parsedFresnelParameters.bias;
  79984. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  79985. return fresnelParameters;
  79986. };
  79987. return FresnelParameters;
  79988. }());
  79989. BABYLON.FresnelParameters = FresnelParameters;
  79990. })(BABYLON || (BABYLON = {}));
  79991. //# sourceMappingURL=fresnelParameters.js.map
  79992. var BABYLON;
  79993. (function (BABYLON) {
  79994. /**
  79995. * A multi-material is used to apply different materials to different parts of the same object without the need of
  79996. * separate meshes. This can be use to improve performances.
  79997. * @see http://doc.babylonjs.com/how_to/multi_materials
  79998. */
  79999. var MultiMaterial = /** @class */ (function (_super) {
  80000. __extends(MultiMaterial, _super);
  80001. /**
  80002. * Instantiates a new Multi Material
  80003. * A multi-material is used to apply different materials to different parts of the same object without the need of
  80004. * separate meshes. This can be use to improve performances.
  80005. * @see http://doc.babylonjs.com/how_to/multi_materials
  80006. * @param name Define the name in the scene
  80007. * @param scene Define the scene the material belongs to
  80008. */
  80009. function MultiMaterial(name, scene) {
  80010. var _this = _super.call(this, name, scene, true) || this;
  80011. scene.multiMaterials.push(_this);
  80012. _this.subMaterials = new Array();
  80013. _this._storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  80014. return _this;
  80015. }
  80016. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  80017. /**
  80018. * Gets or Sets the list of Materials used within the multi material.
  80019. * They need to be ordered according to the submeshes order in the associated mesh
  80020. */
  80021. get: function () {
  80022. return this._subMaterials;
  80023. },
  80024. set: function (value) {
  80025. this._subMaterials = value;
  80026. this._hookArray(value);
  80027. },
  80028. enumerable: true,
  80029. configurable: true
  80030. });
  80031. MultiMaterial.prototype._hookArray = function (array) {
  80032. var _this = this;
  80033. var oldPush = array.push;
  80034. array.push = function () {
  80035. var items = [];
  80036. for (var _i = 0; _i < arguments.length; _i++) {
  80037. items[_i] = arguments[_i];
  80038. }
  80039. var result = oldPush.apply(array, items);
  80040. _this._markAllSubMeshesAsTexturesDirty();
  80041. return result;
  80042. };
  80043. var oldSplice = array.splice;
  80044. array.splice = function (index, deleteCount) {
  80045. var deleted = oldSplice.apply(array, [index, deleteCount]);
  80046. _this._markAllSubMeshesAsTexturesDirty();
  80047. return deleted;
  80048. };
  80049. };
  80050. /**
  80051. * Get one of the submaterial by its index in the submaterials array
  80052. * @param index The index to look the sub material at
  80053. * @returns The Material if the index has been defined
  80054. */
  80055. MultiMaterial.prototype.getSubMaterial = function (index) {
  80056. if (index < 0 || index >= this.subMaterials.length) {
  80057. return this.getScene().defaultMaterial;
  80058. }
  80059. return this.subMaterials[index];
  80060. };
  80061. /**
  80062. * Get the list of active textures for the whole sub materials list.
  80063. * @returns All the textures that will be used during the rendering
  80064. */
  80065. MultiMaterial.prototype.getActiveTextures = function () {
  80066. var _a;
  80067. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  80068. if (subMaterial) {
  80069. return subMaterial.getActiveTextures();
  80070. }
  80071. else {
  80072. return [];
  80073. }
  80074. }));
  80075. };
  80076. /**
  80077. * Gets the current class name of the material e.g. "MultiMaterial"
  80078. * Mainly use in serialization.
  80079. * @returns the class name
  80080. */
  80081. MultiMaterial.prototype.getClassName = function () {
  80082. return "MultiMaterial";
  80083. };
  80084. /**
  80085. * Checks if the material is ready to render the requested sub mesh
  80086. * @param mesh Define the mesh the submesh belongs to
  80087. * @param subMesh Define the sub mesh to look readyness for
  80088. * @param useInstances Define whether or not the material is used with instances
  80089. * @returns true if ready, otherwise false
  80090. */
  80091. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  80092. for (var index = 0; index < this.subMaterials.length; index++) {
  80093. var subMaterial = this.subMaterials[index];
  80094. if (subMaterial) {
  80095. if (subMaterial._storeEffectOnSubMeshes) {
  80096. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  80097. return false;
  80098. }
  80099. continue;
  80100. }
  80101. if (!subMaterial.isReady(mesh)) {
  80102. return false;
  80103. }
  80104. }
  80105. }
  80106. return true;
  80107. };
  80108. /**
  80109. * Clones the current material and its related sub materials
  80110. * @param name Define the name of the newly cloned material
  80111. * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance
  80112. * @returns the cloned material
  80113. */
  80114. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  80115. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  80116. for (var index = 0; index < this.subMaterials.length; index++) {
  80117. var subMaterial = null;
  80118. var current = this.subMaterials[index];
  80119. if (cloneChildren && current) {
  80120. subMaterial = current.clone(name + "-" + current.name);
  80121. }
  80122. else {
  80123. subMaterial = this.subMaterials[index];
  80124. }
  80125. newMultiMaterial.subMaterials.push(subMaterial);
  80126. }
  80127. return newMultiMaterial;
  80128. };
  80129. /**
  80130. * Serializes the materials into a JSON representation.
  80131. * @returns the JSON representation
  80132. */
  80133. MultiMaterial.prototype.serialize = function () {
  80134. var serializationObject = {};
  80135. serializationObject.name = this.name;
  80136. serializationObject.id = this.id;
  80137. if (BABYLON.Tags) {
  80138. serializationObject.tags = BABYLON.Tags.GetTags(this);
  80139. }
  80140. serializationObject.materials = [];
  80141. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  80142. var subMat = this.subMaterials[matIndex];
  80143. if (subMat) {
  80144. serializationObject.materials.push(subMat.id);
  80145. }
  80146. else {
  80147. serializationObject.materials.push(null);
  80148. }
  80149. }
  80150. return serializationObject;
  80151. };
  80152. /**
  80153. * Dispose the material and release its associated resources
  80154. * @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)
  80155. * @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)
  80156. */
  80157. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  80158. var scene = this.getScene();
  80159. if (!scene) {
  80160. return;
  80161. }
  80162. var index = scene.multiMaterials.indexOf(this);
  80163. if (index >= 0) {
  80164. scene.multiMaterials.splice(index, 1);
  80165. }
  80166. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  80167. };
  80168. return MultiMaterial;
  80169. }(BABYLON.Material));
  80170. BABYLON.MultiMaterial = MultiMaterial;
  80171. })(BABYLON || (BABYLON = {}));
  80172. //# sourceMappingURL=multiMaterial.js.map
  80173. var BABYLON;
  80174. (function (BABYLON) {
  80175. /**
  80176. * Manage the touch inputs to control the movement of a free camera.
  80177. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  80178. */
  80179. var FreeCameraTouchInput = /** @class */ (function () {
  80180. function FreeCameraTouchInput() {
  80181. /**
  80182. * Defines the touch sensibility for rotation.
  80183. * The higher the faster.
  80184. */
  80185. this.touchAngularSensibility = 200000.0;
  80186. /**
  80187. * Defines the touch sensibility for move.
  80188. * The higher the faster.
  80189. */
  80190. this.touchMoveSensibility = 250.0;
  80191. this._offsetX = null;
  80192. this._offsetY = null;
  80193. this._pointerPressed = new Array();
  80194. }
  80195. /**
  80196. * Attach the input controls to a specific dom element to get the input from.
  80197. * @param element Defines the element the controls should be listened from
  80198. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  80199. */
  80200. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  80201. var _this = this;
  80202. var previousPosition = null;
  80203. if (this._pointerInput === undefined) {
  80204. this._onLostFocus = function (evt) {
  80205. _this._offsetX = null;
  80206. _this._offsetY = null;
  80207. };
  80208. this._pointerInput = function (p, s) {
  80209. var evt = p.event;
  80210. if (evt.pointerType === "mouse") {
  80211. return;
  80212. }
  80213. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  80214. if (!noPreventDefault) {
  80215. evt.preventDefault();
  80216. }
  80217. _this._pointerPressed.push(evt.pointerId);
  80218. if (_this._pointerPressed.length !== 1) {
  80219. return;
  80220. }
  80221. previousPosition = {
  80222. x: evt.clientX,
  80223. y: evt.clientY
  80224. };
  80225. }
  80226. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  80227. if (!noPreventDefault) {
  80228. evt.preventDefault();
  80229. }
  80230. var index = _this._pointerPressed.indexOf(evt.pointerId);
  80231. if (index === -1) {
  80232. return;
  80233. }
  80234. _this._pointerPressed.splice(index, 1);
  80235. if (index != 0) {
  80236. return;
  80237. }
  80238. previousPosition = null;
  80239. _this._offsetX = null;
  80240. _this._offsetY = null;
  80241. }
  80242. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  80243. if (!noPreventDefault) {
  80244. evt.preventDefault();
  80245. }
  80246. if (!previousPosition) {
  80247. return;
  80248. }
  80249. var index = _this._pointerPressed.indexOf(evt.pointerId);
  80250. if (index != 0) {
  80251. return;
  80252. }
  80253. _this._offsetX = evt.clientX - previousPosition.x;
  80254. _this._offsetY = -(evt.clientY - previousPosition.y);
  80255. }
  80256. };
  80257. }
  80258. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  80259. if (this._onLostFocus) {
  80260. element.addEventListener("blur", this._onLostFocus);
  80261. }
  80262. };
  80263. /**
  80264. * Detach the current controls from the specified dom element.
  80265. * @param element Defines the element to stop listening the inputs from
  80266. */
  80267. FreeCameraTouchInput.prototype.detachControl = function (element) {
  80268. if (this._pointerInput && element) {
  80269. if (this._observer) {
  80270. this.camera.getScene().onPointerObservable.remove(this._observer);
  80271. this._observer = null;
  80272. }
  80273. if (this._onLostFocus) {
  80274. element.removeEventListener("blur", this._onLostFocus);
  80275. this._onLostFocus = null;
  80276. }
  80277. this._pointerPressed = [];
  80278. this._offsetX = null;
  80279. this._offsetY = null;
  80280. }
  80281. };
  80282. /**
  80283. * Update the current camera state depending on the inputs that have been used this frame.
  80284. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  80285. */
  80286. FreeCameraTouchInput.prototype.checkInputs = function () {
  80287. if (this._offsetX && this._offsetY) {
  80288. var camera = this.camera;
  80289. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  80290. if (this._pointerPressed.length > 1) {
  80291. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  80292. }
  80293. else {
  80294. var speed = camera._computeLocalCameraSpeed();
  80295. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  80296. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  80297. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  80298. }
  80299. }
  80300. };
  80301. /**
  80302. * Gets the class name of the current intput.
  80303. * @returns the class name
  80304. */
  80305. FreeCameraTouchInput.prototype.getClassName = function () {
  80306. return "FreeCameraTouchInput";
  80307. };
  80308. /**
  80309. * Get the friendly name associated with the input class.
  80310. * @returns the input friendly name
  80311. */
  80312. FreeCameraTouchInput.prototype.getSimpleName = function () {
  80313. return "touch";
  80314. };
  80315. __decorate([
  80316. BABYLON.serialize()
  80317. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  80318. __decorate([
  80319. BABYLON.serialize()
  80320. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  80321. return FreeCameraTouchInput;
  80322. }());
  80323. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  80324. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  80325. })(BABYLON || (BABYLON = {}));
  80326. //# sourceMappingURL=freeCameraTouchInput.js.map
  80327. var BABYLON;
  80328. (function (BABYLON) {
  80329. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  80330. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  80331. });
  80332. /**
  80333. * This represents a FPS type of camera controlled by touch.
  80334. * This is like a universal camera minus the Gamepad controls.
  80335. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  80336. */
  80337. var TouchCamera = /** @class */ (function (_super) {
  80338. __extends(TouchCamera, _super);
  80339. /**
  80340. * Instantiates a new touch camera.
  80341. * This represents a FPS type of camera controlled by touch.
  80342. * This is like a universal camera minus the Gamepad controls.
  80343. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  80344. * @param name Define the name of the camera in the scene
  80345. * @param position Define the start position of the camera in the scene
  80346. * @param scene Define the scene the camera belongs to
  80347. */
  80348. function TouchCamera(name, position, scene) {
  80349. var _this = _super.call(this, name, position, scene) || this;
  80350. _this.inputs.addTouch();
  80351. _this._setupInputs();
  80352. return _this;
  80353. }
  80354. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  80355. /**
  80356. * Defines the touch sensibility for rotation.
  80357. * The higher the faster.
  80358. */
  80359. get: function () {
  80360. var touch = this.inputs.attached["touch"];
  80361. if (touch) {
  80362. return touch.touchAngularSensibility;
  80363. }
  80364. return 0;
  80365. },
  80366. set: function (value) {
  80367. var touch = this.inputs.attached["touch"];
  80368. if (touch) {
  80369. touch.touchAngularSensibility = value;
  80370. }
  80371. },
  80372. enumerable: true,
  80373. configurable: true
  80374. });
  80375. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  80376. /**
  80377. * Defines the touch sensibility for move.
  80378. * The higher the faster.
  80379. */
  80380. get: function () {
  80381. var touch = this.inputs.attached["touch"];
  80382. if (touch) {
  80383. return touch.touchMoveSensibility;
  80384. }
  80385. return 0;
  80386. },
  80387. set: function (value) {
  80388. var touch = this.inputs.attached["touch"];
  80389. if (touch) {
  80390. touch.touchMoveSensibility = value;
  80391. }
  80392. },
  80393. enumerable: true,
  80394. configurable: true
  80395. });
  80396. /**
  80397. * Gets the current object class name.
  80398. * @return the class name
  80399. */
  80400. TouchCamera.prototype.getClassName = function () {
  80401. return "TouchCamera";
  80402. };
  80403. /** @hidden */
  80404. TouchCamera.prototype._setupInputs = function () {
  80405. var mouse = this.inputs.attached["mouse"];
  80406. if (mouse) {
  80407. mouse.touchEnabled = false;
  80408. }
  80409. };
  80410. return TouchCamera;
  80411. }(BABYLON.FreeCamera));
  80412. BABYLON.TouchCamera = TouchCamera;
  80413. })(BABYLON || (BABYLON = {}));
  80414. //# sourceMappingURL=touchCamera.js.map
  80415. var BABYLON;
  80416. (function (BABYLON) {
  80417. /**
  80418. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  80419. * This is the base class of any Procedural texture and contains most of the shareable code.
  80420. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  80421. */
  80422. var ProceduralTexture = /** @class */ (function (_super) {
  80423. __extends(ProceduralTexture, _super);
  80424. /**
  80425. * Instantiates a new procedural texture.
  80426. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  80427. * This is the base class of any Procedural texture and contains most of the shareable code.
  80428. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  80429. * @param name Define the name of the texture
  80430. * @param size Define the size of the texture to create
  80431. * @param fragment Define the fragment shader to use to generate the texture or null if it is defined later
  80432. * @param scene Define the scene the texture belongs to
  80433. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  80434. * @param generateMipMaps Define if the texture should creates mip maps or not
  80435. * @param isCube Define if the texture is a cube texture or not (this will render each faces of the cube)
  80436. */
  80437. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  80438. if (fallbackTexture === void 0) { fallbackTexture = null; }
  80439. if (generateMipMaps === void 0) { generateMipMaps = true; }
  80440. if (isCube === void 0) { isCube = false; }
  80441. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  80442. _this.isCube = isCube;
  80443. /**
  80444. * Define if the texture is enabled or not (disabled texture will not render)
  80445. */
  80446. _this.isEnabled = true;
  80447. /**
  80448. * Define if the texture must be cleared before rendering (default is true)
  80449. */
  80450. _this.autoClear = true;
  80451. /**
  80452. * Event raised when the texture is generated
  80453. */
  80454. _this.onGeneratedObservable = new BABYLON.Observable();
  80455. /** @hidden */
  80456. _this._textures = {};
  80457. _this._currentRefreshId = -1;
  80458. _this._refreshRate = 1;
  80459. _this._vertexBuffers = {};
  80460. _this._uniforms = new Array();
  80461. _this._samplers = new Array();
  80462. _this._floats = {};
  80463. _this._ints = {};
  80464. _this._floatsArrays = {};
  80465. _this._colors3 = {};
  80466. _this._colors4 = {};
  80467. _this._vectors2 = {};
  80468. _this._vectors3 = {};
  80469. _this._matrices = {};
  80470. _this._fallbackTextureUsed = false;
  80471. _this._cachedDefines = "";
  80472. _this._contentUpdateId = -1;
  80473. scene = _this.getScene();
  80474. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  80475. if (!component) {
  80476. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  80477. scene._addComponent(component);
  80478. }
  80479. scene.proceduralTextures.push(_this);
  80480. _this._engine = scene.getEngine();
  80481. _this.name = name;
  80482. _this.isRenderTarget = true;
  80483. _this._size = size;
  80484. _this._generateMipMaps = generateMipMaps;
  80485. _this.setFragment(fragment);
  80486. _this._fallbackTexture = fallbackTexture;
  80487. if (isCube) {
  80488. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps, generateDepthBuffer: false, generateStencilBuffer: false });
  80489. _this.setFloat("face", 0);
  80490. }
  80491. else {
  80492. _this._texture = _this._engine.createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, generateDepthBuffer: false, generateStencilBuffer: false });
  80493. }
  80494. // VBO
  80495. var vertices = [];
  80496. vertices.push(1, 1);
  80497. vertices.push(-1, 1);
  80498. vertices.push(-1, -1);
  80499. vertices.push(1, -1);
  80500. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  80501. _this._createIndexBuffer();
  80502. return _this;
  80503. }
  80504. /**
  80505. * The effect that is created when initializing the post process.
  80506. * @returns The created effect corrisponding the the postprocess.
  80507. */
  80508. ProceduralTexture.prototype.getEffect = function () {
  80509. return this._effect;
  80510. };
  80511. /**
  80512. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  80513. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  80514. */
  80515. ProceduralTexture.prototype.getContent = function () {
  80516. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  80517. return this._contentData;
  80518. }
  80519. this._contentData = this.readPixels(0, 0, this._contentData);
  80520. this._contentUpdateId = this._currentRefreshId;
  80521. return this._contentData;
  80522. };
  80523. ProceduralTexture.prototype._createIndexBuffer = function () {
  80524. var engine = this._engine;
  80525. // Indices
  80526. var indices = [];
  80527. indices.push(0);
  80528. indices.push(1);
  80529. indices.push(2);
  80530. indices.push(0);
  80531. indices.push(2);
  80532. indices.push(3);
  80533. this._indexBuffer = engine.createIndexBuffer(indices);
  80534. };
  80535. /** @hidden */
  80536. ProceduralTexture.prototype._rebuild = function () {
  80537. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80538. if (vb) {
  80539. vb._rebuild();
  80540. }
  80541. this._createIndexBuffer();
  80542. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  80543. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  80544. }
  80545. };
  80546. /**
  80547. * Resets the texture in order to recreate its associated resources.
  80548. * This can be called in case of context loss
  80549. */
  80550. ProceduralTexture.prototype.reset = function () {
  80551. if (this._effect === undefined) {
  80552. return;
  80553. }
  80554. var engine = this._engine;
  80555. engine._releaseEffect(this._effect);
  80556. };
  80557. ProceduralTexture.prototype._getDefines = function () {
  80558. return "";
  80559. };
  80560. /**
  80561. * Is the texture ready to be used ? (rendered at least once)
  80562. * @returns true if ready, otherwise, false.
  80563. */
  80564. ProceduralTexture.prototype.isReady = function () {
  80565. var _this = this;
  80566. var engine = this._engine;
  80567. var shaders;
  80568. if (!this._fragment) {
  80569. return false;
  80570. }
  80571. if (this._fallbackTextureUsed) {
  80572. return true;
  80573. }
  80574. var defines = this._getDefines();
  80575. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  80576. return true;
  80577. }
  80578. if (this._fragment.fragmentElement !== undefined) {
  80579. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  80580. }
  80581. else {
  80582. shaders = { vertex: "procedural", fragment: this._fragment };
  80583. }
  80584. this._cachedDefines = defines;
  80585. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  80586. _this.releaseInternalTexture();
  80587. if (_this._fallbackTexture) {
  80588. _this._texture = _this._fallbackTexture._texture;
  80589. if (_this._texture) {
  80590. _this._texture.incrementReferences();
  80591. }
  80592. }
  80593. _this._fallbackTextureUsed = true;
  80594. });
  80595. return this._effect.isReady();
  80596. };
  80597. /**
  80598. * Resets the refresh counter of the texture and start bak from scratch.
  80599. * Could be usefull to regenerate the texture if it is setup to render only once.
  80600. */
  80601. ProceduralTexture.prototype.resetRefreshCounter = function () {
  80602. this._currentRefreshId = -1;
  80603. };
  80604. /**
  80605. * Set the fragment shader to use in order to render the texture.
  80606. * @param fragment This can be set to a path (into the shader store) or to a json object containing a fragmentElement property.
  80607. */
  80608. ProceduralTexture.prototype.setFragment = function (fragment) {
  80609. this._fragment = fragment;
  80610. };
  80611. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  80612. /**
  80613. * Define the refresh rate of the texture or the rendering frequency.
  80614. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  80615. */
  80616. get: function () {
  80617. return this._refreshRate;
  80618. },
  80619. set: function (value) {
  80620. this._refreshRate = value;
  80621. this.resetRefreshCounter();
  80622. },
  80623. enumerable: true,
  80624. configurable: true
  80625. });
  80626. /** @hidden */
  80627. ProceduralTexture.prototype._shouldRender = function () {
  80628. if (!this.isEnabled || !this.isReady() || !this._texture) {
  80629. if (this._texture) {
  80630. this._texture.isReady = false;
  80631. }
  80632. return false;
  80633. }
  80634. if (this._fallbackTextureUsed) {
  80635. return false;
  80636. }
  80637. if (this._currentRefreshId === -1) { // At least render once
  80638. this._currentRefreshId = 1;
  80639. return true;
  80640. }
  80641. if (this.refreshRate === this._currentRefreshId) {
  80642. this._currentRefreshId = 1;
  80643. return true;
  80644. }
  80645. this._currentRefreshId++;
  80646. return false;
  80647. };
  80648. /**
  80649. * Get the size the texture is rendering at.
  80650. * @returns the size (texture is always squared)
  80651. */
  80652. ProceduralTexture.prototype.getRenderSize = function () {
  80653. return this._size;
  80654. };
  80655. /**
  80656. * Resize the texture to new value.
  80657. * @param size Define the new size the texture should have
  80658. * @param generateMipMaps Define whether the new texture should create mip maps
  80659. */
  80660. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  80661. if (this._fallbackTextureUsed) {
  80662. return;
  80663. }
  80664. this.releaseInternalTexture();
  80665. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  80666. // Update properties
  80667. this._size = size;
  80668. this._generateMipMaps = generateMipMaps;
  80669. };
  80670. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  80671. if (this._uniforms.indexOf(uniformName) === -1) {
  80672. this._uniforms.push(uniformName);
  80673. }
  80674. };
  80675. /**
  80676. * Set a texture in the shader program used to render.
  80677. * @param name Define the name of the uniform samplers as defined in the shader
  80678. * @param texture Define the texture to bind to this sampler
  80679. * @return the texture itself allowing "fluent" like uniform updates
  80680. */
  80681. ProceduralTexture.prototype.setTexture = function (name, texture) {
  80682. if (this._samplers.indexOf(name) === -1) {
  80683. this._samplers.push(name);
  80684. }
  80685. this._textures[name] = texture;
  80686. return this;
  80687. };
  80688. /**
  80689. * Set a float in the shader.
  80690. * @param name Define the name of the uniform as defined in the shader
  80691. * @param value Define the value to give to the uniform
  80692. * @return the texture itself allowing "fluent" like uniform updates
  80693. */
  80694. ProceduralTexture.prototype.setFloat = function (name, value) {
  80695. this._checkUniform(name);
  80696. this._floats[name] = value;
  80697. return this;
  80698. };
  80699. /**
  80700. * Set a int in the shader.
  80701. * @param name Define the name of the uniform as defined in the shader
  80702. * @param value Define the value to give to the uniform
  80703. * @return the texture itself allowing "fluent" like uniform updates
  80704. */
  80705. ProceduralTexture.prototype.setInt = function (name, value) {
  80706. this._checkUniform(name);
  80707. this._ints[name] = value;
  80708. return this;
  80709. };
  80710. /**
  80711. * Set an array of floats in the shader.
  80712. * @param name Define the name of the uniform as defined in the shader
  80713. * @param value Define the value to give to the uniform
  80714. * @return the texture itself allowing "fluent" like uniform updates
  80715. */
  80716. ProceduralTexture.prototype.setFloats = function (name, value) {
  80717. this._checkUniform(name);
  80718. this._floatsArrays[name] = value;
  80719. return this;
  80720. };
  80721. /**
  80722. * Set a vec3 in the shader from a Color3.
  80723. * @param name Define the name of the uniform as defined in the shader
  80724. * @param value Define the value to give to the uniform
  80725. * @return the texture itself allowing "fluent" like uniform updates
  80726. */
  80727. ProceduralTexture.prototype.setColor3 = function (name, value) {
  80728. this._checkUniform(name);
  80729. this._colors3[name] = value;
  80730. return this;
  80731. };
  80732. /**
  80733. * Set a vec4 in the shader from a Color4.
  80734. * @param name Define the name of the uniform as defined in the shader
  80735. * @param value Define the value to give to the uniform
  80736. * @return the texture itself allowing "fluent" like uniform updates
  80737. */
  80738. ProceduralTexture.prototype.setColor4 = function (name, value) {
  80739. this._checkUniform(name);
  80740. this._colors4[name] = value;
  80741. return this;
  80742. };
  80743. /**
  80744. * Set a vec2 in the shader from a Vector2.
  80745. * @param name Define the name of the uniform as defined in the shader
  80746. * @param value Define the value to give to the uniform
  80747. * @return the texture itself allowing "fluent" like uniform updates
  80748. */
  80749. ProceduralTexture.prototype.setVector2 = function (name, value) {
  80750. this._checkUniform(name);
  80751. this._vectors2[name] = value;
  80752. return this;
  80753. };
  80754. /**
  80755. * Set a vec3 in the shader from a Vector3.
  80756. * @param name Define the name of the uniform as defined in the shader
  80757. * @param value Define the value to give to the uniform
  80758. * @return the texture itself allowing "fluent" like uniform updates
  80759. */
  80760. ProceduralTexture.prototype.setVector3 = function (name, value) {
  80761. this._checkUniform(name);
  80762. this._vectors3[name] = value;
  80763. return this;
  80764. };
  80765. /**
  80766. * Set a mat4 in the shader from a MAtrix.
  80767. * @param name Define the name of the uniform as defined in the shader
  80768. * @param value Define the value to give to the uniform
  80769. * @return the texture itself allowing "fluent" like uniform updates
  80770. */
  80771. ProceduralTexture.prototype.setMatrix = function (name, value) {
  80772. this._checkUniform(name);
  80773. this._matrices[name] = value;
  80774. return this;
  80775. };
  80776. /**
  80777. * Render the texture to its associated render target.
  80778. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  80779. */
  80780. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  80781. var scene = this.getScene();
  80782. if (!scene) {
  80783. return;
  80784. }
  80785. var engine = this._engine;
  80786. // Render
  80787. engine.enableEffect(this._effect);
  80788. engine.setState(false);
  80789. // Texture
  80790. for (var name in this._textures) {
  80791. this._effect.setTexture(name, this._textures[name]);
  80792. }
  80793. // Float
  80794. for (name in this._ints) {
  80795. this._effect.setInt(name, this._ints[name]);
  80796. }
  80797. // Float
  80798. for (name in this._floats) {
  80799. this._effect.setFloat(name, this._floats[name]);
  80800. }
  80801. // Floats
  80802. for (name in this._floatsArrays) {
  80803. this._effect.setArray(name, this._floatsArrays[name]);
  80804. }
  80805. // Color3
  80806. for (name in this._colors3) {
  80807. this._effect.setColor3(name, this._colors3[name]);
  80808. }
  80809. // Color4
  80810. for (name in this._colors4) {
  80811. var color = this._colors4[name];
  80812. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  80813. }
  80814. // Vector2
  80815. for (name in this._vectors2) {
  80816. this._effect.setVector2(name, this._vectors2[name]);
  80817. }
  80818. // Vector3
  80819. for (name in this._vectors3) {
  80820. this._effect.setVector3(name, this._vectors3[name]);
  80821. }
  80822. // Matrix
  80823. for (name in this._matrices) {
  80824. this._effect.setMatrix(name, this._matrices[name]);
  80825. }
  80826. if (!this._texture) {
  80827. return;
  80828. }
  80829. if (this.isCube) {
  80830. for (var face = 0; face < 6; face++) {
  80831. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  80832. // VBOs
  80833. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  80834. this._effect.setFloat("face", face);
  80835. // Clear
  80836. if (this.autoClear) {
  80837. engine.clear(scene.clearColor, true, false, false);
  80838. }
  80839. // Draw order
  80840. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80841. // Mipmaps
  80842. if (face === 5) {
  80843. engine.generateMipMapsForCubemap(this._texture);
  80844. }
  80845. }
  80846. }
  80847. else {
  80848. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  80849. // VBOs
  80850. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  80851. // Clear
  80852. if (this.autoClear) {
  80853. engine.clear(scene.clearColor, true, false, false);
  80854. }
  80855. // Draw order
  80856. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80857. }
  80858. // Unbind
  80859. engine.unBindFramebuffer(this._texture, this.isCube);
  80860. if (this.onGenerated) {
  80861. this.onGenerated();
  80862. }
  80863. this.onGeneratedObservable.notifyObservers(this);
  80864. };
  80865. /**
  80866. * Clone the texture.
  80867. * @returns the cloned texture
  80868. */
  80869. ProceduralTexture.prototype.clone = function () {
  80870. var textureSize = this.getSize();
  80871. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  80872. // Base texture
  80873. newTexture.hasAlpha = this.hasAlpha;
  80874. newTexture.level = this.level;
  80875. // RenderTarget Texture
  80876. newTexture.coordinatesMode = this.coordinatesMode;
  80877. return newTexture;
  80878. };
  80879. /**
  80880. * Dispose the texture and release its asoociated resources.
  80881. */
  80882. ProceduralTexture.prototype.dispose = function () {
  80883. var scene = this.getScene();
  80884. if (!scene) {
  80885. return;
  80886. }
  80887. var index = scene.proceduralTextures.indexOf(this);
  80888. if (index >= 0) {
  80889. scene.proceduralTextures.splice(index, 1);
  80890. }
  80891. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80892. if (vertexBuffer) {
  80893. vertexBuffer.dispose();
  80894. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80895. }
  80896. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  80897. this._indexBuffer = null;
  80898. }
  80899. _super.prototype.dispose.call(this);
  80900. };
  80901. __decorate([
  80902. BABYLON.serialize()
  80903. ], ProceduralTexture.prototype, "isEnabled", void 0);
  80904. __decorate([
  80905. BABYLON.serialize()
  80906. ], ProceduralTexture.prototype, "autoClear", void 0);
  80907. __decorate([
  80908. BABYLON.serialize()
  80909. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  80910. __decorate([
  80911. BABYLON.serialize()
  80912. ], ProceduralTexture.prototype, "_size", void 0);
  80913. __decorate([
  80914. BABYLON.serialize()
  80915. ], ProceduralTexture.prototype, "refreshRate", null);
  80916. return ProceduralTexture;
  80917. }(BABYLON.Texture));
  80918. BABYLON.ProceduralTexture = ProceduralTexture;
  80919. })(BABYLON || (BABYLON = {}));
  80920. //# sourceMappingURL=proceduralTexture.js.map
  80921. var BABYLON;
  80922. (function (BABYLON) {
  80923. /**
  80924. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  80925. * in a given scene.
  80926. */
  80927. var ProceduralTextureSceneComponent = /** @class */ (function () {
  80928. /**
  80929. * Creates a new instance of the component for the given scene
  80930. * @param scene Defines the scene to register the component in
  80931. */
  80932. function ProceduralTextureSceneComponent(scene) {
  80933. /**
  80934. * The component name helpfull to identify the component in the list of scene components.
  80935. */
  80936. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  80937. this.scene = scene;
  80938. this.scene.proceduralTextures = new Array();
  80939. scene.layers = new Array();
  80940. }
  80941. /**
  80942. * Registers the component in a given scene
  80943. */
  80944. ProceduralTextureSceneComponent.prototype.register = function () {
  80945. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  80946. };
  80947. /**
  80948. * Rebuilds the elements related to this component in case of
  80949. * context lost for instance.
  80950. */
  80951. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  80952. // Nothing to do here.
  80953. };
  80954. /**
  80955. * Disposes the component and the associated ressources.
  80956. */
  80957. ProceduralTextureSceneComponent.prototype.dispose = function () {
  80958. // Nothing to do here.
  80959. };
  80960. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  80961. if (this.scene.proceduralTexturesEnabled) {
  80962. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  80963. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  80964. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  80965. if (proceduralTexture._shouldRender()) {
  80966. proceduralTexture.render();
  80967. }
  80968. }
  80969. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  80970. }
  80971. };
  80972. return ProceduralTextureSceneComponent;
  80973. }());
  80974. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  80975. })(BABYLON || (BABYLON = {}));
  80976. //# sourceMappingURL=proceduralTextureSceneComponent.js.map
  80977. var BABYLON;
  80978. (function (BABYLON) {
  80979. /**
  80980. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  80981. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  80982. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  80983. */
  80984. var CustomProceduralTexture = /** @class */ (function (_super) {
  80985. __extends(CustomProceduralTexture, _super);
  80986. /**
  80987. * Instantiates a new Custom Procedural Texture.
  80988. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  80989. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  80990. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  80991. * @param name Define the name of the texture
  80992. * @param texturePath Define the folder path containing all the cutom texture related files (config, shaders...)
  80993. * @param size Define the size of the texture to create
  80994. * @param scene Define the scene the texture belongs to
  80995. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  80996. * @param generateMipMaps Define if the texture should creates mip maps or not
  80997. */
  80998. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  80999. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  81000. _this._animate = true;
  81001. _this._time = 0;
  81002. _this._texturePath = texturePath;
  81003. //Try to load json
  81004. _this._loadJson(texturePath);
  81005. _this.refreshRate = 1;
  81006. return _this;
  81007. }
  81008. CustomProceduralTexture.prototype._loadJson = function (jsonUrl) {
  81009. var _this = this;
  81010. var noConfigFile = function () {
  81011. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  81012. try {
  81013. _this.setFragment(_this._texturePath);
  81014. }
  81015. catch (ex) {
  81016. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  81017. }
  81018. };
  81019. var configFileUrl = jsonUrl + "/config.json";
  81020. var xhr = new XMLHttpRequest();
  81021. xhr.open("GET", configFileUrl, true);
  81022. xhr.addEventListener("load", function () {
  81023. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  81024. try {
  81025. _this._config = JSON.parse(xhr.response);
  81026. _this.updateShaderUniforms();
  81027. _this.updateTextures();
  81028. _this.setFragment(_this._texturePath + "/custom");
  81029. _this._animate = _this._config.animate;
  81030. _this.refreshRate = _this._config.refreshrate;
  81031. }
  81032. catch (ex) {
  81033. noConfigFile();
  81034. }
  81035. }
  81036. else {
  81037. noConfigFile();
  81038. }
  81039. }, false);
  81040. xhr.addEventListener("error", function () {
  81041. noConfigFile();
  81042. }, false);
  81043. try {
  81044. xhr.send();
  81045. }
  81046. catch (ex) {
  81047. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  81048. }
  81049. };
  81050. /**
  81051. * Is the texture ready to be used ? (rendered at least once)
  81052. * @returns true if ready, otherwise, false.
  81053. */
  81054. CustomProceduralTexture.prototype.isReady = function () {
  81055. if (!_super.prototype.isReady.call(this)) {
  81056. return false;
  81057. }
  81058. for (var name in this._textures) {
  81059. var texture = this._textures[name];
  81060. if (!texture.isReady()) {
  81061. return false;
  81062. }
  81063. }
  81064. return true;
  81065. };
  81066. /**
  81067. * Render the texture to its associated render target.
  81068. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  81069. */
  81070. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  81071. var scene = this.getScene();
  81072. if (this._animate && scene) {
  81073. this._time += scene.getAnimationRatio() * 0.03;
  81074. this.updateShaderUniforms();
  81075. }
  81076. _super.prototype.render.call(this, useCameraPostProcess);
  81077. };
  81078. /**
  81079. * Update the list of dependant textures samplers in the shader.
  81080. */
  81081. CustomProceduralTexture.prototype.updateTextures = function () {
  81082. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  81083. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  81084. }
  81085. };
  81086. /**
  81087. * Update the uniform values of the procedural texture in the shader.
  81088. */
  81089. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  81090. if (this._config) {
  81091. for (var j = 0; j < this._config.uniforms.length; j++) {
  81092. var uniform = this._config.uniforms[j];
  81093. switch (uniform.type) {
  81094. case "float":
  81095. this.setFloat(uniform.name, uniform.value);
  81096. break;
  81097. case "color3":
  81098. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  81099. break;
  81100. case "color4":
  81101. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  81102. break;
  81103. case "vector2":
  81104. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  81105. break;
  81106. case "vector3":
  81107. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  81108. break;
  81109. }
  81110. }
  81111. }
  81112. this.setFloat("time", this._time);
  81113. };
  81114. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  81115. /**
  81116. * Define if the texture animates or not.
  81117. */
  81118. get: function () {
  81119. return this._animate;
  81120. },
  81121. set: function (value) {
  81122. this._animate = value;
  81123. },
  81124. enumerable: true,
  81125. configurable: true
  81126. });
  81127. return CustomProceduralTexture;
  81128. }(BABYLON.ProceduralTexture));
  81129. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  81130. })(BABYLON || (BABYLON = {}));
  81131. //# sourceMappingURL=customProceduralTexture.js.map
  81132. var BABYLON;
  81133. (function (BABYLON) {
  81134. /**
  81135. * Manage the gamepad inputs to control a free camera.
  81136. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  81137. */
  81138. var FreeCameraGamepadInput = /** @class */ (function () {
  81139. function FreeCameraGamepadInput() {
  81140. /**
  81141. * Defines the gamepad rotation sensiblity.
  81142. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  81143. */
  81144. this.gamepadAngularSensibility = 200;
  81145. /**
  81146. * Defines the gamepad move sensiblity.
  81147. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  81148. */
  81149. this.gamepadMoveSensibility = 40;
  81150. this._cameraTransform = BABYLON.Matrix.Identity();
  81151. this._deltaTransform = BABYLON.Vector3.Zero();
  81152. this._vector3 = BABYLON.Vector3.Zero();
  81153. this._vector2 = BABYLON.Vector2.Zero();
  81154. }
  81155. /**
  81156. * Attach the input controls to a specific dom element to get the input from.
  81157. * @param element Defines the element the controls should be listened from
  81158. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  81159. */
  81160. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  81161. var _this = this;
  81162. var manager = this.camera.getScene().gamepadManager;
  81163. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  81164. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  81165. // prioritize XBOX gamepads.
  81166. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  81167. _this.gamepad = gamepad;
  81168. }
  81169. }
  81170. });
  81171. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  81172. if (_this.gamepad === gamepad) {
  81173. _this.gamepad = null;
  81174. }
  81175. });
  81176. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  81177. };
  81178. /**
  81179. * Detach the current controls from the specified dom element.
  81180. * @param element Defines the element to stop listening the inputs from
  81181. */
  81182. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  81183. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  81184. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  81185. this.gamepad = null;
  81186. };
  81187. /**
  81188. * Update the current camera state depending on the inputs that have been used this frame.
  81189. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  81190. */
  81191. FreeCameraGamepadInput.prototype.checkInputs = function () {
  81192. if (this.gamepad && this.gamepad.leftStick) {
  81193. var camera = this.camera;
  81194. var LSValues = this.gamepad.leftStick;
  81195. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  81196. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  81197. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  81198. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  81199. var RSValues = this.gamepad.rightStick;
  81200. if (RSValues) {
  81201. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  81202. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  81203. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  81204. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  81205. }
  81206. else {
  81207. RSValues = { x: 0, y: 0 };
  81208. }
  81209. if (!camera.rotationQuaternion) {
  81210. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  81211. }
  81212. else {
  81213. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  81214. }
  81215. var speed = camera._computeLocalCameraSpeed() * 50.0;
  81216. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  81217. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  81218. camera.cameraDirection.addInPlace(this._deltaTransform);
  81219. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  81220. camera.cameraRotation.addInPlace(this._vector2);
  81221. }
  81222. };
  81223. /**
  81224. * Gets the class name of the current intput.
  81225. * @returns the class name
  81226. */
  81227. FreeCameraGamepadInput.prototype.getClassName = function () {
  81228. return "FreeCameraGamepadInput";
  81229. };
  81230. /**
  81231. * Get the friendly name associated with the input class.
  81232. * @returns the input friendly name
  81233. */
  81234. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  81235. return "gamepad";
  81236. };
  81237. __decorate([
  81238. BABYLON.serialize()
  81239. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  81240. __decorate([
  81241. BABYLON.serialize()
  81242. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  81243. return FreeCameraGamepadInput;
  81244. }());
  81245. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  81246. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  81247. })(BABYLON || (BABYLON = {}));
  81248. //# sourceMappingURL=freeCameraGamepadInput.js.map
  81249. var BABYLON;
  81250. (function (BABYLON) {
  81251. /**
  81252. * Manage the gamepad inputs to control an arc rotate camera.
  81253. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  81254. */
  81255. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  81256. function ArcRotateCameraGamepadInput() {
  81257. /**
  81258. * Defines the gamepad rotation sensiblity.
  81259. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  81260. */
  81261. this.gamepadRotationSensibility = 80;
  81262. /**
  81263. * Defines the gamepad move sensiblity.
  81264. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  81265. */
  81266. this.gamepadMoveSensibility = 40;
  81267. }
  81268. /**
  81269. * Attach the input controls to a specific dom element to get the input from.
  81270. * @param element Defines the element the controls should be listened from
  81271. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  81272. */
  81273. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  81274. var _this = this;
  81275. var manager = this.camera.getScene().gamepadManager;
  81276. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  81277. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  81278. // prioritize XBOX gamepads.
  81279. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  81280. _this.gamepad = gamepad;
  81281. }
  81282. }
  81283. });
  81284. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  81285. if (_this.gamepad === gamepad) {
  81286. _this.gamepad = null;
  81287. }
  81288. });
  81289. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  81290. };
  81291. /**
  81292. * Detach the current controls from the specified dom element.
  81293. * @param element Defines the element to stop listening the inputs from
  81294. */
  81295. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  81296. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  81297. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  81298. this.gamepad = null;
  81299. };
  81300. /**
  81301. * Update the current camera state depending on the inputs that have been used this frame.
  81302. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  81303. */
  81304. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  81305. if (this.gamepad) {
  81306. var camera = this.camera;
  81307. var RSValues = this.gamepad.rightStick;
  81308. if (RSValues) {
  81309. if (RSValues.x != 0) {
  81310. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  81311. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  81312. camera.inertialAlphaOffset += normalizedRX;
  81313. }
  81314. }
  81315. if (RSValues.y != 0) {
  81316. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  81317. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  81318. camera.inertialBetaOffset += normalizedRY;
  81319. }
  81320. }
  81321. }
  81322. var LSValues = this.gamepad.leftStick;
  81323. if (LSValues && LSValues.y != 0) {
  81324. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  81325. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  81326. this.camera.inertialRadiusOffset -= normalizedLY;
  81327. }
  81328. }
  81329. }
  81330. };
  81331. /**
  81332. * Gets the class name of the current intput.
  81333. * @returns the class name
  81334. */
  81335. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  81336. return "ArcRotateCameraGamepadInput";
  81337. };
  81338. /**
  81339. * Get the friendly name associated with the input class.
  81340. * @returns the input friendly name
  81341. */
  81342. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  81343. return "gamepad";
  81344. };
  81345. __decorate([
  81346. BABYLON.serialize()
  81347. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  81348. __decorate([
  81349. BABYLON.serialize()
  81350. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  81351. return ArcRotateCameraGamepadInput;
  81352. }());
  81353. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  81354. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  81355. })(BABYLON || (BABYLON = {}));
  81356. //# sourceMappingURL=arcRotateCameraGamepadInput.js.map
  81357. var BABYLON;
  81358. (function (BABYLON) {
  81359. /**
  81360. * Manager for handling gamepads
  81361. */
  81362. var GamepadManager = /** @class */ (function () {
  81363. /**
  81364. * Initializes the gamepad manager
  81365. * @param _scene BabylonJS scene
  81366. */
  81367. function GamepadManager(_scene) {
  81368. var _this = this;
  81369. this._scene = _scene;
  81370. this._babylonGamepads = [];
  81371. this._oneGamepadConnected = false;
  81372. /** @hidden */
  81373. this._isMonitoring = false;
  81374. /**
  81375. * observable to be triggered when the gamepad controller has been disconnected
  81376. */
  81377. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  81378. if (!BABYLON.Tools.IsWindowObjectExist()) {
  81379. this._gamepadEventSupported = false;
  81380. }
  81381. else {
  81382. this._gamepadEventSupported = 'GamepadEvent' in window;
  81383. this._gamepadSupport = (navigator.getGamepads ||
  81384. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  81385. }
  81386. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  81387. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  81388. for (var i in _this._babylonGamepads) {
  81389. var gamepad = _this._babylonGamepads[i];
  81390. if (gamepad && gamepad._isConnected) {
  81391. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  81392. }
  81393. }
  81394. });
  81395. this._onGamepadConnectedEvent = function (evt) {
  81396. var gamepad = evt.gamepad;
  81397. if (gamepad.index in _this._babylonGamepads) {
  81398. if (_this._babylonGamepads[gamepad.index].isConnected) {
  81399. return;
  81400. }
  81401. }
  81402. var newGamepad;
  81403. if (_this._babylonGamepads[gamepad.index]) {
  81404. newGamepad = _this._babylonGamepads[gamepad.index];
  81405. newGamepad.browserGamepad = gamepad;
  81406. newGamepad._isConnected = true;
  81407. }
  81408. else {
  81409. newGamepad = _this._addNewGamepad(gamepad);
  81410. }
  81411. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  81412. _this._startMonitoringGamepads();
  81413. };
  81414. this._onGamepadDisconnectedEvent = function (evt) {
  81415. var gamepad = evt.gamepad;
  81416. // Remove the gamepad from the list of gamepads to monitor.
  81417. for (var i in _this._babylonGamepads) {
  81418. if (_this._babylonGamepads[i].index === gamepad.index) {
  81419. var disconnectedGamepad = _this._babylonGamepads[i];
  81420. disconnectedGamepad._isConnected = false;
  81421. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  81422. break;
  81423. }
  81424. }
  81425. };
  81426. if (this._gamepadSupport) {
  81427. //first add already-connected gamepads
  81428. this._updateGamepadObjects();
  81429. if (this._babylonGamepads.length) {
  81430. this._startMonitoringGamepads();
  81431. }
  81432. // Checking if the gamepad connected event is supported (like in Firefox)
  81433. if (this._gamepadEventSupported) {
  81434. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  81435. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  81436. }
  81437. else {
  81438. this._startMonitoringGamepads();
  81439. }
  81440. }
  81441. }
  81442. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  81443. /**
  81444. * The gamepads in the game pad manager
  81445. */
  81446. get: function () {
  81447. return this._babylonGamepads;
  81448. },
  81449. enumerable: true,
  81450. configurable: true
  81451. });
  81452. /**
  81453. * Get the gamepad controllers based on type
  81454. * @param type The type of gamepad controller
  81455. * @returns Nullable gamepad
  81456. */
  81457. GamepadManager.prototype.getGamepadByType = function (type) {
  81458. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  81459. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  81460. var gamepad = _a[_i];
  81461. if (gamepad && gamepad.type === type) {
  81462. return gamepad;
  81463. }
  81464. }
  81465. return null;
  81466. };
  81467. /**
  81468. * Disposes the gamepad manager
  81469. */
  81470. GamepadManager.prototype.dispose = function () {
  81471. if (this._gamepadEventSupported) {
  81472. if (this._onGamepadConnectedEvent) {
  81473. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  81474. }
  81475. if (this._onGamepadDisconnectedEvent) {
  81476. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  81477. }
  81478. this._onGamepadConnectedEvent = null;
  81479. this._onGamepadDisconnectedEvent = null;
  81480. }
  81481. this._babylonGamepads.forEach(function (gamepad) {
  81482. gamepad.dispose();
  81483. });
  81484. this.onGamepadConnectedObservable.clear();
  81485. this.onGamepadDisconnectedObservable.clear();
  81486. this._oneGamepadConnected = false;
  81487. this._stopMonitoringGamepads();
  81488. this._babylonGamepads = [];
  81489. };
  81490. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  81491. if (!this._oneGamepadConnected) {
  81492. this._oneGamepadConnected = true;
  81493. }
  81494. var newGamepad;
  81495. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  81496. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  81497. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  81498. }
  81499. // if pose is supported, use the (WebVR) pose enabled controller
  81500. else if (gamepad.pose) {
  81501. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  81502. }
  81503. else {
  81504. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  81505. }
  81506. this._babylonGamepads[newGamepad.index] = newGamepad;
  81507. return newGamepad;
  81508. };
  81509. GamepadManager.prototype._startMonitoringGamepads = function () {
  81510. if (!this._isMonitoring) {
  81511. this._isMonitoring = true;
  81512. //back-comp
  81513. if (!this._scene) {
  81514. this._checkGamepadsStatus();
  81515. }
  81516. }
  81517. };
  81518. GamepadManager.prototype._stopMonitoringGamepads = function () {
  81519. this._isMonitoring = false;
  81520. };
  81521. /** @hidden */
  81522. GamepadManager.prototype._checkGamepadsStatus = function () {
  81523. var _this = this;
  81524. // Hack to be compatible Chrome
  81525. this._updateGamepadObjects();
  81526. for (var i in this._babylonGamepads) {
  81527. var gamepad = this._babylonGamepads[i];
  81528. if (!gamepad || !gamepad.isConnected) {
  81529. continue;
  81530. }
  81531. gamepad.update();
  81532. }
  81533. if (this._isMonitoring && !this._scene) {
  81534. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  81535. }
  81536. };
  81537. // This function is called only on Chrome, which does not properly support
  81538. // connection/disconnection events and forces you to recopy again the gamepad object
  81539. GamepadManager.prototype._updateGamepadObjects = function () {
  81540. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  81541. for (var i = 0; i < gamepads.length; i++) {
  81542. var gamepad = gamepads[i];
  81543. if (gamepad) {
  81544. if (!this._babylonGamepads[gamepad.index]) {
  81545. var newGamepad = this._addNewGamepad(gamepad);
  81546. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  81547. }
  81548. else {
  81549. // Forced to copy again this object for Chrome for unknown reason
  81550. this._babylonGamepads[i].browserGamepad = gamepad;
  81551. if (!this._babylonGamepads[i].isConnected) {
  81552. this._babylonGamepads[i]._isConnected = true;
  81553. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  81554. }
  81555. }
  81556. }
  81557. }
  81558. };
  81559. return GamepadManager;
  81560. }());
  81561. BABYLON.GamepadManager = GamepadManager;
  81562. })(BABYLON || (BABYLON = {}));
  81563. //# sourceMappingURL=gamepadManager.js.map
  81564. var BABYLON;
  81565. (function (BABYLON) {
  81566. /**
  81567. * Represents a gamepad control stick position
  81568. */
  81569. var StickValues = /** @class */ (function () {
  81570. /**
  81571. * Initializes the gamepad x and y control stick values
  81572. * @param x The x component of the gamepad control stick value
  81573. * @param y The y component of the gamepad control stick value
  81574. */
  81575. function StickValues(
  81576. /**
  81577. * The x component of the control stick
  81578. */
  81579. x,
  81580. /**
  81581. * The y component of the control stick
  81582. */
  81583. y) {
  81584. this.x = x;
  81585. this.y = y;
  81586. }
  81587. return StickValues;
  81588. }());
  81589. BABYLON.StickValues = StickValues;
  81590. /**
  81591. * Represents a gamepad
  81592. */
  81593. var Gamepad = /** @class */ (function () {
  81594. /**
  81595. * Initializes the gamepad
  81596. * @param id The id of the gamepad
  81597. * @param index The index of the gamepad
  81598. * @param browserGamepad The browser gamepad
  81599. * @param leftStickX The x component of the left joystick
  81600. * @param leftStickY The y component of the left joystick
  81601. * @param rightStickX The x component of the right joystick
  81602. * @param rightStickY The y component of the right joystick
  81603. */
  81604. function Gamepad(
  81605. /**
  81606. * The id of the gamepad
  81607. */
  81608. id,
  81609. /**
  81610. * The index of the gamepad
  81611. */
  81612. index,
  81613. /**
  81614. * The browser gamepad
  81615. */
  81616. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  81617. if (leftStickX === void 0) { leftStickX = 0; }
  81618. if (leftStickY === void 0) { leftStickY = 1; }
  81619. if (rightStickX === void 0) { rightStickX = 2; }
  81620. if (rightStickY === void 0) { rightStickY = 3; }
  81621. this.id = id;
  81622. this.index = index;
  81623. this.browserGamepad = browserGamepad;
  81624. this._leftStick = { x: 0, y: 0 };
  81625. this._rightStick = { x: 0, y: 0 };
  81626. /** @hidden */
  81627. this._isConnected = true;
  81628. /**
  81629. * Specifies whether the left control stick should be Y-inverted
  81630. */
  81631. this._invertLeftStickY = false;
  81632. this.type = Gamepad.GAMEPAD;
  81633. this._leftStickAxisX = leftStickX;
  81634. this._leftStickAxisY = leftStickY;
  81635. this._rightStickAxisX = rightStickX;
  81636. this._rightStickAxisY = rightStickY;
  81637. if (this.browserGamepad.axes.length >= 2) {
  81638. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  81639. }
  81640. if (this.browserGamepad.axes.length >= 4) {
  81641. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  81642. }
  81643. }
  81644. Object.defineProperty(Gamepad.prototype, "isConnected", {
  81645. /**
  81646. * Specifies if the gamepad has been connected
  81647. */
  81648. get: function () {
  81649. return this._isConnected;
  81650. },
  81651. enumerable: true,
  81652. configurable: true
  81653. });
  81654. /**
  81655. * Callback triggered when the left joystick has changed
  81656. * @param callback
  81657. */
  81658. Gamepad.prototype.onleftstickchanged = function (callback) {
  81659. this._onleftstickchanged = callback;
  81660. };
  81661. /**
  81662. * Callback triggered when the right joystick has changed
  81663. * @param callback
  81664. */
  81665. Gamepad.prototype.onrightstickchanged = function (callback) {
  81666. this._onrightstickchanged = callback;
  81667. };
  81668. Object.defineProperty(Gamepad.prototype, "leftStick", {
  81669. /**
  81670. * Gets the left joystick
  81671. */
  81672. get: function () {
  81673. return this._leftStick;
  81674. },
  81675. /**
  81676. * Sets the left joystick values
  81677. */
  81678. set: function (newValues) {
  81679. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  81680. this._onleftstickchanged(newValues);
  81681. }
  81682. this._leftStick = newValues;
  81683. },
  81684. enumerable: true,
  81685. configurable: true
  81686. });
  81687. Object.defineProperty(Gamepad.prototype, "rightStick", {
  81688. /**
  81689. * Gets the right joystick
  81690. */
  81691. get: function () {
  81692. return this._rightStick;
  81693. },
  81694. /**
  81695. * Sets the right joystick value
  81696. */
  81697. set: function (newValues) {
  81698. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  81699. this._onrightstickchanged(newValues);
  81700. }
  81701. this._rightStick = newValues;
  81702. },
  81703. enumerable: true,
  81704. configurable: true
  81705. });
  81706. /**
  81707. * Updates the gamepad joystick positions
  81708. */
  81709. Gamepad.prototype.update = function () {
  81710. if (this._leftStick) {
  81711. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  81712. if (this._invertLeftStickY) {
  81713. this.leftStick.y *= -1;
  81714. }
  81715. }
  81716. if (this._rightStick) {
  81717. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  81718. }
  81719. };
  81720. /**
  81721. * Disposes the gamepad
  81722. */
  81723. Gamepad.prototype.dispose = function () {
  81724. };
  81725. /**
  81726. * Represents a gamepad controller
  81727. */
  81728. Gamepad.GAMEPAD = 0;
  81729. /**
  81730. * Represents a generic controller
  81731. */
  81732. Gamepad.GENERIC = 1;
  81733. /**
  81734. * Represents an XBox controller
  81735. */
  81736. Gamepad.XBOX = 2;
  81737. /**
  81738. * Represents a pose-enabled controller
  81739. */
  81740. Gamepad.POSE_ENABLED = 3;
  81741. return Gamepad;
  81742. }());
  81743. BABYLON.Gamepad = Gamepad;
  81744. /**
  81745. * Represents a generic gamepad
  81746. */
  81747. var GenericPad = /** @class */ (function (_super) {
  81748. __extends(GenericPad, _super);
  81749. /**
  81750. * Initializes the generic gamepad
  81751. * @param id The id of the generic gamepad
  81752. * @param index The index of the generic gamepad
  81753. * @param browserGamepad The browser gamepad
  81754. */
  81755. function GenericPad(id, index, browserGamepad) {
  81756. var _this = _super.call(this, id, index, browserGamepad) || this;
  81757. /**
  81758. * Observable triggered when a button has been pressed
  81759. */
  81760. _this.onButtonDownObservable = new BABYLON.Observable();
  81761. /**
  81762. * Observable triggered when a button has been released
  81763. */
  81764. _this.onButtonUpObservable = new BABYLON.Observable();
  81765. _this.type = Gamepad.GENERIC;
  81766. _this._buttons = new Array(browserGamepad.buttons.length);
  81767. return _this;
  81768. }
  81769. /**
  81770. * Callback triggered when a button has been pressed
  81771. * @param callback Called when a button has been pressed
  81772. */
  81773. GenericPad.prototype.onbuttondown = function (callback) {
  81774. this._onbuttondown = callback;
  81775. };
  81776. /**
  81777. * Callback triggered when a button has been released
  81778. * @param callback Called when a button has been released
  81779. */
  81780. GenericPad.prototype.onbuttonup = function (callback) {
  81781. this._onbuttonup = callback;
  81782. };
  81783. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  81784. if (newValue !== currentValue) {
  81785. if (newValue === 1) {
  81786. if (this._onbuttondown) {
  81787. this._onbuttondown(buttonIndex);
  81788. }
  81789. this.onButtonDownObservable.notifyObservers(buttonIndex);
  81790. }
  81791. if (newValue === 0) {
  81792. if (this._onbuttonup) {
  81793. this._onbuttonup(buttonIndex);
  81794. }
  81795. this.onButtonUpObservable.notifyObservers(buttonIndex);
  81796. }
  81797. }
  81798. return newValue;
  81799. };
  81800. /**
  81801. * Updates the generic gamepad
  81802. */
  81803. GenericPad.prototype.update = function () {
  81804. _super.prototype.update.call(this);
  81805. for (var index = 0; index < this._buttons.length; index++) {
  81806. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  81807. }
  81808. };
  81809. /**
  81810. * Disposes the generic gamepad
  81811. */
  81812. GenericPad.prototype.dispose = function () {
  81813. _super.prototype.dispose.call(this);
  81814. this.onButtonDownObservable.clear();
  81815. this.onButtonUpObservable.clear();
  81816. };
  81817. return GenericPad;
  81818. }(Gamepad));
  81819. BABYLON.GenericPad = GenericPad;
  81820. })(BABYLON || (BABYLON = {}));
  81821. //# sourceMappingURL=gamepad.js.map
  81822. var BABYLON;
  81823. (function (BABYLON) {
  81824. /**
  81825. * Defines supported buttons for XBox360 compatible gamepads
  81826. */
  81827. var Xbox360Button;
  81828. (function (Xbox360Button) {
  81829. /** A */
  81830. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  81831. /** B */
  81832. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  81833. /** X */
  81834. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  81835. /** Y */
  81836. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  81837. /** Start */
  81838. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  81839. /** Back */
  81840. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  81841. /** Left button */
  81842. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  81843. /** Right button */
  81844. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  81845. /** Left stick */
  81846. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  81847. /** Right stick */
  81848. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  81849. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  81850. /** Defines values for XBox360 DPad */
  81851. var Xbox360Dpad;
  81852. (function (Xbox360Dpad) {
  81853. /** Up */
  81854. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  81855. /** Down */
  81856. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  81857. /** Left */
  81858. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  81859. /** Right */
  81860. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  81861. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  81862. /**
  81863. * Defines a XBox360 gamepad
  81864. */
  81865. var Xbox360Pad = /** @class */ (function (_super) {
  81866. __extends(Xbox360Pad, _super);
  81867. /**
  81868. * Creates a new XBox360 gamepad object
  81869. * @param id defines the id of this gamepad
  81870. * @param index defines its index
  81871. * @param gamepad defines the internal HTML gamepad object
  81872. * @param xboxOne defines if it is a XBox One gamepad
  81873. */
  81874. function Xbox360Pad(id, index, gamepad, xboxOne) {
  81875. if (xboxOne === void 0) { xboxOne = false; }
  81876. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  81877. _this._leftTrigger = 0;
  81878. _this._rightTrigger = 0;
  81879. /** Observable raised when a button is pressed */
  81880. _this.onButtonDownObservable = new BABYLON.Observable();
  81881. /** Observable raised when a button is released */
  81882. _this.onButtonUpObservable = new BABYLON.Observable();
  81883. /** Observable raised when a pad is pressed */
  81884. _this.onPadDownObservable = new BABYLON.Observable();
  81885. /** Observable raised when a pad is released */
  81886. _this.onPadUpObservable = new BABYLON.Observable();
  81887. _this._buttonA = 0;
  81888. _this._buttonB = 0;
  81889. _this._buttonX = 0;
  81890. _this._buttonY = 0;
  81891. _this._buttonBack = 0;
  81892. _this._buttonStart = 0;
  81893. _this._buttonLB = 0;
  81894. _this._buttonRB = 0;
  81895. _this._buttonLeftStick = 0;
  81896. _this._buttonRightStick = 0;
  81897. _this._dPadUp = 0;
  81898. _this._dPadDown = 0;
  81899. _this._dPadLeft = 0;
  81900. _this._dPadRight = 0;
  81901. _this._isXboxOnePad = false;
  81902. _this.type = BABYLON.Gamepad.XBOX;
  81903. _this._isXboxOnePad = xboxOne;
  81904. return _this;
  81905. }
  81906. /**
  81907. * Defines the callback to call when left trigger is pressed
  81908. * @param callback defines the callback to use
  81909. */
  81910. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  81911. this._onlefttriggerchanged = callback;
  81912. };
  81913. /**
  81914. * Defines the callback to call when right trigger is pressed
  81915. * @param callback defines the callback to use
  81916. */
  81917. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  81918. this._onrighttriggerchanged = callback;
  81919. };
  81920. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  81921. /**
  81922. * Gets the left trigger value
  81923. */
  81924. get: function () {
  81925. return this._leftTrigger;
  81926. },
  81927. /**
  81928. * Sets the left trigger value
  81929. */
  81930. set: function (newValue) {
  81931. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  81932. this._onlefttriggerchanged(newValue);
  81933. }
  81934. this._leftTrigger = newValue;
  81935. },
  81936. enumerable: true,
  81937. configurable: true
  81938. });
  81939. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  81940. /**
  81941. * Gets the right trigger value
  81942. */
  81943. get: function () {
  81944. return this._rightTrigger;
  81945. },
  81946. /**
  81947. * Sets the right trigger value
  81948. */
  81949. set: function (newValue) {
  81950. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  81951. this._onrighttriggerchanged(newValue);
  81952. }
  81953. this._rightTrigger = newValue;
  81954. },
  81955. enumerable: true,
  81956. configurable: true
  81957. });
  81958. /**
  81959. * Defines the callback to call when a button is pressed
  81960. * @param callback defines the callback to use
  81961. */
  81962. Xbox360Pad.prototype.onbuttondown = function (callback) {
  81963. this._onbuttondown = callback;
  81964. };
  81965. /**
  81966. * Defines the callback to call when a button is released
  81967. * @param callback defines the callback to use
  81968. */
  81969. Xbox360Pad.prototype.onbuttonup = function (callback) {
  81970. this._onbuttonup = callback;
  81971. };
  81972. /**
  81973. * Defines the callback to call when a pad is pressed
  81974. * @param callback defines the callback to use
  81975. */
  81976. Xbox360Pad.prototype.ondpaddown = function (callback) {
  81977. this._ondpaddown = callback;
  81978. };
  81979. /**
  81980. * Defines the callback to call when a pad is released
  81981. * @param callback defines the callback to use
  81982. */
  81983. Xbox360Pad.prototype.ondpadup = function (callback) {
  81984. this._ondpadup = callback;
  81985. };
  81986. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  81987. if (newValue !== currentValue) {
  81988. if (newValue === 1) {
  81989. if (this._onbuttondown) {
  81990. this._onbuttondown(buttonType);
  81991. }
  81992. this.onButtonDownObservable.notifyObservers(buttonType);
  81993. }
  81994. if (newValue === 0) {
  81995. if (this._onbuttonup) {
  81996. this._onbuttonup(buttonType);
  81997. }
  81998. this.onButtonUpObservable.notifyObservers(buttonType);
  81999. }
  82000. }
  82001. return newValue;
  82002. };
  82003. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  82004. if (newValue !== currentValue) {
  82005. if (newValue === 1) {
  82006. if (this._ondpaddown) {
  82007. this._ondpaddown(buttonType);
  82008. }
  82009. this.onPadDownObservable.notifyObservers(buttonType);
  82010. }
  82011. if (newValue === 0) {
  82012. if (this._ondpadup) {
  82013. this._ondpadup(buttonType);
  82014. }
  82015. this.onPadUpObservable.notifyObservers(buttonType);
  82016. }
  82017. }
  82018. return newValue;
  82019. };
  82020. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  82021. /**
  82022. * Gets the value of the `A` button
  82023. */
  82024. get: function () {
  82025. return this._buttonA;
  82026. },
  82027. /**
  82028. * Sets the value of the `A` button
  82029. */
  82030. set: function (value) {
  82031. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  82032. },
  82033. enumerable: true,
  82034. configurable: true
  82035. });
  82036. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  82037. /**
  82038. * Gets the value of the `B` button
  82039. */
  82040. get: function () {
  82041. return this._buttonB;
  82042. },
  82043. /**
  82044. * Sets the value of the `B` button
  82045. */
  82046. set: function (value) {
  82047. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  82048. },
  82049. enumerable: true,
  82050. configurable: true
  82051. });
  82052. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  82053. /**
  82054. * Gets the value of the `X` button
  82055. */
  82056. get: function () {
  82057. return this._buttonX;
  82058. },
  82059. /**
  82060. * Sets the value of the `X` button
  82061. */
  82062. set: function (value) {
  82063. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  82064. },
  82065. enumerable: true,
  82066. configurable: true
  82067. });
  82068. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  82069. /**
  82070. * Gets the value of the `Y` button
  82071. */
  82072. get: function () {
  82073. return this._buttonY;
  82074. },
  82075. /**
  82076. * Sets the value of the `Y` button
  82077. */
  82078. set: function (value) {
  82079. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  82080. },
  82081. enumerable: true,
  82082. configurable: true
  82083. });
  82084. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  82085. /**
  82086. * Gets the value of the `Start` button
  82087. */
  82088. get: function () {
  82089. return this._buttonStart;
  82090. },
  82091. /**
  82092. * Sets the value of the `Start` button
  82093. */
  82094. set: function (value) {
  82095. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  82096. },
  82097. enumerable: true,
  82098. configurable: true
  82099. });
  82100. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  82101. /**
  82102. * Gets the value of the `Back` button
  82103. */
  82104. get: function () {
  82105. return this._buttonBack;
  82106. },
  82107. /**
  82108. * Sets the value of the `Back` button
  82109. */
  82110. set: function (value) {
  82111. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  82112. },
  82113. enumerable: true,
  82114. configurable: true
  82115. });
  82116. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  82117. /**
  82118. * Gets the value of the `Left` button
  82119. */
  82120. get: function () {
  82121. return this._buttonLB;
  82122. },
  82123. /**
  82124. * Sets the value of the `Left` button
  82125. */
  82126. set: function (value) {
  82127. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  82128. },
  82129. enumerable: true,
  82130. configurable: true
  82131. });
  82132. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  82133. /**
  82134. * Gets the value of the `Right` button
  82135. */
  82136. get: function () {
  82137. return this._buttonRB;
  82138. },
  82139. /**
  82140. * Sets the value of the `Right` button
  82141. */
  82142. set: function (value) {
  82143. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  82144. },
  82145. enumerable: true,
  82146. configurable: true
  82147. });
  82148. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  82149. /**
  82150. * Gets the value of the Left joystick
  82151. */
  82152. get: function () {
  82153. return this._buttonLeftStick;
  82154. },
  82155. /**
  82156. * Sets the value of the Left joystick
  82157. */
  82158. set: function (value) {
  82159. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  82160. },
  82161. enumerable: true,
  82162. configurable: true
  82163. });
  82164. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  82165. /**
  82166. * Gets the value of the Right joystick
  82167. */
  82168. get: function () {
  82169. return this._buttonRightStick;
  82170. },
  82171. /**
  82172. * Sets the value of the Right joystick
  82173. */
  82174. set: function (value) {
  82175. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  82176. },
  82177. enumerable: true,
  82178. configurable: true
  82179. });
  82180. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  82181. /**
  82182. * Gets the value of D-pad up
  82183. */
  82184. get: function () {
  82185. return this._dPadUp;
  82186. },
  82187. /**
  82188. * Sets the value of D-pad up
  82189. */
  82190. set: function (value) {
  82191. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  82192. },
  82193. enumerable: true,
  82194. configurable: true
  82195. });
  82196. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  82197. /**
  82198. * Gets the value of D-pad down
  82199. */
  82200. get: function () {
  82201. return this._dPadDown;
  82202. },
  82203. /**
  82204. * Sets the value of D-pad down
  82205. */
  82206. set: function (value) {
  82207. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  82208. },
  82209. enumerable: true,
  82210. configurable: true
  82211. });
  82212. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  82213. /**
  82214. * Gets the value of D-pad left
  82215. */
  82216. get: function () {
  82217. return this._dPadLeft;
  82218. },
  82219. /**
  82220. * Sets the value of D-pad left
  82221. */
  82222. set: function (value) {
  82223. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  82224. },
  82225. enumerable: true,
  82226. configurable: true
  82227. });
  82228. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  82229. /**
  82230. * Gets the value of D-pad right
  82231. */
  82232. get: function () {
  82233. return this._dPadRight;
  82234. },
  82235. /**
  82236. * Sets the value of D-pad right
  82237. */
  82238. set: function (value) {
  82239. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  82240. },
  82241. enumerable: true,
  82242. configurable: true
  82243. });
  82244. /**
  82245. * Force the gamepad to synchronize with device values
  82246. */
  82247. Xbox360Pad.prototype.update = function () {
  82248. _super.prototype.update.call(this);
  82249. if (this._isXboxOnePad) {
  82250. this.buttonA = this.browserGamepad.buttons[0].value;
  82251. this.buttonB = this.browserGamepad.buttons[1].value;
  82252. this.buttonX = this.browserGamepad.buttons[2].value;
  82253. this.buttonY = this.browserGamepad.buttons[3].value;
  82254. this.buttonLB = this.browserGamepad.buttons[4].value;
  82255. this.buttonRB = this.browserGamepad.buttons[5].value;
  82256. this.leftTrigger = this.browserGamepad.axes[2];
  82257. this.rightTrigger = this.browserGamepad.axes[5];
  82258. this.buttonBack = this.browserGamepad.buttons[9].value;
  82259. this.buttonStart = this.browserGamepad.buttons[8].value;
  82260. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  82261. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  82262. this.dPadUp = this.browserGamepad.buttons[11].value;
  82263. this.dPadDown = this.browserGamepad.buttons[12].value;
  82264. this.dPadLeft = this.browserGamepad.buttons[13].value;
  82265. this.dPadRight = this.browserGamepad.buttons[14].value;
  82266. }
  82267. else {
  82268. this.buttonA = this.browserGamepad.buttons[0].value;
  82269. this.buttonB = this.browserGamepad.buttons[1].value;
  82270. this.buttonX = this.browserGamepad.buttons[2].value;
  82271. this.buttonY = this.browserGamepad.buttons[3].value;
  82272. this.buttonLB = this.browserGamepad.buttons[4].value;
  82273. this.buttonRB = this.browserGamepad.buttons[5].value;
  82274. this.leftTrigger = this.browserGamepad.buttons[6].value;
  82275. this.rightTrigger = this.browserGamepad.buttons[7].value;
  82276. this.buttonBack = this.browserGamepad.buttons[8].value;
  82277. this.buttonStart = this.browserGamepad.buttons[9].value;
  82278. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  82279. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  82280. this.dPadUp = this.browserGamepad.buttons[12].value;
  82281. this.dPadDown = this.browserGamepad.buttons[13].value;
  82282. this.dPadLeft = this.browserGamepad.buttons[14].value;
  82283. this.dPadRight = this.browserGamepad.buttons[15].value;
  82284. }
  82285. };
  82286. /**
  82287. * Disposes the gamepad
  82288. */
  82289. Xbox360Pad.prototype.dispose = function () {
  82290. _super.prototype.dispose.call(this);
  82291. this.onButtonDownObservable.clear();
  82292. this.onButtonUpObservable.clear();
  82293. this.onPadDownObservable.clear();
  82294. this.onPadUpObservable.clear();
  82295. };
  82296. return Xbox360Pad;
  82297. }(BABYLON.Gamepad));
  82298. BABYLON.Xbox360Pad = Xbox360Pad;
  82299. })(BABYLON || (BABYLON = {}));
  82300. //# sourceMappingURL=xboxGamepad.js.map
  82301. var BABYLON;
  82302. (function (BABYLON) {
  82303. /**
  82304. * Defines the types of pose enabled controllers that are supported
  82305. */
  82306. var PoseEnabledControllerType;
  82307. (function (PoseEnabledControllerType) {
  82308. /**
  82309. * HTC Vive
  82310. */
  82311. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  82312. /**
  82313. * Oculus Rift
  82314. */
  82315. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  82316. /**
  82317. * Windows mixed reality
  82318. */
  82319. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  82320. /**
  82321. * Samsung gear VR
  82322. */
  82323. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  82324. /**
  82325. * Google Daydream
  82326. */
  82327. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  82328. /**
  82329. * Generic
  82330. */
  82331. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  82332. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  82333. /**
  82334. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  82335. */
  82336. var PoseEnabledControllerHelper = /** @class */ (function () {
  82337. function PoseEnabledControllerHelper() {
  82338. }
  82339. /**
  82340. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  82341. * @param vrGamepad the gamepad to initialized
  82342. * @returns a vr controller of the type the gamepad identified as
  82343. */
  82344. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  82345. // Oculus Touch
  82346. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  82347. return new BABYLON.OculusTouchController(vrGamepad);
  82348. }
  82349. // Windows Mixed Reality controllers
  82350. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  82351. return new BABYLON.WindowsMotionController(vrGamepad);
  82352. }
  82353. // HTC Vive
  82354. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  82355. return new BABYLON.ViveController(vrGamepad);
  82356. }
  82357. // Samsung/Oculus Gear VR or Oculus Go
  82358. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  82359. return new BABYLON.GearVRController(vrGamepad);
  82360. }
  82361. // Google Daydream
  82362. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  82363. return new BABYLON.DaydreamController(vrGamepad);
  82364. }
  82365. // Generic
  82366. else {
  82367. return new BABYLON.GenericController(vrGamepad);
  82368. }
  82369. };
  82370. return PoseEnabledControllerHelper;
  82371. }());
  82372. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  82373. /**
  82374. * Defines the PoseEnabledController object that contains state of a vr capable controller
  82375. */
  82376. var PoseEnabledController = /** @class */ (function (_super) {
  82377. __extends(PoseEnabledController, _super);
  82378. /**
  82379. * Creates a new PoseEnabledController from a gamepad
  82380. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  82381. */
  82382. function PoseEnabledController(browserGamepad) {
  82383. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  82384. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  82385. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  82386. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  82387. /**
  82388. * The device position in babylon space
  82389. */
  82390. _this.devicePosition = BABYLON.Vector3.Zero();
  82391. /**
  82392. * The device rotation in babylon space
  82393. */
  82394. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  82395. /**
  82396. * The scale factor of the device in babylon space
  82397. */
  82398. _this.deviceScaleFactor = 1;
  82399. // Used to convert 6dof controllers to 3dof
  82400. _this._trackPosition = true;
  82401. _this._maxRotationDistFromHeadset = Math.PI / 5;
  82402. _this._draggedRoomRotation = 0;
  82403. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  82404. /**
  82405. * Internal, matrix used to convert room space to babylon space
  82406. * @hidden
  82407. */
  82408. _this._deviceToWorld = BABYLON.Matrix.Identity();
  82409. /**
  82410. * Node to be used when casting a ray from the controller
  82411. * @hidden
  82412. */
  82413. _this._pointingPoseNode = null;
  82414. _this._workingMatrix = BABYLON.Matrix.Identity();
  82415. /**
  82416. * @hidden
  82417. */
  82418. _this._meshAttachedObservable = new BABYLON.Observable();
  82419. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  82420. _this.controllerType = PoseEnabledControllerType.GENERIC;
  82421. _this.position = BABYLON.Vector3.Zero();
  82422. _this.rotationQuaternion = new BABYLON.Quaternion();
  82423. _this._calculatedPosition = BABYLON.Vector3.Zero();
  82424. _this._calculatedRotation = new BABYLON.Quaternion();
  82425. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  82426. return _this;
  82427. }
  82428. /**
  82429. * @hidden
  82430. */
  82431. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  82432. if (this._trackPosition) {
  82433. this._calculatedPosition.copyFrom(fixedPosition);
  82434. this._trackPosition = false;
  82435. }
  82436. };
  82437. /**
  82438. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  82439. */
  82440. PoseEnabledController.prototype.update = function () {
  82441. _super.prototype.update.call(this);
  82442. this._updatePoseAndMesh();
  82443. };
  82444. /**
  82445. * Updates only the pose device and mesh without doing any button event checking
  82446. */
  82447. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  82448. var pose = this.browserGamepad.pose;
  82449. this.updateFromDevice(pose);
  82450. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  82451. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  82452. camera._computeDevicePosition();
  82453. this._deviceToWorld.setTranslation(camera.devicePosition);
  82454. if (camera.deviceRotationQuaternion) {
  82455. var camera = camera;
  82456. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  82457. // Find the radian distance away that the headset is from the controllers rotation
  82458. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  82459. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  82460. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  82461. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  82462. this._draggedRoomRotation += rotationAmount;
  82463. // Rotate controller around headset
  82464. var sin = Math.sin(-rotationAmount);
  82465. var cos = Math.cos(-rotationAmount);
  82466. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  82467. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  82468. }
  82469. }
  82470. }
  82471. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  82472. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  82473. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  82474. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  82475. if (this._mesh) {
  82476. this._mesh.position.copyFrom(this.devicePosition);
  82477. if (this._mesh.rotationQuaternion) {
  82478. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  82479. }
  82480. }
  82481. };
  82482. /**
  82483. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  82484. * @param poseData raw pose fromthe device
  82485. */
  82486. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  82487. if (poseData) {
  82488. this.rawPose = poseData;
  82489. if (poseData.position) {
  82490. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  82491. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  82492. this._deviceRoomPosition.z *= -1;
  82493. }
  82494. if (this._trackPosition) {
  82495. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  82496. }
  82497. this._calculatedPosition.addInPlace(this.position);
  82498. }
  82499. var pose = this.rawPose;
  82500. if (poseData.orientation && pose.orientation) {
  82501. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  82502. if (this._mesh) {
  82503. if (this._mesh.getScene().useRightHandedSystem) {
  82504. this._deviceRoomRotationQuaternion.z *= -1;
  82505. this._deviceRoomRotationQuaternion.w *= -1;
  82506. }
  82507. else {
  82508. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  82509. }
  82510. }
  82511. // if the camera is set, rotate to the camera's rotation
  82512. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  82513. }
  82514. }
  82515. };
  82516. /**
  82517. * Attaches a mesh to the controller
  82518. * @param mesh the mesh to be attached
  82519. */
  82520. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  82521. if (this._mesh) {
  82522. this._mesh.parent = null;
  82523. }
  82524. this._mesh = mesh;
  82525. if (this._poseControlledCamera) {
  82526. this._mesh.parent = this._poseControlledCamera;
  82527. }
  82528. if (!this._mesh.rotationQuaternion) {
  82529. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  82530. }
  82531. // 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
  82532. this._updatePoseAndMesh();
  82533. if (this._pointingPoseNode) {
  82534. var parents = [];
  82535. var obj = this._pointingPoseNode;
  82536. while (obj.parent) {
  82537. parents.push(obj.parent);
  82538. obj = obj.parent;
  82539. }
  82540. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  82541. }
  82542. this._meshAttachedObservable.notifyObservers(mesh);
  82543. };
  82544. /**
  82545. * Attaches the controllers mesh to a camera
  82546. * @param camera the camera the mesh should be attached to
  82547. */
  82548. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  82549. this._poseControlledCamera = camera;
  82550. if (this._mesh) {
  82551. this._mesh.parent = this._poseControlledCamera;
  82552. }
  82553. };
  82554. /**
  82555. * Disposes of the controller
  82556. */
  82557. PoseEnabledController.prototype.dispose = function () {
  82558. if (this._mesh) {
  82559. this._mesh.dispose();
  82560. }
  82561. this._mesh = null;
  82562. _super.prototype.dispose.call(this);
  82563. };
  82564. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  82565. /**
  82566. * The mesh that is attached to the controller
  82567. */
  82568. get: function () {
  82569. return this._mesh;
  82570. },
  82571. enumerable: true,
  82572. configurable: true
  82573. });
  82574. /**
  82575. * Gets the ray of the controller in the direction the controller is pointing
  82576. * @param length the length the resulting ray should be
  82577. * @returns a ray in the direction the controller is pointing
  82578. */
  82579. PoseEnabledController.prototype.getForwardRay = function (length) {
  82580. if (length === void 0) { length = 100; }
  82581. if (!this.mesh) {
  82582. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  82583. }
  82584. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  82585. var origin = m.getTranslation();
  82586. var forward = new BABYLON.Vector3(0, 0, -1);
  82587. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  82588. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  82589. return new BABYLON.Ray(origin, direction, length);
  82590. };
  82591. /**
  82592. * Name of the child mesh that can be used to cast a ray from the controller
  82593. */
  82594. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  82595. return PoseEnabledController;
  82596. }(BABYLON.Gamepad));
  82597. BABYLON.PoseEnabledController = PoseEnabledController;
  82598. })(BABYLON || (BABYLON = {}));
  82599. //# sourceMappingURL=poseEnabledController.js.map
  82600. var BABYLON;
  82601. (function (BABYLON) {
  82602. /**
  82603. * Defines the WebVRController object that represents controllers tracked in 3D space
  82604. */
  82605. var WebVRController = /** @class */ (function (_super) {
  82606. __extends(WebVRController, _super);
  82607. /**
  82608. * Creates a new WebVRController from a gamepad
  82609. * @param vrGamepad the gamepad that the WebVRController should be created from
  82610. */
  82611. function WebVRController(vrGamepad) {
  82612. var _this = _super.call(this, vrGamepad) || this;
  82613. // Observables
  82614. /**
  82615. * Fired when the trigger state has changed
  82616. */
  82617. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  82618. /**
  82619. * Fired when the main button state has changed
  82620. */
  82621. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  82622. /**
  82623. * Fired when the secondary button state has changed
  82624. */
  82625. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  82626. /**
  82627. * Fired when the pad state has changed
  82628. */
  82629. _this.onPadStateChangedObservable = new BABYLON.Observable();
  82630. /**
  82631. * Fired when controllers stick values have changed
  82632. */
  82633. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  82634. /**
  82635. * X and Y axis corrisponding to the controllers joystick
  82636. */
  82637. _this.pad = { x: 0, y: 0 };
  82638. // avoid GC, store state in a tmp object
  82639. _this._changes = {
  82640. pressChanged: false,
  82641. touchChanged: false,
  82642. valueChanged: false,
  82643. changed: false
  82644. };
  82645. _this._buttons = new Array(vrGamepad.buttons.length);
  82646. _this.hand = vrGamepad.hand;
  82647. return _this;
  82648. }
  82649. /**
  82650. * Fired when a controller button's state has changed
  82651. * @param callback the callback containing the button that was modified
  82652. */
  82653. WebVRController.prototype.onButtonStateChange = function (callback) {
  82654. this._onButtonStateChange = callback;
  82655. };
  82656. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  82657. /**
  82658. * The default controller model for the controller
  82659. */
  82660. get: function () {
  82661. return this._defaultModel;
  82662. },
  82663. enumerable: true,
  82664. configurable: true
  82665. });
  82666. /**
  82667. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  82668. */
  82669. WebVRController.prototype.update = function () {
  82670. _super.prototype.update.call(this);
  82671. for (var index = 0; index < this._buttons.length; index++) {
  82672. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  82673. }
  82674. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  82675. this.pad.x = this.leftStick.x;
  82676. this.pad.y = this.leftStick.y;
  82677. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  82678. }
  82679. };
  82680. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  82681. if (!newState) {
  82682. newState = {
  82683. pressed: false,
  82684. touched: false,
  82685. value: 0
  82686. };
  82687. }
  82688. if (!currentState) {
  82689. this._buttons[buttonIndex] = {
  82690. pressed: newState.pressed,
  82691. touched: newState.touched,
  82692. value: newState.value
  82693. };
  82694. return;
  82695. }
  82696. this._checkChanges(newState, currentState);
  82697. if (this._changes.changed) {
  82698. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  82699. this._handleButtonChange(buttonIndex, newState, this._changes);
  82700. }
  82701. this._buttons[buttonIndex].pressed = newState.pressed;
  82702. this._buttons[buttonIndex].touched = newState.touched;
  82703. // oculus triggers are never 0, thou not touched.
  82704. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  82705. };
  82706. WebVRController.prototype._checkChanges = function (newState, currentState) {
  82707. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  82708. this._changes.touchChanged = newState.touched !== currentState.touched;
  82709. this._changes.valueChanged = newState.value !== currentState.value;
  82710. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  82711. return this._changes;
  82712. };
  82713. /**
  82714. * Disposes of th webVRCOntroller
  82715. */
  82716. WebVRController.prototype.dispose = function () {
  82717. _super.prototype.dispose.call(this);
  82718. this.onTriggerStateChangedObservable.clear();
  82719. this.onMainButtonStateChangedObservable.clear();
  82720. this.onSecondaryButtonStateChangedObservable.clear();
  82721. this.onPadStateChangedObservable.clear();
  82722. this.onPadValuesChangedObservable.clear();
  82723. };
  82724. return WebVRController;
  82725. }(BABYLON.PoseEnabledController));
  82726. BABYLON.WebVRController = WebVRController;
  82727. })(BABYLON || (BABYLON = {}));
  82728. //# sourceMappingURL=webVRController.js.map
  82729. var BABYLON;
  82730. (function (BABYLON) {
  82731. /**
  82732. * Oculus Touch Controller
  82733. */
  82734. var OculusTouchController = /** @class */ (function (_super) {
  82735. __extends(OculusTouchController, _super);
  82736. /**
  82737. * Creates a new OculusTouchController from a gamepad
  82738. * @param vrGamepad the gamepad that the controller should be created from
  82739. */
  82740. function OculusTouchController(vrGamepad) {
  82741. var _this = _super.call(this, vrGamepad) || this;
  82742. /**
  82743. * Fired when the secondary trigger on this controller is modified
  82744. */
  82745. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  82746. /**
  82747. * Fired when the thumb rest on this controller is modified
  82748. */
  82749. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  82750. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  82751. return _this;
  82752. }
  82753. /**
  82754. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82755. * @param scene scene in which to add meshes
  82756. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82757. */
  82758. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82759. var _this = this;
  82760. var meshName;
  82761. // Hand
  82762. if (this.hand === 'left') {
  82763. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  82764. }
  82765. else { // Right is the default if no hand is specified
  82766. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  82767. }
  82768. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  82769. /*
  82770. Parent Mesh name: oculus_touch_left
  82771. - body
  82772. - trigger
  82773. - thumbstick
  82774. - grip
  82775. - button_y
  82776. - button_x
  82777. - button_enter
  82778. */
  82779. _this._defaultModel = newMeshes[1];
  82780. _this.attachToMesh(_this._defaultModel);
  82781. if (meshLoaded) {
  82782. meshLoaded(_this._defaultModel);
  82783. }
  82784. });
  82785. };
  82786. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  82787. /**
  82788. * Fired when the A button on this controller is modified
  82789. */
  82790. get: function () {
  82791. if (this.hand === 'right') {
  82792. return this.onMainButtonStateChangedObservable;
  82793. }
  82794. else {
  82795. throw new Error('No A button on left hand');
  82796. }
  82797. },
  82798. enumerable: true,
  82799. configurable: true
  82800. });
  82801. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  82802. /**
  82803. * Fired when the B button on this controller is modified
  82804. */
  82805. get: function () {
  82806. if (this.hand === 'right') {
  82807. return this.onSecondaryButtonStateChangedObservable;
  82808. }
  82809. else {
  82810. throw new Error('No B button on left hand');
  82811. }
  82812. },
  82813. enumerable: true,
  82814. configurable: true
  82815. });
  82816. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  82817. /**
  82818. * Fired when the X button on this controller is modified
  82819. */
  82820. get: function () {
  82821. if (this.hand === 'left') {
  82822. return this.onMainButtonStateChangedObservable;
  82823. }
  82824. else {
  82825. throw new Error('No X button on right hand');
  82826. }
  82827. },
  82828. enumerable: true,
  82829. configurable: true
  82830. });
  82831. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  82832. /**
  82833. * Fired when the Y button on this controller is modified
  82834. */
  82835. get: function () {
  82836. if (this.hand === 'left') {
  82837. return this.onSecondaryButtonStateChangedObservable;
  82838. }
  82839. else {
  82840. throw new Error('No Y button on right hand');
  82841. }
  82842. },
  82843. enumerable: true,
  82844. configurable: true
  82845. });
  82846. /**
  82847. * Called once for each button that changed state since the last frame
  82848. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  82849. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  82850. * 2) secondary trigger (same)
  82851. * 3) A (right) X (left), touch, pressed = value
  82852. * 4) B / Y
  82853. * 5) thumb rest
  82854. * @param buttonIdx Which button index changed
  82855. * @param state New state of the button
  82856. * @param changes Which properties on the state changed since last frame
  82857. */
  82858. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82859. var notifyObject = state; //{ state: state, changes: changes };
  82860. var triggerDirection = this.hand === 'right' ? -1 : 1;
  82861. switch (buttonIdx) {
  82862. case 0:
  82863. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  82864. return;
  82865. case 1: // index trigger
  82866. if (this._defaultModel) {
  82867. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  82868. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  82869. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  82870. }
  82871. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  82872. return;
  82873. case 2: // secondary trigger
  82874. if (this._defaultModel) {
  82875. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  82876. }
  82877. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  82878. return;
  82879. case 3:
  82880. if (this._defaultModel) {
  82881. if (notifyObject.pressed) {
  82882. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  82883. }
  82884. else {
  82885. (this._defaultModel.getChildren()[1]).position.y = 0;
  82886. }
  82887. }
  82888. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  82889. return;
  82890. case 4:
  82891. if (this._defaultModel) {
  82892. if (notifyObject.pressed) {
  82893. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  82894. }
  82895. else {
  82896. (this._defaultModel.getChildren()[2]).position.y = 0;
  82897. }
  82898. }
  82899. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  82900. return;
  82901. case 5:
  82902. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  82903. return;
  82904. }
  82905. };
  82906. /**
  82907. * Base Url for the controller model.
  82908. */
  82909. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  82910. /**
  82911. * File name for the left controller model.
  82912. */
  82913. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  82914. /**
  82915. * File name for the right controller model.
  82916. */
  82917. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  82918. return OculusTouchController;
  82919. }(BABYLON.WebVRController));
  82920. BABYLON.OculusTouchController = OculusTouchController;
  82921. })(BABYLON || (BABYLON = {}));
  82922. //# sourceMappingURL=oculusTouchController.js.map
  82923. var BABYLON;
  82924. (function (BABYLON) {
  82925. /**
  82926. * Vive Controller
  82927. */
  82928. var ViveController = /** @class */ (function (_super) {
  82929. __extends(ViveController, _super);
  82930. /**
  82931. * Creates a new ViveController from a gamepad
  82932. * @param vrGamepad the gamepad that the controller should be created from
  82933. */
  82934. function ViveController(vrGamepad) {
  82935. var _this = _super.call(this, vrGamepad) || this;
  82936. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  82937. _this._invertLeftStickY = true;
  82938. return _this;
  82939. }
  82940. /**
  82941. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82942. * @param scene scene in which to add meshes
  82943. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82944. */
  82945. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82946. var _this = this;
  82947. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  82948. /*
  82949. Parent Mesh name: ViveWand
  82950. - body
  82951. - r_gripper
  82952. - l_gripper
  82953. - menu_button
  82954. - system_button
  82955. - trackpad
  82956. - trigger
  82957. - LED
  82958. */
  82959. _this._defaultModel = newMeshes[1];
  82960. _this.attachToMesh(_this._defaultModel);
  82961. if (meshLoaded) {
  82962. meshLoaded(_this._defaultModel);
  82963. }
  82964. });
  82965. };
  82966. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  82967. /**
  82968. * Fired when the left button on this controller is modified
  82969. */
  82970. get: function () {
  82971. return this.onMainButtonStateChangedObservable;
  82972. },
  82973. enumerable: true,
  82974. configurable: true
  82975. });
  82976. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  82977. /**
  82978. * Fired when the right button on this controller is modified
  82979. */
  82980. get: function () {
  82981. return this.onMainButtonStateChangedObservable;
  82982. },
  82983. enumerable: true,
  82984. configurable: true
  82985. });
  82986. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  82987. /**
  82988. * Fired when the menu button on this controller is modified
  82989. */
  82990. get: function () {
  82991. return this.onSecondaryButtonStateChangedObservable;
  82992. },
  82993. enumerable: true,
  82994. configurable: true
  82995. });
  82996. /**
  82997. * Called once for each button that changed state since the last frame
  82998. * Vive mapping:
  82999. * 0: touchpad
  83000. * 1: trigger
  83001. * 2: left AND right buttons
  83002. * 3: menu button
  83003. * @param buttonIdx Which button index changed
  83004. * @param state New state of the button
  83005. * @param changes Which properties on the state changed since last frame
  83006. */
  83007. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  83008. var notifyObject = state; //{ state: state, changes: changes };
  83009. switch (buttonIdx) {
  83010. case 0:
  83011. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  83012. return;
  83013. case 1: // index trigger
  83014. if (this._defaultModel) {
  83015. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  83016. }
  83017. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  83018. return;
  83019. case 2: // left AND right button
  83020. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  83021. return;
  83022. case 3:
  83023. if (this._defaultModel) {
  83024. if (notifyObject.pressed) {
  83025. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  83026. }
  83027. else {
  83028. (this._defaultModel.getChildren()[2]).position.y = 0;
  83029. }
  83030. }
  83031. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  83032. return;
  83033. }
  83034. };
  83035. /**
  83036. * Base Url for the controller model.
  83037. */
  83038. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  83039. /**
  83040. * File name for the controller model.
  83041. */
  83042. ViveController.MODEL_FILENAME = 'wand.babylon';
  83043. return ViveController;
  83044. }(BABYLON.WebVRController));
  83045. BABYLON.ViveController = ViveController;
  83046. })(BABYLON || (BABYLON = {}));
  83047. //# sourceMappingURL=viveController.js.map
  83048. var BABYLON;
  83049. (function (BABYLON) {
  83050. /**
  83051. * Generic Controller
  83052. */
  83053. var GenericController = /** @class */ (function (_super) {
  83054. __extends(GenericController, _super);
  83055. /**
  83056. * Creates a new GenericController from a gamepad
  83057. * @param vrGamepad the gamepad that the controller should be created from
  83058. */
  83059. function GenericController(vrGamepad) {
  83060. return _super.call(this, vrGamepad) || this;
  83061. }
  83062. /**
  83063. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  83064. * @param scene scene in which to add meshes
  83065. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  83066. */
  83067. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  83068. var _this = this;
  83069. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  83070. _this._defaultModel = newMeshes[1];
  83071. _this.attachToMesh(_this._defaultModel);
  83072. if (meshLoaded) {
  83073. meshLoaded(_this._defaultModel);
  83074. }
  83075. });
  83076. };
  83077. /**
  83078. * Called once for each button that changed state since the last frame
  83079. * @param buttonIdx Which button index changed
  83080. * @param state New state of the button
  83081. * @param changes Which properties on the state changed since last frame
  83082. */
  83083. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  83084. console.log("Button id: " + buttonIdx + "state: ");
  83085. console.dir(state);
  83086. };
  83087. /**
  83088. * Base Url for the controller model.
  83089. */
  83090. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  83091. /**
  83092. * File name for the controller model.
  83093. */
  83094. GenericController.MODEL_FILENAME = 'generic.babylon';
  83095. return GenericController;
  83096. }(BABYLON.WebVRController));
  83097. BABYLON.GenericController = GenericController;
  83098. })(BABYLON || (BABYLON = {}));
  83099. //# sourceMappingURL=genericController.js.map
  83100. var BABYLON;
  83101. (function (BABYLON) {
  83102. /**
  83103. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  83104. */
  83105. var LoadedMeshInfo = /** @class */ (function () {
  83106. function LoadedMeshInfo() {
  83107. /**
  83108. * Map of the button meshes contained in the controller
  83109. */
  83110. this.buttonMeshes = {};
  83111. /**
  83112. * Map of the axis meshes contained in the controller
  83113. */
  83114. this.axisMeshes = {};
  83115. }
  83116. return LoadedMeshInfo;
  83117. }());
  83118. /**
  83119. * Defines the WindowsMotionController object that the state of the windows motion controller
  83120. */
  83121. var WindowsMotionController = /** @class */ (function (_super) {
  83122. __extends(WindowsMotionController, _super);
  83123. /**
  83124. * Creates a new WindowsMotionController from a gamepad
  83125. * @param vrGamepad the gamepad that the controller should be created from
  83126. */
  83127. function WindowsMotionController(vrGamepad) {
  83128. var _this = _super.call(this, vrGamepad) || this;
  83129. _this._mapping = {
  83130. // Semantic button names
  83131. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  83132. // A mapping of the button name to glTF model node name
  83133. // that should be transformed by button value.
  83134. buttonMeshNames: {
  83135. 'trigger': 'SELECT',
  83136. 'menu': 'MENU',
  83137. 'grip': 'GRASP',
  83138. 'thumbstick': 'THUMBSTICK_PRESS',
  83139. 'trackpad': 'TOUCHPAD_PRESS'
  83140. },
  83141. // This mapping is used to translate from the Motion Controller to Babylon semantics
  83142. buttonObservableNames: {
  83143. 'trigger': 'onTriggerStateChangedObservable',
  83144. 'menu': 'onSecondaryButtonStateChangedObservable',
  83145. 'grip': 'onMainButtonStateChangedObservable',
  83146. 'thumbstick': 'onPadStateChangedObservable',
  83147. 'trackpad': 'onTrackpadChangedObservable'
  83148. },
  83149. // A mapping of the axis name to glTF model node name
  83150. // that should be transformed by axis value.
  83151. // This array mirrors the browserGamepad.axes array, such that
  83152. // the mesh corresponding to axis 0 is in this array index 0.
  83153. axisMeshNames: [
  83154. 'THUMBSTICK_X',
  83155. 'THUMBSTICK_Y',
  83156. 'TOUCHPAD_TOUCH_X',
  83157. 'TOUCHPAD_TOUCH_Y'
  83158. ],
  83159. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  83160. };
  83161. /**
  83162. * Fired when the trackpad on this controller is clicked
  83163. */
  83164. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  83165. /**
  83166. * Fired when the trackpad on this controller is modified
  83167. */
  83168. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  83169. /**
  83170. * The current x and y values of this controller's trackpad
  83171. */
  83172. _this.trackpad = { x: 0, y: 0 };
  83173. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  83174. _this._loadedMeshInfo = null;
  83175. return _this;
  83176. }
  83177. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  83178. /**
  83179. * Fired when the trigger on this controller is modified
  83180. */
  83181. get: function () {
  83182. return this.onTriggerStateChangedObservable;
  83183. },
  83184. enumerable: true,
  83185. configurable: true
  83186. });
  83187. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  83188. /**
  83189. * Fired when the menu button on this controller is modified
  83190. */
  83191. get: function () {
  83192. return this.onSecondaryButtonStateChangedObservable;
  83193. },
  83194. enumerable: true,
  83195. configurable: true
  83196. });
  83197. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  83198. /**
  83199. * Fired when the grip button on this controller is modified
  83200. */
  83201. get: function () {
  83202. return this.onMainButtonStateChangedObservable;
  83203. },
  83204. enumerable: true,
  83205. configurable: true
  83206. });
  83207. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  83208. /**
  83209. * Fired when the thumbstick button on this controller is modified
  83210. */
  83211. get: function () {
  83212. return this.onPadStateChangedObservable;
  83213. },
  83214. enumerable: true,
  83215. configurable: true
  83216. });
  83217. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  83218. /**
  83219. * Fired when the touchpad button on this controller is modified
  83220. */
  83221. get: function () {
  83222. return this.onTrackpadChangedObservable;
  83223. },
  83224. enumerable: true,
  83225. configurable: true
  83226. });
  83227. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  83228. /**
  83229. * Fired when the touchpad values on this controller are modified
  83230. */
  83231. get: function () {
  83232. return this.onTrackpadValuesChangedObservable;
  83233. },
  83234. enumerable: true,
  83235. configurable: true
  83236. });
  83237. WindowsMotionController.prototype._updateTrackpad = function () {
  83238. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  83239. this.trackpad.x = this.browserGamepad["axes"][2];
  83240. this.trackpad.y = this.browserGamepad["axes"][3];
  83241. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  83242. }
  83243. };
  83244. /**
  83245. * Called once per frame by the engine.
  83246. */
  83247. WindowsMotionController.prototype.update = function () {
  83248. _super.prototype.update.call(this);
  83249. if (this.browserGamepad.axes) {
  83250. this._updateTrackpad();
  83251. // Only need to animate axes if there is a loaded mesh
  83252. if (this._loadedMeshInfo) {
  83253. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  83254. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  83255. }
  83256. }
  83257. }
  83258. };
  83259. /**
  83260. * Called once for each button that changed state since the last frame
  83261. * @param buttonIdx Which button index changed
  83262. * @param state New state of the button
  83263. * @param changes Which properties on the state changed since last frame
  83264. */
  83265. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  83266. var buttonName = this._mapping.buttons[buttonIdx];
  83267. if (!buttonName) {
  83268. return;
  83269. }
  83270. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  83271. this._updateTrackpad();
  83272. // Only emit events for buttons that we know how to map from index to name
  83273. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  83274. if (observable) {
  83275. observable.notifyObservers(state);
  83276. }
  83277. this._lerpButtonTransform(buttonName, state.value);
  83278. };
  83279. /**
  83280. * Moves the buttons on the controller mesh based on their current state
  83281. * @param buttonName the name of the button to move
  83282. * @param buttonValue the value of the button which determines the buttons new position
  83283. */
  83284. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  83285. // If there is no loaded mesh, there is nothing to transform.
  83286. if (!this._loadedMeshInfo) {
  83287. return;
  83288. }
  83289. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  83290. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  83291. return;
  83292. }
  83293. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  83294. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  83295. };
  83296. /**
  83297. * Moves the axis on the controller mesh based on its current state
  83298. * @param axis the index of the axis
  83299. * @param axisValue the value of the axis which determines the meshes new position
  83300. * @hidden
  83301. */
  83302. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  83303. if (!this._loadedMeshInfo) {
  83304. return;
  83305. }
  83306. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  83307. if (!meshInfo) {
  83308. return;
  83309. }
  83310. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  83311. return;
  83312. }
  83313. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  83314. var lerpValue = axisValue * 0.5 + 0.5;
  83315. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  83316. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  83317. };
  83318. /**
  83319. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  83320. * @param scene scene in which to add meshes
  83321. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  83322. */
  83323. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  83324. var _this = this;
  83325. if (forceDefault === void 0) { forceDefault = false; }
  83326. var path;
  83327. var filename;
  83328. // Checking if GLB loader is present
  83329. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  83330. // Determine the device specific folder based on the ID suffix
  83331. var device = 'default';
  83332. if (this.id && !forceDefault) {
  83333. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  83334. device = ((match && match[0]) || device);
  83335. }
  83336. // Hand
  83337. if (this.hand === 'left') {
  83338. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  83339. }
  83340. else { // Right is the default if no hand is specified
  83341. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  83342. }
  83343. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  83344. }
  83345. else {
  83346. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  83347. path = BABYLON.GenericController.MODEL_BASE_URL;
  83348. filename = BABYLON.GenericController.MODEL_FILENAME;
  83349. }
  83350. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  83351. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  83352. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  83353. if (!_this._loadedMeshInfo) {
  83354. return;
  83355. }
  83356. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  83357. _this.attachToMesh(_this._defaultModel);
  83358. if (meshLoaded) {
  83359. meshLoaded(_this._defaultModel);
  83360. }
  83361. }, null, function (scene, message) {
  83362. BABYLON.Tools.Log(message);
  83363. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  83364. if (!forceDefault) {
  83365. _this.initControllerMesh(scene, meshLoaded, true);
  83366. }
  83367. });
  83368. };
  83369. /**
  83370. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  83371. * can be transformed by button presses and axes values, based on this._mapping.
  83372. *
  83373. * @param scene scene in which the meshes exist
  83374. * @param meshes list of meshes that make up the controller model to process
  83375. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  83376. */
  83377. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  83378. var loadedMeshInfo = null;
  83379. // Create a new mesh to contain the glTF hierarchy
  83380. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  83381. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  83382. var childMesh = null;
  83383. for (var i = 0; i < meshes.length; i++) {
  83384. var mesh = meshes[i];
  83385. if (!mesh.parent) {
  83386. // Exclude controller meshes from picking results
  83387. mesh.isPickable = false;
  83388. // Handle root node, attach to the new parentMesh
  83389. childMesh = mesh;
  83390. break;
  83391. }
  83392. }
  83393. if (childMesh) {
  83394. childMesh.setParent(parentMesh);
  83395. // Create our mesh info. Note that this method will always return non-null.
  83396. loadedMeshInfo = this.createMeshInfo(parentMesh);
  83397. }
  83398. else {
  83399. BABYLON.Tools.Warn('Could not find root node in model file.');
  83400. }
  83401. return loadedMeshInfo;
  83402. };
  83403. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  83404. var loadedMeshInfo = new LoadedMeshInfo();
  83405. var i;
  83406. loadedMeshInfo.rootNode = rootNode;
  83407. // Reset the caches
  83408. loadedMeshInfo.buttonMeshes = {};
  83409. loadedMeshInfo.axisMeshes = {};
  83410. // Button Meshes
  83411. for (i = 0; i < this._mapping.buttons.length; i++) {
  83412. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  83413. if (!buttonMeshName) {
  83414. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  83415. continue;
  83416. }
  83417. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  83418. if (!buttonMesh) {
  83419. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  83420. continue;
  83421. }
  83422. var buttonMeshInfo = {
  83423. index: i,
  83424. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  83425. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  83426. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  83427. };
  83428. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  83429. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  83430. }
  83431. else {
  83432. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  83433. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  83434. '(VALUE: ' + !!buttonMeshInfo.value +
  83435. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  83436. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  83437. ')');
  83438. }
  83439. }
  83440. // Axis Meshes
  83441. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  83442. var axisMeshName = this._mapping.axisMeshNames[i];
  83443. if (!axisMeshName) {
  83444. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  83445. continue;
  83446. }
  83447. var axisMesh = getChildByName(rootNode, axisMeshName);
  83448. if (!axisMesh) {
  83449. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  83450. continue;
  83451. }
  83452. var axisMeshInfo = {
  83453. index: i,
  83454. value: getImmediateChildByName(axisMesh, 'VALUE'),
  83455. min: getImmediateChildByName(axisMesh, 'MIN'),
  83456. max: getImmediateChildByName(axisMesh, 'MAX')
  83457. };
  83458. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  83459. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  83460. }
  83461. else {
  83462. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  83463. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  83464. '(VALUE: ' + !!axisMeshInfo.value +
  83465. ', MIN: ' + !!axisMeshInfo.min +
  83466. ', MAX:' + !!axisMeshInfo.max +
  83467. ')');
  83468. }
  83469. }
  83470. // Pointing Ray
  83471. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  83472. if (!loadedMeshInfo.pointingPoseNode) {
  83473. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  83474. }
  83475. else {
  83476. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  83477. }
  83478. return loadedMeshInfo;
  83479. // Look through all children recursively. This will return null if no mesh exists with the given name.
  83480. function getChildByName(node, name) {
  83481. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  83482. }
  83483. // Look through only immediate children. This will return null if no mesh exists with the given name.
  83484. function getImmediateChildByName(node, name) {
  83485. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  83486. }
  83487. };
  83488. /**
  83489. * Gets the ray of the controller in the direction the controller is pointing
  83490. * @param length the length the resulting ray should be
  83491. * @returns a ray in the direction the controller is pointing
  83492. */
  83493. WindowsMotionController.prototype.getForwardRay = function (length) {
  83494. if (length === void 0) { length = 100; }
  83495. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  83496. return _super.prototype.getForwardRay.call(this, length);
  83497. }
  83498. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  83499. var origin = m.getTranslation();
  83500. var forward = new BABYLON.Vector3(0, 0, -1);
  83501. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  83502. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  83503. return new BABYLON.Ray(origin, direction, length);
  83504. };
  83505. /**
  83506. * Disposes of the controller
  83507. */
  83508. WindowsMotionController.prototype.dispose = function () {
  83509. _super.prototype.dispose.call(this);
  83510. this.onTrackpadChangedObservable.clear();
  83511. };
  83512. /**
  83513. * The base url used to load the left and right controller models
  83514. */
  83515. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  83516. /**
  83517. * The name of the left controller model file
  83518. */
  83519. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  83520. /**
  83521. * The name of the right controller model file
  83522. */
  83523. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  83524. /**
  83525. * The controller name prefix for this controller type
  83526. */
  83527. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  83528. /**
  83529. * The controller id pattern for this controller type
  83530. */
  83531. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  83532. return WindowsMotionController;
  83533. }(BABYLON.WebVRController));
  83534. BABYLON.WindowsMotionController = WindowsMotionController;
  83535. })(BABYLON || (BABYLON = {}));
  83536. //# sourceMappingURL=windowsMotionController.js.map
  83537. var BABYLON;
  83538. (function (BABYLON) {
  83539. /**
  83540. * Gear VR Controller
  83541. */
  83542. var GearVRController = /** @class */ (function (_super) {
  83543. __extends(GearVRController, _super);
  83544. /**
  83545. * Creates a new GearVRController from a gamepad
  83546. * @param vrGamepad the gamepad that the controller should be created from
  83547. */
  83548. function GearVRController(vrGamepad) {
  83549. var _this = _super.call(this, vrGamepad) || this;
  83550. _this._buttonIndexToObservableNameMap = [
  83551. 'onTrackpadChangedObservable',
  83552. 'onTriggerStateChangedObservable' // Trigger
  83553. ];
  83554. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  83555. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  83556. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  83557. _this._disableTrackPosition(_this._calculatedPosition);
  83558. return _this;
  83559. }
  83560. /**
  83561. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  83562. * @param scene scene in which to add meshes
  83563. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  83564. */
  83565. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  83566. var _this = this;
  83567. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  83568. // Offset the controller so it will rotate around the users wrist
  83569. var mesh = new BABYLON.Mesh("", scene);
  83570. newMeshes[1].parent = mesh;
  83571. newMeshes[1].position.z = -0.15;
  83572. _this._defaultModel = mesh;
  83573. _this.attachToMesh(_this._defaultModel);
  83574. if (meshLoaded) {
  83575. meshLoaded(_this._defaultModel);
  83576. }
  83577. });
  83578. };
  83579. /**
  83580. * Called once for each button that changed state since the last frame
  83581. * @param buttonIdx Which button index changed
  83582. * @param state New state of the button
  83583. * @param changes Which properties on the state changed since last frame
  83584. */
  83585. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  83586. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  83587. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  83588. // Only emit events for buttons that we know how to map from index to observable
  83589. var observable = this[observableName];
  83590. if (observable) {
  83591. observable.notifyObservers(state);
  83592. }
  83593. }
  83594. };
  83595. /**
  83596. * Base Url for the controller model.
  83597. */
  83598. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  83599. /**
  83600. * File name for the controller model.
  83601. */
  83602. GearVRController.MODEL_FILENAME = 'generic.babylon';
  83603. /**
  83604. * Gamepad Id prefix used to identify this controller.
  83605. */
  83606. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  83607. return GearVRController;
  83608. }(BABYLON.WebVRController));
  83609. BABYLON.GearVRController = GearVRController;
  83610. })(BABYLON || (BABYLON = {}));
  83611. //# sourceMappingURL=gearVRController.js.map
  83612. var BABYLON;
  83613. (function (BABYLON) {
  83614. /**
  83615. * Google Daydream controller
  83616. */
  83617. var DaydreamController = /** @class */ (function (_super) {
  83618. __extends(DaydreamController, _super);
  83619. /**
  83620. * Creates a new DaydreamController from a gamepad
  83621. * @param vrGamepad the gamepad that the controller should be created from
  83622. */
  83623. function DaydreamController(vrGamepad) {
  83624. var _this = _super.call(this, vrGamepad) || this;
  83625. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  83626. return _this;
  83627. }
  83628. /**
  83629. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  83630. * @param scene scene in which to add meshes
  83631. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  83632. */
  83633. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  83634. var _this = this;
  83635. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  83636. _this._defaultModel = newMeshes[1];
  83637. _this.attachToMesh(_this._defaultModel);
  83638. if (meshLoaded) {
  83639. meshLoaded(_this._defaultModel);
  83640. }
  83641. });
  83642. };
  83643. /**
  83644. * Called once for each button that changed state since the last frame
  83645. * @param buttonIdx Which button index changed
  83646. * @param state New state of the button
  83647. * @param changes Which properties on the state changed since last frame
  83648. */
  83649. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  83650. // Daydream controller only has 1 GamepadButton (on the trackpad).
  83651. if (buttonIdx === 0) {
  83652. var observable = this.onTriggerStateChangedObservable;
  83653. if (observable) {
  83654. observable.notifyObservers(state);
  83655. }
  83656. }
  83657. else {
  83658. // If the app or home buttons are ever made available
  83659. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  83660. }
  83661. };
  83662. /**
  83663. * Base Url for the controller model.
  83664. */
  83665. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  83666. /**
  83667. * File name for the controller model.
  83668. */
  83669. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  83670. /**
  83671. * Gamepad Id prefix used to identify Daydream Controller.
  83672. */
  83673. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  83674. return DaydreamController;
  83675. }(BABYLON.WebVRController));
  83676. BABYLON.DaydreamController = DaydreamController;
  83677. })(BABYLON || (BABYLON = {}));
  83678. //# sourceMappingURL=daydreamController.js.map
  83679. var BABYLON;
  83680. (function (BABYLON) {
  83681. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  83682. get: function () {
  83683. if (!this._gamepadManager) {
  83684. this._gamepadManager = new BABYLON.GamepadManager(this);
  83685. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  83686. if (!component) {
  83687. component = new GamepadSystemSceneComponent(this);
  83688. this._addComponent(component);
  83689. }
  83690. }
  83691. return this._gamepadManager;
  83692. },
  83693. enumerable: true,
  83694. configurable: true
  83695. });
  83696. /**
  83697. * Adds a gamepad to the free camera inputs manager
  83698. */
  83699. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  83700. this.add(new BABYLON.FreeCameraGamepadInput());
  83701. return this;
  83702. };
  83703. /**
  83704. * Adds a gamepad to the arc rotate camera inputs manager
  83705. */
  83706. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  83707. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  83708. return this;
  83709. };
  83710. /**
  83711. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  83712. */
  83713. var GamepadSystemSceneComponent = /** @class */ (function () {
  83714. /**
  83715. * Creates a new instance of the component for the given scene
  83716. * @param scene Defines the scene to register the component in
  83717. */
  83718. function GamepadSystemSceneComponent(scene) {
  83719. /**
  83720. * The component name helpfull to identify the component in the list of scene components.
  83721. */
  83722. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  83723. this.scene = scene;
  83724. }
  83725. /**
  83726. * Registers the component in a given scene
  83727. */
  83728. GamepadSystemSceneComponent.prototype.register = function () {
  83729. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  83730. };
  83731. /**
  83732. * Rebuilds the elements related to this component in case of
  83733. * context lost for instance.
  83734. */
  83735. GamepadSystemSceneComponent.prototype.rebuild = function () {
  83736. // Nothing to do for gamepads
  83737. };
  83738. /**
  83739. * Disposes the component and the associated ressources
  83740. */
  83741. GamepadSystemSceneComponent.prototype.dispose = function () {
  83742. var gamepadManager = this.scene._gamepadManager;
  83743. if (gamepadManager) {
  83744. gamepadManager.dispose();
  83745. this.scene._gamepadManager = null;
  83746. }
  83747. };
  83748. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  83749. var gamepadManager = this.scene._gamepadManager;
  83750. if (gamepadManager && gamepadManager._isMonitoring) {
  83751. gamepadManager._checkGamepadsStatus();
  83752. }
  83753. };
  83754. return GamepadSystemSceneComponent;
  83755. }());
  83756. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  83757. })(BABYLON || (BABYLON = {}));
  83758. //# sourceMappingURL=gamepadSceneComponent.js.map
  83759. var BABYLON;
  83760. (function (BABYLON) {
  83761. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  83762. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  83763. });
  83764. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  83765. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  83766. });
  83767. /**
  83768. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  83769. * an arc rotate version arcFollowCamera are available.
  83770. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  83771. */
  83772. var FollowCamera = /** @class */ (function (_super) {
  83773. __extends(FollowCamera, _super);
  83774. /**
  83775. * Instantiates the follow camera.
  83776. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  83777. * @param name Define the name of the camera in the scene
  83778. * @param position Define the position of the camera
  83779. * @param scene Define the scene the camera belong to
  83780. * @param lockedTarget Define the target of the camera
  83781. */
  83782. function FollowCamera(name, position, scene, lockedTarget) {
  83783. if (lockedTarget === void 0) { lockedTarget = null; }
  83784. var _this = _super.call(this, name, position, scene) || this;
  83785. /**
  83786. * Distance the follow camera should follow an object at
  83787. */
  83788. _this.radius = 12;
  83789. /**
  83790. * Define a rotation offset between the camera and the object it follows
  83791. */
  83792. _this.rotationOffset = 0;
  83793. /**
  83794. * Define a height offset between the camera and the object it follows.
  83795. * It can help following an object from the top (like a car chaing a plane)
  83796. */
  83797. _this.heightOffset = 4;
  83798. /**
  83799. * Define how fast the camera can accelerate to follow it s target.
  83800. */
  83801. _this.cameraAcceleration = 0.05;
  83802. /**
  83803. * Define the speed limit of the camera following an object.
  83804. */
  83805. _this.maxCameraSpeed = 20;
  83806. _this.lockedTarget = lockedTarget;
  83807. return _this;
  83808. }
  83809. FollowCamera.prototype._follow = function (cameraTarget) {
  83810. if (!cameraTarget) {
  83811. return;
  83812. }
  83813. var yRotation;
  83814. if (cameraTarget.rotationQuaternion) {
  83815. var rotMatrix = new BABYLON.Matrix();
  83816. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  83817. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  83818. }
  83819. else {
  83820. yRotation = cameraTarget.rotation.y;
  83821. }
  83822. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  83823. var targetPosition = cameraTarget.getAbsolutePosition();
  83824. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  83825. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  83826. var dx = targetX - this.position.x;
  83827. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  83828. var dz = (targetZ) - this.position.z;
  83829. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  83830. var vy = dy * this.cameraAcceleration;
  83831. var vz = dz * this.cameraAcceleration * 2;
  83832. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  83833. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  83834. }
  83835. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  83836. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  83837. }
  83838. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  83839. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  83840. }
  83841. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  83842. this.setTarget(targetPosition);
  83843. };
  83844. /** @hidden */
  83845. FollowCamera.prototype._checkInputs = function () {
  83846. _super.prototype._checkInputs.call(this);
  83847. if (this.lockedTarget) {
  83848. this._follow(this.lockedTarget);
  83849. }
  83850. };
  83851. /**
  83852. * Gets the camera class name.
  83853. * @returns the class name
  83854. */
  83855. FollowCamera.prototype.getClassName = function () {
  83856. return "FollowCamera";
  83857. };
  83858. __decorate([
  83859. BABYLON.serialize()
  83860. ], FollowCamera.prototype, "radius", void 0);
  83861. __decorate([
  83862. BABYLON.serialize()
  83863. ], FollowCamera.prototype, "rotationOffset", void 0);
  83864. __decorate([
  83865. BABYLON.serialize()
  83866. ], FollowCamera.prototype, "heightOffset", void 0);
  83867. __decorate([
  83868. BABYLON.serialize()
  83869. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  83870. __decorate([
  83871. BABYLON.serialize()
  83872. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  83873. __decorate([
  83874. BABYLON.serializeAsMeshReference("lockedTargetId")
  83875. ], FollowCamera.prototype, "lockedTarget", void 0);
  83876. return FollowCamera;
  83877. }(BABYLON.TargetCamera));
  83878. BABYLON.FollowCamera = FollowCamera;
  83879. /**
  83880. * Arc Rotate version of the follow camera.
  83881. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  83882. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  83883. */
  83884. var ArcFollowCamera = /** @class */ (function (_super) {
  83885. __extends(ArcFollowCamera, _super);
  83886. /**
  83887. * Instantiates a new ArcFollowCamera
  83888. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  83889. * @param name Define the name of the camera
  83890. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  83891. * @param beta Define the rotation angle of the camera around the elevation axis
  83892. * @param radius Define the radius of the camera from its target point
  83893. * @param target Define the target of the camera
  83894. * @param scene Define the scene the camera belongs to
  83895. */
  83896. function ArcFollowCamera(name,
  83897. /** The longitudinal angle of the camera */
  83898. alpha,
  83899. /** The latitudinal angle of the camera */
  83900. beta,
  83901. /** The radius of the camera from its target */
  83902. radius,
  83903. /** Define the camera target (the messh it should follow) */
  83904. target, scene) {
  83905. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  83906. _this.alpha = alpha;
  83907. _this.beta = beta;
  83908. _this.radius = radius;
  83909. _this.target = target;
  83910. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  83911. _this._follow();
  83912. return _this;
  83913. }
  83914. ArcFollowCamera.prototype._follow = function () {
  83915. if (!this.target) {
  83916. return;
  83917. }
  83918. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  83919. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  83920. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  83921. var targetPosition = this.target.getAbsolutePosition();
  83922. this.position = targetPosition.add(this._cartesianCoordinates);
  83923. this.setTarget(targetPosition);
  83924. };
  83925. /** @hidden */
  83926. ArcFollowCamera.prototype._checkInputs = function () {
  83927. _super.prototype._checkInputs.call(this);
  83928. this._follow();
  83929. };
  83930. /**
  83931. * Returns the class name of the object.
  83932. * It is mostly used internally for serialization purposes.
  83933. */
  83934. ArcFollowCamera.prototype.getClassName = function () {
  83935. return "ArcFollowCamera";
  83936. };
  83937. return ArcFollowCamera;
  83938. }(BABYLON.TargetCamera));
  83939. BABYLON.ArcFollowCamera = ArcFollowCamera;
  83940. })(BABYLON || (BABYLON = {}));
  83941. //# sourceMappingURL=followCamera.js.map
  83942. var BABYLON;
  83943. (function (BABYLON) {
  83944. /**
  83945. * 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,
  83946. * which still works and will still be found in many Playgrounds.
  83947. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  83948. */
  83949. var UniversalCamera = /** @class */ (function (_super) {
  83950. __extends(UniversalCamera, _super);
  83951. /**
  83952. * 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,
  83953. * which still works and will still be found in many Playgrounds.
  83954. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  83955. * @param name Define the name of the camera in the scene
  83956. * @param position Define the start position of the camera in the scene
  83957. * @param scene Define the scene the camera belongs to
  83958. */
  83959. function UniversalCamera(name, position, scene) {
  83960. var _this = _super.call(this, name, position, scene) || this;
  83961. _this.inputs.addGamepad();
  83962. return _this;
  83963. }
  83964. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  83965. /**
  83966. * Defines the gamepad rotation sensiblity.
  83967. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  83968. */
  83969. get: function () {
  83970. var gamepad = this.inputs.attached["gamepad"];
  83971. if (gamepad) {
  83972. return gamepad.gamepadAngularSensibility;
  83973. }
  83974. return 0;
  83975. },
  83976. set: function (value) {
  83977. var gamepad = this.inputs.attached["gamepad"];
  83978. if (gamepad) {
  83979. gamepad.gamepadAngularSensibility = value;
  83980. }
  83981. },
  83982. enumerable: true,
  83983. configurable: true
  83984. });
  83985. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  83986. /**
  83987. * Defines the gamepad move sensiblity.
  83988. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  83989. */
  83990. get: function () {
  83991. var gamepad = this.inputs.attached["gamepad"];
  83992. if (gamepad) {
  83993. return gamepad.gamepadMoveSensibility;
  83994. }
  83995. return 0;
  83996. },
  83997. set: function (value) {
  83998. var gamepad = this.inputs.attached["gamepad"];
  83999. if (gamepad) {
  84000. gamepad.gamepadMoveSensibility = value;
  84001. }
  84002. },
  84003. enumerable: true,
  84004. configurable: true
  84005. });
  84006. /**
  84007. * Gets the current object class name.
  84008. * @return the class name
  84009. */
  84010. UniversalCamera.prototype.getClassName = function () {
  84011. return "UniversalCamera";
  84012. };
  84013. return UniversalCamera;
  84014. }(BABYLON.TouchCamera));
  84015. BABYLON.UniversalCamera = UniversalCamera;
  84016. })(BABYLON || (BABYLON = {}));
  84017. //# sourceMappingURL=universalCamera.js.map
  84018. var BABYLON;
  84019. (function (BABYLON) {
  84020. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  84021. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  84022. });
  84023. /**
  84024. * This represents a FPS type of camera. This is only here for back compat purpose.
  84025. * Please use the UniversalCamera instead as both are identical.
  84026. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  84027. */
  84028. var GamepadCamera = /** @class */ (function (_super) {
  84029. __extends(GamepadCamera, _super);
  84030. /**
  84031. * Instantiates a new Gamepad Camera
  84032. * This represents a FPS type of camera. This is only here for back compat purpose.
  84033. * Please use the UniversalCamera instead as both are identical.
  84034. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  84035. * @param name Define the name of the camera in the scene
  84036. * @param position Define the start position of the camera in the scene
  84037. * @param scene Define the scene the camera belongs to
  84038. */
  84039. function GamepadCamera(name, position, scene) {
  84040. return _super.call(this, name, position, scene) || this;
  84041. }
  84042. /**
  84043. * Gets the current object class name.
  84044. * @return the class name
  84045. */
  84046. GamepadCamera.prototype.getClassName = function () {
  84047. return "GamepadCamera";
  84048. };
  84049. return GamepadCamera;
  84050. }(BABYLON.UniversalCamera));
  84051. BABYLON.GamepadCamera = GamepadCamera;
  84052. })(BABYLON || (BABYLON = {}));
  84053. //# sourceMappingURL=gamepadCamera.js.map
  84054. var BABYLON;
  84055. (function (BABYLON) {
  84056. /**
  84057. * PostProcessRenderPipelineManager class
  84058. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  84059. */
  84060. var PostProcessRenderPipelineManager = /** @class */ (function () {
  84061. /**
  84062. * Initializes a PostProcessRenderPipelineManager
  84063. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  84064. */
  84065. function PostProcessRenderPipelineManager() {
  84066. this._renderPipelines = {};
  84067. }
  84068. /**
  84069. * Adds a pipeline to the manager
  84070. * @param renderPipeline The pipeline to add
  84071. */
  84072. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  84073. this._renderPipelines[renderPipeline._name] = renderPipeline;
  84074. };
  84075. /**
  84076. * Attaches a camera to the pipeline
  84077. * @param renderPipelineName The name of the pipeline to attach to
  84078. * @param cameras the camera to attach
  84079. * @param unique if the camera can be attached multiple times to the pipeline
  84080. */
  84081. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  84082. if (unique === void 0) { unique = false; }
  84083. var renderPipeline = this._renderPipelines[renderPipelineName];
  84084. if (!renderPipeline) {
  84085. return;
  84086. }
  84087. renderPipeline._attachCameras(cameras, unique);
  84088. };
  84089. /**
  84090. * Detaches a camera from the pipeline
  84091. * @param renderPipelineName The name of the pipeline to detach from
  84092. * @param cameras the camera to detach
  84093. */
  84094. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  84095. var renderPipeline = this._renderPipelines[renderPipelineName];
  84096. if (!renderPipeline) {
  84097. return;
  84098. }
  84099. renderPipeline._detachCameras(cameras);
  84100. };
  84101. /**
  84102. * Enables an effect by name on a pipeline
  84103. * @param renderPipelineName the name of the pipeline to enable the effect in
  84104. * @param renderEffectName the name of the effect to enable
  84105. * @param cameras the cameras that the effect should be enabled on
  84106. */
  84107. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  84108. var renderPipeline = this._renderPipelines[renderPipelineName];
  84109. if (!renderPipeline) {
  84110. return;
  84111. }
  84112. renderPipeline._enableEffect(renderEffectName, cameras);
  84113. };
  84114. /**
  84115. * Disables an effect by name on a pipeline
  84116. * @param renderPipelineName the name of the pipeline to disable the effect in
  84117. * @param renderEffectName the name of the effect to disable
  84118. * @param cameras the cameras that the effect should be disabled on
  84119. */
  84120. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  84121. var renderPipeline = this._renderPipelines[renderPipelineName];
  84122. if (!renderPipeline) {
  84123. return;
  84124. }
  84125. renderPipeline._disableEffect(renderEffectName, cameras);
  84126. };
  84127. /**
  84128. * Updates the state of all contained render pipelines and disposes of any non supported pipelines
  84129. */
  84130. PostProcessRenderPipelineManager.prototype.update = function () {
  84131. for (var renderPipelineName in this._renderPipelines) {
  84132. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  84133. var pipeline = this._renderPipelines[renderPipelineName];
  84134. if (!pipeline.isSupported) {
  84135. pipeline.dispose();
  84136. delete this._renderPipelines[renderPipelineName];
  84137. }
  84138. else {
  84139. pipeline._update();
  84140. }
  84141. }
  84142. }
  84143. };
  84144. /** @hidden */
  84145. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  84146. for (var renderPipelineName in this._renderPipelines) {
  84147. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  84148. var pipeline = this._renderPipelines[renderPipelineName];
  84149. pipeline._rebuild();
  84150. }
  84151. }
  84152. };
  84153. /**
  84154. * Disposes of the manager and pipelines
  84155. */
  84156. PostProcessRenderPipelineManager.prototype.dispose = function () {
  84157. for (var renderPipelineName in this._renderPipelines) {
  84158. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  84159. var pipeline = this._renderPipelines[renderPipelineName];
  84160. pipeline.dispose();
  84161. }
  84162. }
  84163. };
  84164. return PostProcessRenderPipelineManager;
  84165. }());
  84166. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  84167. })(BABYLON || (BABYLON = {}));
  84168. //# sourceMappingURL=postProcessRenderPipelineManager.js.map
  84169. var BABYLON;
  84170. (function (BABYLON) {
  84171. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  84172. get: function () {
  84173. if (!this._postProcessRenderPipelineManager) {
  84174. // Register the G Buffer component to the scene.
  84175. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  84176. if (!component) {
  84177. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  84178. this._addComponent(component);
  84179. }
  84180. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  84181. }
  84182. return this._postProcessRenderPipelineManager;
  84183. },
  84184. enumerable: true,
  84185. configurable: true
  84186. });
  84187. /**
  84188. * Defines the Render Pipeline scene component responsible to rendering pipelines
  84189. */
  84190. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  84191. /**
  84192. * Creates a new instance of the component for the given scene
  84193. * @param scene Defines the scene to register the component in
  84194. */
  84195. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  84196. /**
  84197. * The component name helpfull to identify the component in the list of scene components.
  84198. */
  84199. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  84200. this.scene = scene;
  84201. }
  84202. /**
  84203. * Registers the component in a given scene
  84204. */
  84205. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  84206. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  84207. };
  84208. /**
  84209. * Rebuilds the elements related to this component in case of
  84210. * context lost for instance.
  84211. */
  84212. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  84213. if (this.scene._postProcessRenderPipelineManager) {
  84214. this.scene._postProcessRenderPipelineManager._rebuild();
  84215. }
  84216. };
  84217. /**
  84218. * Disposes the component and the associated ressources
  84219. */
  84220. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  84221. if (this.scene._postProcessRenderPipelineManager) {
  84222. this.scene._postProcessRenderPipelineManager.dispose();
  84223. }
  84224. };
  84225. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  84226. if (this.scene._postProcessRenderPipelineManager) {
  84227. this.scene._postProcessRenderPipelineManager.update();
  84228. }
  84229. };
  84230. return PostProcessRenderPipelineManagerSceneComponent;
  84231. }());
  84232. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  84233. })(BABYLON || (BABYLON = {}));
  84234. //# sourceMappingURL=postProcessRenderPipelineManagerSceneComponent.js.map
  84235. var BABYLON;
  84236. (function (BABYLON) {
  84237. /**
  84238. * This represents a set of one or more post processes in Babylon.
  84239. * A post process can be used to apply a shader to a texture after it is rendered.
  84240. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  84241. */
  84242. var PostProcessRenderEffect = /** @class */ (function () {
  84243. /**
  84244. * Instantiates a post process render effect.
  84245. * A post process can be used to apply a shader to a texture after it is rendered.
  84246. * @param engine The engine the effect is tied to
  84247. * @param name The name of the effect
  84248. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  84249. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  84250. */
  84251. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  84252. this._name = name;
  84253. this._singleInstance = singleInstance || true;
  84254. this._getPostProcesses = getPostProcesses;
  84255. this._cameras = {};
  84256. this._indicesForCamera = {};
  84257. this._postProcesses = {};
  84258. }
  84259. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  84260. /**
  84261. * Checks if all the post processes in the effect are supported.
  84262. */
  84263. get: function () {
  84264. for (var index in this._postProcesses) {
  84265. if (this._postProcesses.hasOwnProperty(index)) {
  84266. var pps = this._postProcesses[index];
  84267. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  84268. if (!pps[ppIndex].isSupported) {
  84269. return false;
  84270. }
  84271. }
  84272. }
  84273. }
  84274. return true;
  84275. },
  84276. enumerable: true,
  84277. configurable: true
  84278. });
  84279. /**
  84280. * Updates the current state of the effect
  84281. * @hidden
  84282. */
  84283. PostProcessRenderEffect.prototype._update = function () {
  84284. };
  84285. /**
  84286. * Attaches the effect on cameras
  84287. * @param cameras The camera to attach to.
  84288. * @hidden
  84289. */
  84290. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  84291. var _this = this;
  84292. var cameraKey;
  84293. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84294. if (!cams) {
  84295. return;
  84296. }
  84297. for (var i = 0; i < cams.length; i++) {
  84298. var camera = cams[i];
  84299. var cameraName = camera.name;
  84300. if (this._singleInstance) {
  84301. cameraKey = 0;
  84302. }
  84303. else {
  84304. cameraKey = cameraName;
  84305. }
  84306. if (!this._postProcesses[cameraKey]) {
  84307. var postProcess = this._getPostProcesses();
  84308. if (postProcess) {
  84309. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  84310. }
  84311. }
  84312. if (!this._indicesForCamera[cameraName]) {
  84313. this._indicesForCamera[cameraName] = [];
  84314. }
  84315. this._postProcesses[cameraKey].forEach(function (postProcess) {
  84316. var index = camera.attachPostProcess(postProcess);
  84317. _this._indicesForCamera[cameraName].push(index);
  84318. });
  84319. if (!this._cameras[cameraName]) {
  84320. this._cameras[cameraName] = camera;
  84321. }
  84322. }
  84323. };
  84324. /**
  84325. * Detatches the effect on cameras
  84326. * @param cameras The camera to detatch from.
  84327. * @hidden
  84328. */
  84329. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  84330. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84331. if (!cams) {
  84332. return;
  84333. }
  84334. for (var i = 0; i < cams.length; i++) {
  84335. var camera = cams[i];
  84336. var cameraName = camera.name;
  84337. var postProcesses = this._postProcesses[this._singleInstance ? 0 : cameraName];
  84338. if (postProcesses) {
  84339. postProcesses.forEach(function (postProcess) {
  84340. camera.detachPostProcess(postProcess);
  84341. });
  84342. }
  84343. if (this._cameras[cameraName]) {
  84344. this._cameras[cameraName] = null;
  84345. }
  84346. }
  84347. };
  84348. /**
  84349. * Enables the effect on given cameras
  84350. * @param cameras The camera to enable.
  84351. * @hidden
  84352. */
  84353. PostProcessRenderEffect.prototype._enable = function (cameras) {
  84354. var _this = this;
  84355. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84356. if (!cams) {
  84357. return;
  84358. }
  84359. for (var i = 0; i < cams.length; i++) {
  84360. var camera = cams[i];
  84361. var cameraName = camera.name;
  84362. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  84363. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  84364. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  84365. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  84366. });
  84367. }
  84368. }
  84369. }
  84370. };
  84371. /**
  84372. * Disables the effect on the given cameras
  84373. * @param cameras The camera to disable.
  84374. * @hidden
  84375. */
  84376. PostProcessRenderEffect.prototype._disable = function (cameras) {
  84377. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84378. if (!cams) {
  84379. return;
  84380. }
  84381. for (var i = 0; i < cams.length; i++) {
  84382. var camera = cams[i];
  84383. var cameraName = camera.name;
  84384. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  84385. camera.detachPostProcess(postProcess);
  84386. });
  84387. }
  84388. };
  84389. /**
  84390. * Gets a list of the post processes contained in the effect.
  84391. * @param camera The camera to get the post processes on.
  84392. * @returns The list of the post processes in the effect.
  84393. */
  84394. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  84395. if (this._singleInstance) {
  84396. return this._postProcesses[0];
  84397. }
  84398. else {
  84399. if (!camera) {
  84400. return null;
  84401. }
  84402. return this._postProcesses[camera.name];
  84403. }
  84404. };
  84405. return PostProcessRenderEffect;
  84406. }());
  84407. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  84408. })(BABYLON || (BABYLON = {}));
  84409. //# sourceMappingURL=postProcessRenderEffect.js.map
  84410. var BABYLON;
  84411. (function (BABYLON) {
  84412. /**
  84413. * PostProcessRenderPipeline
  84414. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  84415. */
  84416. var PostProcessRenderPipeline = /** @class */ (function () {
  84417. /**
  84418. * Initializes a PostProcessRenderPipeline
  84419. * @param engine engine to add the pipeline to
  84420. * @param name name of the pipeline
  84421. */
  84422. function PostProcessRenderPipeline(engine, name) {
  84423. this.engine = engine;
  84424. this._name = name;
  84425. this._renderEffects = {};
  84426. this._renderEffectsForIsolatedPass = new Array();
  84427. this._cameras = [];
  84428. }
  84429. /**
  84430. * "PostProcessRenderPipeline"
  84431. * @returns "PostProcessRenderPipeline"
  84432. */
  84433. PostProcessRenderPipeline.prototype.getClassName = function () {
  84434. return "PostProcessRenderPipeline";
  84435. };
  84436. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  84437. /**
  84438. * If all the render effects in the pipeline are support
  84439. */
  84440. get: function () {
  84441. for (var renderEffectName in this._renderEffects) {
  84442. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  84443. if (!this._renderEffects[renderEffectName].isSupported) {
  84444. return false;
  84445. }
  84446. }
  84447. }
  84448. return true;
  84449. },
  84450. enumerable: true,
  84451. configurable: true
  84452. });
  84453. /**
  84454. * Adds an effect to the pipeline
  84455. * @param renderEffect the effect to add
  84456. */
  84457. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  84458. this._renderEffects[renderEffect._name] = renderEffect;
  84459. };
  84460. // private
  84461. /** @hidden */
  84462. PostProcessRenderPipeline.prototype._rebuild = function () {
  84463. };
  84464. /** @hidden */
  84465. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  84466. var renderEffects = this._renderEffects[renderEffectName];
  84467. if (!renderEffects) {
  84468. return;
  84469. }
  84470. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  84471. };
  84472. /** @hidden */
  84473. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  84474. var renderEffects = this._renderEffects[renderEffectName];
  84475. if (!renderEffects) {
  84476. return;
  84477. }
  84478. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  84479. };
  84480. /** @hidden */
  84481. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  84482. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84483. if (!cams) {
  84484. return;
  84485. }
  84486. var indicesToDelete = [];
  84487. var i;
  84488. for (i = 0; i < cams.length; i++) {
  84489. var camera = cams[i];
  84490. var cameraName = camera.name;
  84491. if (this._cameras.indexOf(camera) === -1) {
  84492. this._cameras[cameraName] = camera;
  84493. }
  84494. else if (unique) {
  84495. indicesToDelete.push(i);
  84496. }
  84497. }
  84498. for (i = 0; i < indicesToDelete.length; i++) {
  84499. cameras.splice(indicesToDelete[i], 1);
  84500. }
  84501. for (var renderEffectName in this._renderEffects) {
  84502. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  84503. this._renderEffects[renderEffectName]._attachCameras(cams);
  84504. }
  84505. }
  84506. };
  84507. /** @hidden */
  84508. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  84509. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  84510. if (!cams) {
  84511. return;
  84512. }
  84513. for (var renderEffectName in this._renderEffects) {
  84514. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  84515. this._renderEffects[renderEffectName]._detachCameras(cams);
  84516. }
  84517. }
  84518. for (var i = 0; i < cams.length; i++) {
  84519. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  84520. }
  84521. };
  84522. /** @hidden */
  84523. PostProcessRenderPipeline.prototype._update = function () {
  84524. for (var renderEffectName in this._renderEffects) {
  84525. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  84526. this._renderEffects[renderEffectName]._update();
  84527. }
  84528. }
  84529. for (var i = 0; i < this._cameras.length; i++) {
  84530. var cameraName = this._cameras[i].name;
  84531. if (this._renderEffectsForIsolatedPass[cameraName]) {
  84532. this._renderEffectsForIsolatedPass[cameraName]._update();
  84533. }
  84534. }
  84535. };
  84536. /** @hidden */
  84537. PostProcessRenderPipeline.prototype._reset = function () {
  84538. this._renderEffects = {};
  84539. this._renderEffectsForIsolatedPass = new Array();
  84540. };
  84541. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  84542. // 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)
  84543. var effectKeys = Object.keys(this._renderEffects);
  84544. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  84545. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  84546. if (postProcesses) {
  84547. postProcesses[0].samples = sampleCount;
  84548. return true;
  84549. }
  84550. }
  84551. return false;
  84552. };
  84553. /**
  84554. * Disposes of the pipeline
  84555. */
  84556. PostProcessRenderPipeline.prototype.dispose = function () {
  84557. // Must be implemented by children
  84558. };
  84559. __decorate([
  84560. BABYLON.serialize()
  84561. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  84562. return PostProcessRenderPipeline;
  84563. }());
  84564. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  84565. })(BABYLON || (BABYLON = {}));
  84566. //# sourceMappingURL=postProcessRenderPipeline.js.map
  84567. var BABYLON;
  84568. (function (BABYLON) {
  84569. /**
  84570. * This represents a depth renderer in Babylon.
  84571. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  84572. */
  84573. var DepthRenderer = /** @class */ (function () {
  84574. /**
  84575. * Instantiates a depth renderer
  84576. * @param scene The scene the renderer belongs to
  84577. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  84578. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  84579. */
  84580. function DepthRenderer(scene, type, camera) {
  84581. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  84582. if (camera === void 0) { camera = null; }
  84583. var _this = this;
  84584. /**
  84585. * Specifiess that the depth renderer will only be used within
  84586. * the camera it is created for.
  84587. * This can help forcing its rendering during the camera processing.
  84588. */
  84589. this.useOnlyInActiveCamera = false;
  84590. this._scene = scene;
  84591. // Register the G Buffer component to the scene.
  84592. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  84593. if (!component) {
  84594. component = new BABYLON.DepthRendererSceneComponent(scene);
  84595. scene._addComponent(component);
  84596. }
  84597. this._camera = camera;
  84598. var engine = scene.getEngine();
  84599. // Render target
  84600. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  84601. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84602. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84603. this._depthMap.refreshRate = 1;
  84604. this._depthMap.renderParticles = false;
  84605. this._depthMap.renderList = null;
  84606. // Camera to get depth map from to support multiple concurrent cameras
  84607. this._depthMap.activeCamera = this._camera;
  84608. this._depthMap.ignoreCameraViewport = true;
  84609. this._depthMap.useCameraPostProcesses = false;
  84610. // set default depth value to 1.0 (far away)
  84611. this._depthMap.onClearObservable.add(function (engine) {
  84612. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  84613. });
  84614. // Custom render function
  84615. var renderSubMesh = function (subMesh) {
  84616. var mesh = subMesh.getRenderingMesh();
  84617. var scene = _this._scene;
  84618. var engine = scene.getEngine();
  84619. var material = subMesh.getMaterial();
  84620. if (!material) {
  84621. return;
  84622. }
  84623. // Culling and reverse (right handed system)
  84624. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  84625. // Managing instances
  84626. var batch = mesh._getInstancesRenderList(subMesh._id);
  84627. if (batch.mustReturn) {
  84628. return;
  84629. }
  84630. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  84631. var camera = _this._camera || scene.activeCamera;
  84632. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  84633. engine.enableEffect(_this._effect);
  84634. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  84635. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  84636. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  84637. // Alpha test
  84638. if (material && material.needAlphaTesting()) {
  84639. var alphaTexture = material.getAlphaTestTexture();
  84640. if (alphaTexture) {
  84641. _this._effect.setTexture("diffuseSampler", alphaTexture);
  84642. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  84643. }
  84644. }
  84645. // Bones
  84646. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84647. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84648. }
  84649. // Draw
  84650. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  84651. }
  84652. };
  84653. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  84654. var index;
  84655. if (depthOnlySubMeshes.length) {
  84656. engine.setColorWrite(false);
  84657. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  84658. renderSubMesh(depthOnlySubMeshes.data[index]);
  84659. }
  84660. engine.setColorWrite(true);
  84661. }
  84662. for (index = 0; index < opaqueSubMeshes.length; index++) {
  84663. renderSubMesh(opaqueSubMeshes.data[index]);
  84664. }
  84665. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  84666. renderSubMesh(alphaTestSubMeshes.data[index]);
  84667. }
  84668. };
  84669. }
  84670. /**
  84671. * Creates the depth rendering effect and checks if the effect is ready.
  84672. * @param subMesh The submesh to be used to render the depth map of
  84673. * @param useInstances If multiple world instances should be used
  84674. * @returns if the depth renderer is ready to render the depth map
  84675. */
  84676. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  84677. var material = subMesh.getMaterial();
  84678. if (material.disableDepthWrite) {
  84679. return false;
  84680. }
  84681. var defines = [];
  84682. var attribs = [BABYLON.VertexBuffer.PositionKind];
  84683. var mesh = subMesh.getMesh();
  84684. // Alpha test
  84685. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  84686. defines.push("#define ALPHATEST");
  84687. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84688. attribs.push(BABYLON.VertexBuffer.UVKind);
  84689. defines.push("#define UV1");
  84690. }
  84691. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  84692. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84693. defines.push("#define UV2");
  84694. }
  84695. }
  84696. // Bones
  84697. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84698. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84699. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84700. if (mesh.numBoneInfluencers > 4) {
  84701. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84702. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84703. }
  84704. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84705. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  84706. }
  84707. else {
  84708. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84709. }
  84710. // Instances
  84711. if (useInstances) {
  84712. defines.push("#define INSTANCES");
  84713. attribs.push("world0");
  84714. attribs.push("world1");
  84715. attribs.push("world2");
  84716. attribs.push("world3");
  84717. }
  84718. // Get correct effect
  84719. var join = defines.join("\n");
  84720. if (this._cachedDefines !== join) {
  84721. this._cachedDefines = join;
  84722. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  84723. }
  84724. return this._effect.isReady();
  84725. };
  84726. /**
  84727. * Gets the texture which the depth map will be written to.
  84728. * @returns The depth map texture
  84729. */
  84730. DepthRenderer.prototype.getDepthMap = function () {
  84731. return this._depthMap;
  84732. };
  84733. /**
  84734. * Disposes of the depth renderer.
  84735. */
  84736. DepthRenderer.prototype.dispose = function () {
  84737. this._depthMap.dispose();
  84738. };
  84739. return DepthRenderer;
  84740. }());
  84741. BABYLON.DepthRenderer = DepthRenderer;
  84742. })(BABYLON || (BABYLON = {}));
  84743. //# sourceMappingURL=depthRenderer.js.map
  84744. var BABYLON;
  84745. (function (BABYLON) {
  84746. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  84747. camera = camera || this.activeCamera;
  84748. if (!camera) {
  84749. throw "No camera available to enable depth renderer";
  84750. }
  84751. if (!this._depthRenderer) {
  84752. this._depthRenderer = {};
  84753. }
  84754. if (!this._depthRenderer[camera.id]) {
  84755. var textureType = 0;
  84756. if (this.getEngine().getCaps().textureHalfFloatRender) {
  84757. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84758. }
  84759. else if (this.getEngine().getCaps().textureFloatRender) {
  84760. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84761. }
  84762. else {
  84763. throw "Depth renderer does not support int texture type";
  84764. }
  84765. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  84766. }
  84767. return this._depthRenderer[camera.id];
  84768. };
  84769. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  84770. camera = camera || this.activeCamera;
  84771. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  84772. return;
  84773. }
  84774. this._depthRenderer[camera.id].dispose();
  84775. delete this._depthRenderer[camera.id];
  84776. };
  84777. /**
  84778. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  84779. * in several rendering techniques.
  84780. */
  84781. var DepthRendererSceneComponent = /** @class */ (function () {
  84782. /**
  84783. * Creates a new instance of the component for the given scene
  84784. * @param scene Defines the scene to register the component in
  84785. */
  84786. function DepthRendererSceneComponent(scene) {
  84787. /**
  84788. * The component name helpfull to identify the component in the list of scene components.
  84789. */
  84790. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  84791. this.scene = scene;
  84792. }
  84793. /**
  84794. * Registers the component in a given scene
  84795. */
  84796. DepthRendererSceneComponent.prototype.register = function () {
  84797. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  84798. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  84799. };
  84800. /**
  84801. * Rebuilds the elements related to this component in case of
  84802. * context lost for instance.
  84803. */
  84804. DepthRendererSceneComponent.prototype.rebuild = function () {
  84805. // Nothing to do for this component
  84806. };
  84807. /**
  84808. * Disposes the component and the associated ressources
  84809. */
  84810. DepthRendererSceneComponent.prototype.dispose = function () {
  84811. for (var key in this.scene._depthRenderer) {
  84812. this.scene._depthRenderer[key].dispose();
  84813. }
  84814. };
  84815. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  84816. if (this.scene._depthRenderer) {
  84817. for (var key in this.scene._depthRenderer) {
  84818. var depthRenderer = this.scene._depthRenderer[key];
  84819. if (!depthRenderer.useOnlyInActiveCamera) {
  84820. renderTargets.push(depthRenderer.getDepthMap());
  84821. }
  84822. }
  84823. }
  84824. };
  84825. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  84826. if (this.scene._depthRenderer) {
  84827. for (var key in this.scene._depthRenderer) {
  84828. var depthRenderer = this.scene._depthRenderer[key];
  84829. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  84830. renderTargets.push(depthRenderer.getDepthMap());
  84831. }
  84832. }
  84833. }
  84834. };
  84835. return DepthRendererSceneComponent;
  84836. }());
  84837. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  84838. })(BABYLON || (BABYLON = {}));
  84839. //# sourceMappingURL=depthRendererSceneComponent.js.map
  84840. var BABYLON;
  84841. (function (BABYLON) {
  84842. /**
  84843. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  84844. */
  84845. var GeometryBufferRenderer = /** @class */ (function () {
  84846. /**
  84847. * Creates a new G Buffer for the scene
  84848. * @param scene The scene the buffer belongs to
  84849. * @param ratio How big is the buffer related to the main canvas.
  84850. */
  84851. function GeometryBufferRenderer(scene, ratio) {
  84852. if (ratio === void 0) { ratio = 1; }
  84853. /**
  84854. * Dictionary used to store the previous transformation matrices of each rendered mesh
  84855. * in order to compute objects velocities when enableVelocity is set to "true"
  84856. * @hidden
  84857. */
  84858. this._previousTransformationMatrices = {};
  84859. this._enablePosition = false;
  84860. this._enableVelocity = false;
  84861. this._positionIndex = -1;
  84862. this._velocityIndex = -1;
  84863. this._scene = scene;
  84864. this._ratio = ratio;
  84865. // Register the G Buffer component to the scene.
  84866. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  84867. if (!component) {
  84868. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  84869. scene._addComponent(component);
  84870. }
  84871. // Render target
  84872. this._createRenderTargets();
  84873. }
  84874. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  84875. /**
  84876. * Set the render list (meshes to be rendered) used in the G buffer.
  84877. */
  84878. set: function (meshes) {
  84879. this._multiRenderTarget.renderList = meshes;
  84880. },
  84881. enumerable: true,
  84882. configurable: true
  84883. });
  84884. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  84885. /**
  84886. * Gets wether or not G buffer are supported by the running hardware.
  84887. * This requires draw buffer supports
  84888. */
  84889. get: function () {
  84890. return this._multiRenderTarget.isSupported;
  84891. },
  84892. enumerable: true,
  84893. configurable: true
  84894. });
  84895. /**
  84896. * Returns the index of the given texture type in the G-Buffer textures array
  84897. * @param textureType The texture type constant. For example GeometryBufferRenderer.POSITION_TEXTURE_INDEX
  84898. * @returns the index of the given texture type in the G-Buffer textures array
  84899. */
  84900. GeometryBufferRenderer.prototype.getTextureIndex = function (textureType) {
  84901. switch (textureType) {
  84902. case GeometryBufferRenderer.POSITION_TEXTURE_TYPE: return this._positionIndex;
  84903. case GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE: return this._velocityIndex;
  84904. default: return -1;
  84905. }
  84906. };
  84907. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  84908. /**
  84909. * Gets a boolean indicating if objects positions are enabled for the G buffer.
  84910. */
  84911. get: function () {
  84912. return this._enablePosition;
  84913. },
  84914. /**
  84915. * Sets whether or not objects positions are enabled for the G buffer.
  84916. */
  84917. set: function (enable) {
  84918. this._enablePosition = enable;
  84919. this.dispose();
  84920. this._createRenderTargets();
  84921. },
  84922. enumerable: true,
  84923. configurable: true
  84924. });
  84925. Object.defineProperty(GeometryBufferRenderer.prototype, "enableVelocity", {
  84926. /**
  84927. * Gets a boolean indicating if objects velocities are enabled for the G buffer.
  84928. */
  84929. get: function () {
  84930. return this._enableVelocity;
  84931. },
  84932. /**
  84933. * Sets wether or not objects velocities are enabled for the G buffer.
  84934. */
  84935. set: function (enable) {
  84936. this._enableVelocity = enable;
  84937. this.dispose();
  84938. this._createRenderTargets();
  84939. },
  84940. enumerable: true,
  84941. configurable: true
  84942. });
  84943. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  84944. /**
  84945. * Gets the scene associated with the buffer.
  84946. */
  84947. get: function () {
  84948. return this._scene;
  84949. },
  84950. enumerable: true,
  84951. configurable: true
  84952. });
  84953. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  84954. /**
  84955. * Gets the ratio used by the buffer during its creation.
  84956. * How big is the buffer related to the main canvas.
  84957. */
  84958. get: function () {
  84959. return this._ratio;
  84960. },
  84961. enumerable: true,
  84962. configurable: true
  84963. });
  84964. /**
  84965. * Checks wether everything is ready to render a submesh to the G buffer.
  84966. * @param subMesh the submesh to check readiness for
  84967. * @param useInstances is the mesh drawn using instance or not
  84968. * @returns true if ready otherwise false
  84969. */
  84970. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  84971. var material = subMesh.getMaterial();
  84972. if (material && material.disableDepthWrite) {
  84973. return false;
  84974. }
  84975. var defines = [];
  84976. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  84977. var mesh = subMesh.getMesh();
  84978. // Alpha test
  84979. if (material && material.needAlphaTesting()) {
  84980. defines.push("#define ALPHATEST");
  84981. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84982. attribs.push(BABYLON.VertexBuffer.UVKind);
  84983. defines.push("#define UV1");
  84984. }
  84985. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  84986. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84987. defines.push("#define UV2");
  84988. }
  84989. }
  84990. // Buffers
  84991. if (this._enablePosition) {
  84992. defines.push("#define POSITION");
  84993. defines.push("#define POSITION_INDEX " + this._positionIndex);
  84994. }
  84995. if (this._enableVelocity) {
  84996. defines.push("#define VELOCITY");
  84997. defines.push("#define VELOCITY_INDEX " + this._velocityIndex);
  84998. }
  84999. // Bones
  85000. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85001. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85002. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85003. if (mesh.numBoneInfluencers > 4) {
  85004. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85005. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85006. }
  85007. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85008. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  85009. }
  85010. else {
  85011. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85012. }
  85013. // Instances
  85014. if (useInstances) {
  85015. defines.push("#define INSTANCES");
  85016. attribs.push("world0");
  85017. attribs.push("world1");
  85018. attribs.push("world2");
  85019. attribs.push("world3");
  85020. }
  85021. // Setup textures count
  85022. defines.push("#define RENDER_TARGET_COUNT " + this._multiRenderTarget.textures.length);
  85023. // Get correct effect
  85024. var join = defines.join("\n");
  85025. if (this._cachedDefines !== join) {
  85026. this._cachedDefines = join;
  85027. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view", "previousWorldViewProjection"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  85028. }
  85029. return this._effect.isReady();
  85030. };
  85031. /**
  85032. * Gets the current underlying G Buffer.
  85033. * @returns the buffer
  85034. */
  85035. GeometryBufferRenderer.prototype.getGBuffer = function () {
  85036. return this._multiRenderTarget;
  85037. };
  85038. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  85039. /**
  85040. * Gets the number of samples used to render the buffer (anti aliasing).
  85041. */
  85042. get: function () {
  85043. return this._multiRenderTarget.samples;
  85044. },
  85045. /**
  85046. * Sets the number of samples used to render the buffer (anti aliasing).
  85047. */
  85048. set: function (value) {
  85049. this._multiRenderTarget.samples = value;
  85050. },
  85051. enumerable: true,
  85052. configurable: true
  85053. });
  85054. /**
  85055. * Disposes the renderer and frees up associated resources.
  85056. */
  85057. GeometryBufferRenderer.prototype.dispose = function () {
  85058. this.getGBuffer().dispose();
  85059. };
  85060. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  85061. var _this = this;
  85062. var engine = this._scene.getEngine();
  85063. var count = 2;
  85064. if (this._enablePosition) {
  85065. this._positionIndex = count;
  85066. count++;
  85067. }
  85068. if (this._enableVelocity) {
  85069. this._velocityIndex = count;
  85070. count++;
  85071. }
  85072. 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 });
  85073. if (!this.isSupported) {
  85074. return;
  85075. }
  85076. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85077. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85078. this._multiRenderTarget.refreshRate = 1;
  85079. this._multiRenderTarget.renderParticles = false;
  85080. this._multiRenderTarget.renderList = null;
  85081. // set default depth value to 1.0 (far away)
  85082. this._multiRenderTarget.onClearObservable.add(function (engine) {
  85083. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  85084. });
  85085. // Custom render function
  85086. var renderSubMesh = function (subMesh) {
  85087. var mesh = subMesh.getRenderingMesh();
  85088. var scene = _this._scene;
  85089. var engine = scene.getEngine();
  85090. var material = subMesh.getMaterial();
  85091. if (!material) {
  85092. return;
  85093. }
  85094. // Velocity
  85095. if (!_this._previousTransformationMatrices[mesh.uniqueId]) {
  85096. _this._previousTransformationMatrices[mesh.uniqueId] = BABYLON.Matrix.Identity();
  85097. }
  85098. // Culling
  85099. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  85100. // Managing instances
  85101. var batch = mesh._getInstancesRenderList(subMesh._id);
  85102. if (batch.mustReturn) {
  85103. return;
  85104. }
  85105. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  85106. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  85107. engine.enableEffect(_this._effect);
  85108. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  85109. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  85110. _this._effect.setMatrix("view", scene.getViewMatrix());
  85111. // Alpha test
  85112. if (material && material.needAlphaTesting()) {
  85113. var alphaTexture = material.getAlphaTestTexture();
  85114. if (alphaTexture) {
  85115. _this._effect.setTexture("diffuseSampler", alphaTexture);
  85116. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  85117. }
  85118. }
  85119. // Bones
  85120. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85121. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85122. }
  85123. // Velocity
  85124. _this._effect.setMatrix("previousWorldViewProjection", _this._previousTransformationMatrices[mesh.uniqueId]);
  85125. // Draw
  85126. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  85127. }
  85128. // Velocity
  85129. _this._previousTransformationMatrices[mesh.uniqueId] = mesh.getWorldMatrix().multiply(_this._scene.getTransformMatrix());
  85130. };
  85131. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  85132. var index;
  85133. if (depthOnlySubMeshes.length) {
  85134. engine.setColorWrite(false);
  85135. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  85136. renderSubMesh(depthOnlySubMeshes.data[index]);
  85137. }
  85138. engine.setColorWrite(true);
  85139. }
  85140. for (index = 0; index < opaqueSubMeshes.length; index++) {
  85141. renderSubMesh(opaqueSubMeshes.data[index]);
  85142. }
  85143. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  85144. renderSubMesh(alphaTestSubMeshes.data[index]);
  85145. }
  85146. };
  85147. };
  85148. /**
  85149. * Constant used to retrieve the position texture index in the G-Buffer textures array
  85150. * using getIndex(GeometryBufferRenderer.POSITION_TEXTURE_INDEX)
  85151. */
  85152. GeometryBufferRenderer.POSITION_TEXTURE_TYPE = 1;
  85153. /**
  85154. * Constant used to retrieve the velocity texture index in the G-Buffer textures array
  85155. * using getIndex(GeometryBufferRenderer.VELOCITY_TEXTURE_INDEX)
  85156. */
  85157. GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE = 2;
  85158. return GeometryBufferRenderer;
  85159. }());
  85160. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  85161. })(BABYLON || (BABYLON = {}));
  85162. //# sourceMappingURL=geometryBufferRenderer.js.map
  85163. var BABYLON;
  85164. (function (BABYLON) {
  85165. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  85166. get: function () {
  85167. this._geometryBufferRenderer;
  85168. },
  85169. set: function (value) {
  85170. if (value && value.isSupported) {
  85171. this._geometryBufferRenderer = value;
  85172. }
  85173. },
  85174. enumerable: true,
  85175. configurable: true
  85176. });
  85177. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  85178. if (ratio === void 0) { ratio = 1; }
  85179. if (this._geometryBufferRenderer) {
  85180. return this._geometryBufferRenderer;
  85181. }
  85182. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  85183. if (!this._geometryBufferRenderer.isSupported) {
  85184. this._geometryBufferRenderer = null;
  85185. }
  85186. return this._geometryBufferRenderer;
  85187. };
  85188. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  85189. if (!this._geometryBufferRenderer) {
  85190. return;
  85191. }
  85192. this._geometryBufferRenderer.dispose();
  85193. this._geometryBufferRenderer = null;
  85194. };
  85195. /**
  85196. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  85197. * in several rendering techniques.
  85198. */
  85199. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  85200. /**
  85201. * Creates a new instance of the component for the given scene
  85202. * @param scene Defines the scene to register the component in
  85203. */
  85204. function GeometryBufferRendererSceneComponent(scene) {
  85205. /**
  85206. * The component name helpful to identify the component in the list of scene components.
  85207. */
  85208. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  85209. this.scene = scene;
  85210. }
  85211. /**
  85212. * Registers the component in a given scene
  85213. */
  85214. GeometryBufferRendererSceneComponent.prototype.register = function () {
  85215. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  85216. };
  85217. /**
  85218. * Rebuilds the elements related to this component in case of
  85219. * context lost for instance.
  85220. */
  85221. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  85222. // Nothing to do for this component
  85223. };
  85224. /**
  85225. * Disposes the component and the associated ressources
  85226. */
  85227. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  85228. // Nothing to do for this component
  85229. };
  85230. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  85231. if (this.scene._geometryBufferRenderer) {
  85232. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  85233. }
  85234. };
  85235. return GeometryBufferRendererSceneComponent;
  85236. }());
  85237. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  85238. })(BABYLON || (BABYLON = {}));
  85239. //# sourceMappingURL=geometryBufferRendererSceneComponent.js.map
  85240. var BABYLON;
  85241. (function (BABYLON) {
  85242. /**
  85243. * Render pipeline to produce ssao effect
  85244. */
  85245. var SSAORenderingPipeline = /** @class */ (function (_super) {
  85246. __extends(SSAORenderingPipeline, _super);
  85247. /**
  85248. * @constructor
  85249. * @param name - The rendering pipeline name
  85250. * @param scene - The scene linked to this pipeline
  85251. * @param ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  85252. * @param cameras - The array of cameras that the rendering pipeline will be attached to
  85253. */
  85254. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  85255. var _this = _super.call(this, scene.getEngine(), name) || this;
  85256. // Members
  85257. /**
  85258. * @ignore
  85259. * The PassPostProcess id in the pipeline that contains the original scene color
  85260. */
  85261. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  85262. /**
  85263. * @ignore
  85264. * The SSAO PostProcess id in the pipeline
  85265. */
  85266. _this.SSAORenderEffect = "SSAORenderEffect";
  85267. /**
  85268. * @ignore
  85269. * The horizontal blur PostProcess id in the pipeline
  85270. */
  85271. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  85272. /**
  85273. * @ignore
  85274. * The vertical blur PostProcess id in the pipeline
  85275. */
  85276. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  85277. /**
  85278. * @ignore
  85279. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  85280. */
  85281. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  85282. /**
  85283. * The output strength of the SSAO post-process. Default value is 1.0.
  85284. */
  85285. _this.totalStrength = 1.0;
  85286. /**
  85287. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  85288. */
  85289. _this.radius = 0.0001;
  85290. /**
  85291. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  85292. * Must not be equal to fallOff and superior to fallOff.
  85293. * Default value is 0.975
  85294. */
  85295. _this.area = 0.0075;
  85296. /**
  85297. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  85298. * Must not be equal to area and inferior to area.
  85299. * Default value is 0.0
  85300. */
  85301. _this.fallOff = 0.000001;
  85302. /**
  85303. * The base color of the SSAO post-process
  85304. * The final result is "base + ssao" between [0, 1]
  85305. */
  85306. _this.base = 0.5;
  85307. _this._firstUpdate = true;
  85308. _this._scene = scene;
  85309. // Set up assets
  85310. _this._createRandomTexture();
  85311. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  85312. var ssaoRatio = ratio.ssaoRatio || ratio;
  85313. var combineRatio = ratio.combineRatio || ratio;
  85314. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  85315. _this._createSSAOPostProcess(ssaoRatio);
  85316. _this._createBlurPostProcess(ssaoRatio);
  85317. _this._createSSAOCombinePostProcess(combineRatio);
  85318. // Set up pipeline
  85319. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  85320. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  85321. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  85322. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  85323. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  85324. // Finish
  85325. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85326. if (cameras) {
  85327. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  85328. }
  85329. return _this;
  85330. }
  85331. // Public Methods
  85332. /**
  85333. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  85334. */
  85335. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  85336. if (disableDepthRender === void 0) { disableDepthRender = false; }
  85337. for (var i = 0; i < this._scene.cameras.length; i++) {
  85338. var camera = this._scene.cameras[i];
  85339. this._originalColorPostProcess.dispose(camera);
  85340. this._ssaoPostProcess.dispose(camera);
  85341. this._blurHPostProcess.dispose(camera);
  85342. this._blurVPostProcess.dispose(camera);
  85343. this._ssaoCombinePostProcess.dispose(camera);
  85344. }
  85345. this._randomTexture.dispose();
  85346. if (disableDepthRender) {
  85347. this._scene.disableDepthRenderer();
  85348. }
  85349. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  85350. _super.prototype.dispose.call(this);
  85351. };
  85352. // Private Methods
  85353. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  85354. var _this = this;
  85355. var size = 16;
  85356. 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);
  85357. 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);
  85358. this._blurHPostProcess.onActivateObservable.add(function () {
  85359. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  85360. _this._blurHPostProcess.kernel = size * dw;
  85361. });
  85362. this._blurVPostProcess.onActivateObservable.add(function () {
  85363. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  85364. _this._blurVPostProcess.kernel = size * dw;
  85365. });
  85366. };
  85367. /** @hidden */
  85368. SSAORenderingPipeline.prototype._rebuild = function () {
  85369. this._firstUpdate = true;
  85370. _super.prototype._rebuild.call(this);
  85371. };
  85372. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  85373. var _this = this;
  85374. var numSamples = 16;
  85375. var sampleSphere = [
  85376. 0.5381, 0.1856, -0.4319,
  85377. 0.1379, 0.2486, 0.4430,
  85378. 0.3371, 0.5679, -0.0057,
  85379. -0.6999, -0.0451, -0.0019,
  85380. 0.0689, -0.1598, -0.8547,
  85381. 0.0560, 0.0069, -0.1843,
  85382. -0.0146, 0.1402, 0.0762,
  85383. 0.0100, -0.1924, -0.0344,
  85384. -0.3577, -0.5301, -0.4358,
  85385. -0.3169, 0.1063, 0.0158,
  85386. 0.0103, -0.5869, 0.0046,
  85387. -0.0897, -0.4940, 0.3287,
  85388. 0.7119, -0.0154, -0.0918,
  85389. -0.0533, 0.0596, -0.5411,
  85390. 0.0352, -0.0631, 0.5460,
  85391. -0.4776, 0.2847, -0.0271
  85392. ];
  85393. var samplesFactor = 1.0 / numSamples;
  85394. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  85395. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  85396. "area", "fallOff", "base", "range", "viewport"
  85397. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  85398. this._ssaoPostProcess.onApply = function (effect) {
  85399. if (_this._firstUpdate) {
  85400. effect.setArray3("sampleSphere", sampleSphere);
  85401. effect.setFloat("samplesFactor", samplesFactor);
  85402. effect.setFloat("randTextureTiles", 4.0);
  85403. }
  85404. effect.setFloat("totalStrength", _this.totalStrength);
  85405. effect.setFloat("radius", _this.radius);
  85406. effect.setFloat("area", _this.area);
  85407. effect.setFloat("fallOff", _this.fallOff);
  85408. effect.setFloat("base", _this.base);
  85409. effect.setTexture("textureSampler", _this._depthTexture);
  85410. effect.setTexture("randomSampler", _this._randomTexture);
  85411. };
  85412. };
  85413. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  85414. var _this = this;
  85415. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  85416. this._ssaoCombinePostProcess.onApply = function (effect) {
  85417. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  85418. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  85419. };
  85420. };
  85421. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  85422. var size = 512;
  85423. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85424. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  85425. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  85426. var context = this._randomTexture.getContext();
  85427. var rand = function (min, max) {
  85428. return Math.random() * (max - min) + min;
  85429. };
  85430. var randVector = BABYLON.Vector3.Zero();
  85431. for (var x = 0; x < size; x++) {
  85432. for (var y = 0; y < size; y++) {
  85433. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  85434. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  85435. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  85436. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  85437. context.fillRect(x, y, 1, 1);
  85438. }
  85439. }
  85440. this._randomTexture.update(false);
  85441. };
  85442. __decorate([
  85443. BABYLON.serialize()
  85444. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  85445. __decorate([
  85446. BABYLON.serialize()
  85447. ], SSAORenderingPipeline.prototype, "radius", void 0);
  85448. __decorate([
  85449. BABYLON.serialize()
  85450. ], SSAORenderingPipeline.prototype, "area", void 0);
  85451. __decorate([
  85452. BABYLON.serialize()
  85453. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  85454. __decorate([
  85455. BABYLON.serialize()
  85456. ], SSAORenderingPipeline.prototype, "base", void 0);
  85457. return SSAORenderingPipeline;
  85458. }(BABYLON.PostProcessRenderPipeline));
  85459. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  85460. })(BABYLON || (BABYLON = {}));
  85461. //# sourceMappingURL=ssaoRenderingPipeline.js.map
  85462. var BABYLON;
  85463. (function (BABYLON) {
  85464. /**
  85465. * Render pipeline to produce ssao effect
  85466. */
  85467. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  85468. __extends(SSAO2RenderingPipeline, _super);
  85469. /**
  85470. * @constructor
  85471. * @param name The rendering pipeline name
  85472. * @param scene The scene linked to this pipeline
  85473. * @param ratio The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 }
  85474. * @param cameras The array of cameras that the rendering pipeline will be attached to
  85475. */
  85476. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  85477. var _this = _super.call(this, scene.getEngine(), name) || this;
  85478. // Members
  85479. /**
  85480. * @ignore
  85481. * The PassPostProcess id in the pipeline that contains the original scene color
  85482. */
  85483. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  85484. /**
  85485. * @ignore
  85486. * The SSAO PostProcess id in the pipeline
  85487. */
  85488. _this.SSAORenderEffect = "SSAORenderEffect";
  85489. /**
  85490. * @ignore
  85491. * The horizontal blur PostProcess id in the pipeline
  85492. */
  85493. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  85494. /**
  85495. * @ignore
  85496. * The vertical blur PostProcess id in the pipeline
  85497. */
  85498. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  85499. /**
  85500. * @ignore
  85501. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  85502. */
  85503. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  85504. /**
  85505. * The output strength of the SSAO post-process. Default value is 1.0.
  85506. */
  85507. _this.totalStrength = 1.0;
  85508. /**
  85509. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  85510. */
  85511. _this.maxZ = 100.0;
  85512. /**
  85513. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  85514. */
  85515. _this.minZAspect = 0.2;
  85516. _this._samples = 8;
  85517. _this._textureSamples = 1;
  85518. _this._expensiveBlur = true;
  85519. /**
  85520. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  85521. */
  85522. _this.radius = 2.0;
  85523. /**
  85524. * The base color of the SSAO post-process
  85525. * The final result is "base + ssao" between [0, 1]
  85526. */
  85527. _this.base = 0;
  85528. _this._firstUpdate = true;
  85529. _this._bits = new Uint32Array(1);
  85530. _this._scene = scene;
  85531. _this._ratio = ratio;
  85532. if (!_this.isSupported) {
  85533. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  85534. return _this;
  85535. }
  85536. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  85537. var blurRatio = _this._ratio.blurRatio || ratio;
  85538. // Set up assets
  85539. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  85540. _this._createRandomTexture();
  85541. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  85542. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  85543. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  85544. _this._originalColorPostProcess.samples = _this.textureSamples;
  85545. _this._createSSAOPostProcess(1.0);
  85546. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  85547. _this._createSSAOCombinePostProcess(blurRatio);
  85548. // Set up pipeline
  85549. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  85550. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  85551. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  85552. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  85553. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  85554. // Finish
  85555. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85556. if (cameras) {
  85557. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  85558. }
  85559. return _this;
  85560. }
  85561. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  85562. get: function () {
  85563. return this._samples;
  85564. },
  85565. /**
  85566. * Number of samples used for the SSAO calculations. Default value is 8
  85567. */
  85568. set: function (n) {
  85569. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  85570. this._samples = n;
  85571. this._sampleSphere = this._generateHemisphere();
  85572. this._firstUpdate = true;
  85573. },
  85574. enumerable: true,
  85575. configurable: true
  85576. });
  85577. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  85578. get: function () {
  85579. return this._textureSamples;
  85580. },
  85581. /**
  85582. * Number of samples to use for antialiasing
  85583. */
  85584. set: function (n) {
  85585. this._textureSamples = n;
  85586. this._originalColorPostProcess.samples = n;
  85587. this._blurHPostProcess.samples = n;
  85588. this._blurVPostProcess.samples = n;
  85589. this._ssaoPostProcess.samples = n;
  85590. this._ssaoCombinePostProcess.samples = n;
  85591. },
  85592. enumerable: true,
  85593. configurable: true
  85594. });
  85595. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  85596. get: function () {
  85597. return this._expensiveBlur;
  85598. },
  85599. /**
  85600. * If bilateral blur should be used
  85601. */
  85602. set: function (b) {
  85603. 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"]);
  85604. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  85605. this._expensiveBlur = b;
  85606. this._firstUpdate = true;
  85607. },
  85608. enumerable: true,
  85609. configurable: true
  85610. });
  85611. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  85612. /**
  85613. * Support test.
  85614. */
  85615. get: function () {
  85616. var engine = BABYLON.Engine.LastCreatedEngine;
  85617. if (!engine) {
  85618. return false;
  85619. }
  85620. return engine.getCaps().drawBuffersExtension;
  85621. },
  85622. enumerable: true,
  85623. configurable: true
  85624. });
  85625. // Public Methods
  85626. /**
  85627. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  85628. */
  85629. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  85630. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  85631. for (var i = 0; i < this._scene.cameras.length; i++) {
  85632. var camera = this._scene.cameras[i];
  85633. this._originalColorPostProcess.dispose(camera);
  85634. this._ssaoPostProcess.dispose(camera);
  85635. this._blurHPostProcess.dispose(camera);
  85636. this._blurVPostProcess.dispose(camera);
  85637. this._ssaoCombinePostProcess.dispose(camera);
  85638. }
  85639. this._randomTexture.dispose();
  85640. if (disableGeometryBufferRenderer) {
  85641. this._scene.disableGeometryBufferRenderer();
  85642. }
  85643. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  85644. _super.prototype.dispose.call(this);
  85645. };
  85646. // Private Methods
  85647. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  85648. var _this = this;
  85649. this._samplerOffsets = [];
  85650. var expensive = this.expensiveBlur;
  85651. for (var i = -8; i < 8; i++) {
  85652. this._samplerOffsets.push(i * 2 + 0.5);
  85653. }
  85654. 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");
  85655. this._blurHPostProcess.onApply = function (effect) {
  85656. if (!_this._scene.activeCamera) {
  85657. return;
  85658. }
  85659. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  85660. effect.setFloat("near", _this._scene.activeCamera.minZ);
  85661. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  85662. effect.setFloat("radius", _this.radius);
  85663. effect.setTexture("depthSampler", _this._depthTexture);
  85664. if (_this._firstUpdate) {
  85665. effect.setArray("samplerOffsets", _this._samplerOffsets);
  85666. }
  85667. };
  85668. 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");
  85669. this._blurVPostProcess.onApply = function (effect) {
  85670. if (!_this._scene.activeCamera) {
  85671. return;
  85672. }
  85673. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  85674. effect.setFloat("near", _this._scene.activeCamera.minZ);
  85675. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  85676. effect.setFloat("radius", _this.radius);
  85677. effect.setTexture("depthSampler", _this._depthTexture);
  85678. if (_this._firstUpdate) {
  85679. effect.setArray("samplerOffsets", _this._samplerOffsets);
  85680. _this._firstUpdate = false;
  85681. }
  85682. };
  85683. this._blurHPostProcess.samples = this.textureSamples;
  85684. this._blurVPostProcess.samples = this.textureSamples;
  85685. };
  85686. /** @hidden */
  85687. SSAO2RenderingPipeline.prototype._rebuild = function () {
  85688. this._firstUpdate = true;
  85689. _super.prototype._rebuild.call(this);
  85690. };
  85691. //Van der Corput radical inverse
  85692. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  85693. this._bits[0] = i;
  85694. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  85695. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  85696. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  85697. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  85698. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  85699. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  85700. };
  85701. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  85702. return [i / n, this._radicalInverse_VdC(i)];
  85703. };
  85704. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  85705. var phi = v * 2.0 * Math.PI;
  85706. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  85707. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  85708. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  85709. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  85710. };
  85711. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  85712. var numSamples = this.samples;
  85713. var result = [];
  85714. var vector;
  85715. var i = 0;
  85716. while (i < numSamples) {
  85717. if (numSamples < 16) {
  85718. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  85719. }
  85720. else {
  85721. var rand = this._hammersley(i, numSamples);
  85722. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  85723. }
  85724. result.push(vector.x, vector.y, vector.z);
  85725. i++;
  85726. }
  85727. return result;
  85728. };
  85729. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  85730. var _this = this;
  85731. var numSamples = this.samples;
  85732. this._sampleSphere = this._generateHemisphere();
  85733. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  85734. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  85735. "base", "range", "projection", "near", "far", "texelSize",
  85736. "xViewport", "yViewport", "maxZ", "minZAspect"
  85737. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  85738. this._ssaoPostProcess.onApply = function (effect) {
  85739. if (_this._firstUpdate) {
  85740. effect.setArray3("sampleSphere", _this._sampleSphere);
  85741. effect.setFloat("randTextureTiles", 32.0);
  85742. }
  85743. if (!_this._scene.activeCamera) {
  85744. return;
  85745. }
  85746. effect.setFloat("samplesFactor", 1 / _this.samples);
  85747. effect.setFloat("totalStrength", _this.totalStrength);
  85748. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  85749. effect.setFloat("radius", _this.radius);
  85750. effect.setFloat("maxZ", _this.maxZ);
  85751. effect.setFloat("minZAspect", _this.minZAspect);
  85752. effect.setFloat("base", _this.base);
  85753. effect.setFloat("near", _this._scene.activeCamera.minZ);
  85754. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  85755. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  85756. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  85757. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  85758. effect.setTexture("textureSampler", _this._depthTexture);
  85759. effect.setTexture("normalSampler", _this._normalTexture);
  85760. effect.setTexture("randomSampler", _this._randomTexture);
  85761. };
  85762. this._ssaoPostProcess.samples = this.textureSamples;
  85763. };
  85764. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  85765. var _this = this;
  85766. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  85767. this._ssaoCombinePostProcess.onApply = function (effect) {
  85768. var viewport = _this._scene.activeCamera.viewport;
  85769. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  85770. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  85771. };
  85772. this._ssaoCombinePostProcess.samples = this.textureSamples;
  85773. };
  85774. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  85775. var size = 128;
  85776. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85777. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  85778. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  85779. var context = this._randomTexture.getContext();
  85780. var rand = function (min, max) {
  85781. return Math.random() * (max - min) + min;
  85782. };
  85783. var randVector = BABYLON.Vector3.Zero();
  85784. for (var x = 0; x < size; x++) {
  85785. for (var y = 0; y < size; y++) {
  85786. randVector.x = rand(0.0, 1.0);
  85787. randVector.y = rand(0.0, 1.0);
  85788. randVector.z = 0.0;
  85789. randVector.normalize();
  85790. randVector.scaleInPlace(255);
  85791. randVector.x = Math.floor(randVector.x);
  85792. randVector.y = Math.floor(randVector.y);
  85793. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  85794. context.fillRect(x, y, 1, 1);
  85795. }
  85796. }
  85797. this._randomTexture.update(false);
  85798. };
  85799. /**
  85800. * Serialize the rendering pipeline (Used when exporting)
  85801. * @returns the serialized object
  85802. */
  85803. SSAO2RenderingPipeline.prototype.serialize = function () {
  85804. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  85805. serializationObject.customType = "SSAO2RenderingPipeline";
  85806. return serializationObject;
  85807. };
  85808. /**
  85809. * Parse the serialized pipeline
  85810. * @param source Source pipeline.
  85811. * @param scene The scene to load the pipeline to.
  85812. * @param rootUrl The URL of the serialized pipeline.
  85813. * @returns An instantiated pipeline from the serialized object.
  85814. */
  85815. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  85816. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  85817. };
  85818. __decorate([
  85819. BABYLON.serialize()
  85820. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  85821. __decorate([
  85822. BABYLON.serialize()
  85823. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  85824. __decorate([
  85825. BABYLON.serialize()
  85826. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  85827. __decorate([
  85828. BABYLON.serialize("samples")
  85829. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  85830. __decorate([
  85831. BABYLON.serialize("textureSamples")
  85832. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  85833. __decorate([
  85834. BABYLON.serialize()
  85835. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  85836. __decorate([
  85837. BABYLON.serialize("expensiveBlur")
  85838. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  85839. __decorate([
  85840. BABYLON.serialize()
  85841. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  85842. __decorate([
  85843. BABYLON.serialize()
  85844. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  85845. return SSAO2RenderingPipeline;
  85846. }(BABYLON.PostProcessRenderPipeline));
  85847. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  85848. })(BABYLON || (BABYLON = {}));
  85849. //# sourceMappingURL=ssao2RenderingPipeline.js.map
  85850. var BABYLON;
  85851. (function (BABYLON) {
  85852. /**
  85853. * BABYLON.JS Chromatic Aberration GLSL Shader
  85854. * Author: Olivier Guyot
  85855. * Separates very slightly R, G and B colors on the edges of the screen
  85856. * Inspired by Francois Tarlier & Martins Upitis
  85857. */
  85858. var LensRenderingPipeline = /** @class */ (function (_super) {
  85859. __extends(LensRenderingPipeline, _super);
  85860. /**
  85861. * @constructor
  85862. *
  85863. * Effect parameters are as follow:
  85864. * {
  85865. * chromatic_aberration: number; // from 0 to x (1 for realism)
  85866. * edge_blur: number; // from 0 to x (1 for realism)
  85867. * distortion: number; // from 0 to x (1 for realism)
  85868. * grain_amount: number; // from 0 to 1
  85869. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  85870. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  85871. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  85872. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  85873. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  85874. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  85875. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  85876. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  85877. * }
  85878. * Note: if an effect parameter is unset, effect is disabled
  85879. *
  85880. * @param name The rendering pipeline name
  85881. * @param parameters - An object containing all parameters (see above)
  85882. * @param scene The scene linked to this pipeline
  85883. * @param ratio The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  85884. * @param cameras The array of cameras that the rendering pipeline will be attached to
  85885. */
  85886. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  85887. if (ratio === void 0) { ratio = 1.0; }
  85888. var _this = _super.call(this, scene.getEngine(), name) || this;
  85889. // Lens effects can be of the following:
  85890. // - chromatic aberration (slight shift of RGB colors)
  85891. // - blur on the edge of the lens
  85892. // - lens distortion
  85893. // - depth-of-field blur & highlights enhancing
  85894. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  85895. // - grain effect (noise or custom texture)
  85896. // Two additional texture samplers are needed:
  85897. // - depth map (for depth-of-field)
  85898. // - grain texture
  85899. /**
  85900. * @ignore
  85901. * The chromatic aberration PostProcess id in the pipeline
  85902. */
  85903. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  85904. /**
  85905. * @ignore
  85906. * The highlights enhancing PostProcess id in the pipeline
  85907. */
  85908. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  85909. /**
  85910. * @ignore
  85911. * The depth-of-field PostProcess id in the pipeline
  85912. */
  85913. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  85914. _this._scene = scene;
  85915. // Fetch texture samplers
  85916. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  85917. if (parameters.grain_texture) {
  85918. _this._grainTexture = parameters.grain_texture;
  85919. }
  85920. else {
  85921. _this._createGrainTexture();
  85922. }
  85923. // save parameters
  85924. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  85925. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  85926. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  85927. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  85928. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  85929. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  85930. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  85931. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  85932. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  85933. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  85934. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  85935. // Create effects
  85936. _this._createChromaticAberrationPostProcess(ratio);
  85937. _this._createHighlightsPostProcess(ratio);
  85938. _this._createDepthOfFieldPostProcess(ratio / 4);
  85939. // Set up pipeline
  85940. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  85941. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  85942. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  85943. if (_this._highlightsGain === -1) {
  85944. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  85945. }
  85946. // Finish
  85947. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85948. if (cameras) {
  85949. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  85950. }
  85951. return _this;
  85952. }
  85953. // public methods (self explanatory)
  85954. /**
  85955. * Sets the amount of blur at the edges
  85956. * @param amount blur amount
  85957. */
  85958. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  85959. /**
  85960. * Sets edge blur to 0
  85961. */
  85962. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  85963. /**
  85964. * Sets the amout of grain
  85965. * @param amount Amount of grain
  85966. */
  85967. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  85968. /**
  85969. * Set grain amount to 0
  85970. */
  85971. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  85972. /**
  85973. * Sets the chromatic aberration amount
  85974. * @param amount amount of chromatic aberration
  85975. */
  85976. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  85977. /**
  85978. * Sets chromatic aberration amount to 0
  85979. */
  85980. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  85981. /**
  85982. * Sets the EdgeDistortion amount
  85983. * @param amount amount of EdgeDistortion
  85984. */
  85985. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  85986. /**
  85987. * Sets edge distortion to 0
  85988. */
  85989. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  85990. /**
  85991. * Sets the FocusDistance amount
  85992. * @param amount amount of FocusDistance
  85993. */
  85994. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  85995. /**
  85996. * Disables depth of field
  85997. */
  85998. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  85999. /**
  86000. * Sets the Aperture amount
  86001. * @param amount amount of Aperture
  86002. */
  86003. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  86004. /**
  86005. * Sets the DarkenOutOfFocus amount
  86006. * @param amount amount of DarkenOutOfFocus
  86007. */
  86008. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  86009. /**
  86010. * Creates a pentagon bokeh effect
  86011. */
  86012. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  86013. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  86014. };
  86015. /**
  86016. * Disables the pentagon bokeh effect
  86017. */
  86018. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  86019. this._highlightsPostProcess.updateEffect();
  86020. };
  86021. /**
  86022. * Enables noise blur
  86023. */
  86024. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  86025. /**
  86026. * Disables noise blur
  86027. */
  86028. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  86029. /**
  86030. * Sets the HighlightsGain amount
  86031. * @param amount amount of HighlightsGain
  86032. */
  86033. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  86034. this._highlightsGain = amount;
  86035. };
  86036. /**
  86037. * Sets the HighlightsThreshold amount
  86038. * @param amount amount of HighlightsThreshold
  86039. */
  86040. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  86041. if (this._highlightsGain === -1) {
  86042. this._highlightsGain = 1.0;
  86043. }
  86044. this._highlightsThreshold = amount;
  86045. };
  86046. /**
  86047. * Disables highlights
  86048. */
  86049. LensRenderingPipeline.prototype.disableHighlights = function () {
  86050. this._highlightsGain = -1;
  86051. };
  86052. /**
  86053. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  86054. * @param disableDepthRender If the scens depth rendering should be disabled (default: false)
  86055. */
  86056. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  86057. if (disableDepthRender === void 0) { disableDepthRender = false; }
  86058. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  86059. this._chromaticAberrationPostProcess = null;
  86060. this._highlightsPostProcess = null;
  86061. this._depthOfFieldPostProcess = null;
  86062. this._grainTexture.dispose();
  86063. if (disableDepthRender) {
  86064. this._scene.disableDepthRenderer();
  86065. }
  86066. };
  86067. // colors shifting and distortion
  86068. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  86069. var _this = this;
  86070. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  86071. [], // samplers
  86072. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  86073. this._chromaticAberrationPostProcess.onApply = function (effect) {
  86074. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  86075. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  86076. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  86077. effect.setFloat('radialIntensity', 1);
  86078. effect.setFloat2('direction', 17, 17);
  86079. effect.setFloat2('centerPosition', 0.5, 0.5);
  86080. };
  86081. };
  86082. // highlights enhancing
  86083. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  86084. var _this = this;
  86085. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  86086. [], // samplers
  86087. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  86088. this._highlightsPostProcess.onApply = function (effect) {
  86089. effect.setFloat('gain', _this._highlightsGain);
  86090. effect.setFloat('threshold', _this._highlightsThreshold);
  86091. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  86092. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  86093. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  86094. };
  86095. };
  86096. // colors shifting and distortion
  86097. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  86098. var _this = this;
  86099. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  86100. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  86101. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  86102. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  86103. this._depthOfFieldPostProcess.onApply = function (effect) {
  86104. effect.setTexture("depthSampler", _this._depthTexture);
  86105. effect.setTexture("grainSampler", _this._grainTexture);
  86106. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  86107. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  86108. effect.setFloat('grain_amount', _this._grainAmount);
  86109. effect.setBool('blur_noise', _this._blurNoise);
  86110. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  86111. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  86112. effect.setFloat('distortion', _this._distortion);
  86113. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  86114. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  86115. effect.setFloat('aperture', _this._dofAperture);
  86116. effect.setFloat('darken', _this._dofDarken);
  86117. effect.setFloat('edge_blur', _this._edgeBlur);
  86118. effect.setBool('highlights', (_this._highlightsGain !== -1));
  86119. if (_this._scene.activeCamera) {
  86120. effect.setFloat('near', _this._scene.activeCamera.minZ);
  86121. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  86122. }
  86123. };
  86124. };
  86125. // creates a black and white random noise texture, 512x512
  86126. LensRenderingPipeline.prototype._createGrainTexture = function () {
  86127. var size = 512;
  86128. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86129. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  86130. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  86131. var context = this._grainTexture.getContext();
  86132. var rand = function (min, max) {
  86133. return Math.random() * (max - min) + min;
  86134. };
  86135. var value;
  86136. for (var x = 0; x < size; x++) {
  86137. for (var y = 0; y < size; y++) {
  86138. value = Math.floor(rand(0.42, 0.58) * 255);
  86139. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  86140. context.fillRect(x, y, 1, 1);
  86141. }
  86142. }
  86143. this._grainTexture.update(false);
  86144. };
  86145. return LensRenderingPipeline;
  86146. }(BABYLON.PostProcessRenderPipeline));
  86147. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  86148. })(BABYLON || (BABYLON = {}));
  86149. //# sourceMappingURL=lensRenderingPipeline.js.map
  86150. var BABYLON;
  86151. (function (BABYLON) {
  86152. /**
  86153. * Standard rendering pipeline
  86154. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  86155. * @see https://doc.babylonjs.com/how_to/using_standard_rendering_pipeline
  86156. */
  86157. var StandardRenderingPipeline = /** @class */ (function (_super) {
  86158. __extends(StandardRenderingPipeline, _super);
  86159. /**
  86160. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  86161. * @constructor
  86162. * @param name The rendering pipeline name
  86163. * @param scene The scene linked to this pipeline
  86164. * @param ratio The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  86165. * @param originalPostProcess the custom original color post-process. Must be "reusable". Can be null.
  86166. * @param cameras The array of cameras that the rendering pipeline will be attached to
  86167. */
  86168. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  86169. if (originalPostProcess === void 0) { originalPostProcess = null; }
  86170. var _this = _super.call(this, scene.getEngine(), name) || this;
  86171. /**
  86172. * Post-process used to down scale an image x4
  86173. */
  86174. _this.downSampleX4PostProcess = null;
  86175. /**
  86176. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  86177. */
  86178. _this.brightPassPostProcess = null;
  86179. /**
  86180. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  86181. */
  86182. _this.blurHPostProcesses = [];
  86183. /**
  86184. * Post-process array storing all the vertical blur post-processes used by the pipeline
  86185. */
  86186. _this.blurVPostProcesses = [];
  86187. /**
  86188. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  86189. */
  86190. _this.textureAdderPostProcess = null;
  86191. /**
  86192. * Post-process used to create volumetric lighting effect
  86193. */
  86194. _this.volumetricLightPostProcess = null;
  86195. /**
  86196. * Post-process used to smooth the previous volumetric light post-process on the X axis
  86197. */
  86198. _this.volumetricLightSmoothXPostProcess = null;
  86199. /**
  86200. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  86201. */
  86202. _this.volumetricLightSmoothYPostProcess = null;
  86203. /**
  86204. * Post-process used to merge the volumetric light effect and the real scene color
  86205. */
  86206. _this.volumetricLightMergePostProces = null;
  86207. /**
  86208. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  86209. */
  86210. _this.volumetricLightFinalPostProcess = null;
  86211. /**
  86212. * Base post-process used to calculate the average luminance of the final image for HDR
  86213. */
  86214. _this.luminancePostProcess = null;
  86215. /**
  86216. * Post-processes used to create down sample post-processes in order to get
  86217. * the average luminance of the final image for HDR
  86218. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  86219. */
  86220. _this.luminanceDownSamplePostProcesses = [];
  86221. /**
  86222. * Post-process used to create a HDR effect (light adaptation)
  86223. */
  86224. _this.hdrPostProcess = null;
  86225. /**
  86226. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  86227. */
  86228. _this.textureAdderFinalPostProcess = null;
  86229. /**
  86230. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  86231. */
  86232. _this.lensFlareFinalPostProcess = null;
  86233. /**
  86234. * Post-process used to merge the final HDR post-process and the real scene color
  86235. */
  86236. _this.hdrFinalPostProcess = null;
  86237. /**
  86238. * Post-process used to create a lens flare effect
  86239. */
  86240. _this.lensFlarePostProcess = null;
  86241. /**
  86242. * Post-process that merges the result of the lens flare post-process and the real scene color
  86243. */
  86244. _this.lensFlareComposePostProcess = null;
  86245. /**
  86246. * Post-process used to create a motion blur effect
  86247. */
  86248. _this.motionBlurPostProcess = null;
  86249. /**
  86250. * Post-process used to create a depth of field effect
  86251. */
  86252. _this.depthOfFieldPostProcess = null;
  86253. /**
  86254. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  86255. */
  86256. _this.fxaaPostProcess = null;
  86257. // Values
  86258. /**
  86259. * Represents the brightness threshold in order to configure the illuminated surfaces
  86260. */
  86261. _this.brightThreshold = 1.0;
  86262. /**
  86263. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  86264. */
  86265. _this.blurWidth = 512.0;
  86266. /**
  86267. * Sets if the blur for highlighted surfaces must be only horizontal
  86268. */
  86269. _this.horizontalBlur = false;
  86270. /**
  86271. * Sets the overall exposure used by the pipeline
  86272. */
  86273. _this.exposure = 1.0;
  86274. /**
  86275. * Texture used typically to simulate "dirty" on camera lens
  86276. */
  86277. _this.lensTexture = null;
  86278. /**
  86279. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  86280. */
  86281. _this.volumetricLightCoefficient = 0.2;
  86282. /**
  86283. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  86284. */
  86285. _this.volumetricLightPower = 4.0;
  86286. /**
  86287. * Used the set the blur intensity to smooth the volumetric lights
  86288. */
  86289. _this.volumetricLightBlurScale = 64.0;
  86290. /**
  86291. * Light (spot or directional) used to generate the volumetric lights rays
  86292. * The source light must have a shadow generate so the pipeline can get its
  86293. * depth map
  86294. */
  86295. _this.sourceLight = null;
  86296. /**
  86297. * For eye adaptation, represents the minimum luminance the eye can see
  86298. */
  86299. _this.hdrMinimumLuminance = 1.0;
  86300. /**
  86301. * For eye adaptation, represents the decrease luminance speed
  86302. */
  86303. _this.hdrDecreaseRate = 0.5;
  86304. /**
  86305. * For eye adaptation, represents the increase luminance speed
  86306. */
  86307. _this.hdrIncreaseRate = 0.5;
  86308. /**
  86309. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  86310. */
  86311. _this.lensColorTexture = null;
  86312. /**
  86313. * The overall strengh for the lens flare effect
  86314. */
  86315. _this.lensFlareStrength = 20.0;
  86316. /**
  86317. * Dispersion coefficient for lens flare ghosts
  86318. */
  86319. _this.lensFlareGhostDispersal = 1.4;
  86320. /**
  86321. * Main lens flare halo width
  86322. */
  86323. _this.lensFlareHaloWidth = 0.7;
  86324. /**
  86325. * Based on the lens distortion effect, defines how much the lens flare result
  86326. * is distorted
  86327. */
  86328. _this.lensFlareDistortionStrength = 16.0;
  86329. /**
  86330. * Lens star texture must be used to simulate rays on the flares and is available
  86331. * in the documentation
  86332. */
  86333. _this.lensStarTexture = null;
  86334. /**
  86335. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  86336. * flare effect by taking account of the dirt texture
  86337. */
  86338. _this.lensFlareDirtTexture = null;
  86339. /**
  86340. * Represents the focal length for the depth of field effect
  86341. */
  86342. _this.depthOfFieldDistance = 10.0;
  86343. /**
  86344. * Represents the blur intensity for the blurred part of the depth of field effect
  86345. */
  86346. _this.depthOfFieldBlurWidth = 64.0;
  86347. /**
  86348. * For motion blur, defines how much the image is blurred by the movement
  86349. */
  86350. _this.motionStrength = 1.0;
  86351. /**
  86352. * List of animations for the pipeline (IAnimatable implementation)
  86353. */
  86354. _this.animations = [];
  86355. _this._currentDepthOfFieldSource = null;
  86356. _this._hdrCurrentLuminance = 1.0;
  86357. // Getters and setters
  86358. _this._bloomEnabled = false;
  86359. _this._depthOfFieldEnabled = false;
  86360. _this._vlsEnabled = false;
  86361. _this._lensFlareEnabled = false;
  86362. _this._hdrEnabled = false;
  86363. _this._motionBlurEnabled = false;
  86364. _this._fxaaEnabled = false;
  86365. _this._motionBlurSamples = 64.0;
  86366. _this._volumetricLightStepsCount = 50.0;
  86367. _this._samples = 1;
  86368. _this._cameras = cameras || [];
  86369. // Initialize
  86370. _this._scene = scene;
  86371. _this._basePostProcess = originalPostProcess;
  86372. _this._ratio = ratio;
  86373. // Misc
  86374. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86375. // Finish
  86376. scene.postProcessRenderPipelineManager.addPipeline(_this);
  86377. _this._buildPipeline();
  86378. return _this;
  86379. }
  86380. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  86381. /**
  86382. * @ignore
  86383. * Specifies if the bloom pipeline is enabled
  86384. */
  86385. get: function () {
  86386. return this._bloomEnabled;
  86387. },
  86388. set: function (enabled) {
  86389. if (this._bloomEnabled === enabled) {
  86390. return;
  86391. }
  86392. this._bloomEnabled = enabled;
  86393. this._buildPipeline();
  86394. },
  86395. enumerable: true,
  86396. configurable: true
  86397. });
  86398. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  86399. /**
  86400. * @ignore
  86401. * Specifies if the depth of field pipeline is enabed
  86402. */
  86403. get: function () {
  86404. return this._depthOfFieldEnabled;
  86405. },
  86406. set: function (enabled) {
  86407. if (this._depthOfFieldEnabled === enabled) {
  86408. return;
  86409. }
  86410. this._depthOfFieldEnabled = enabled;
  86411. this._buildPipeline();
  86412. },
  86413. enumerable: true,
  86414. configurable: true
  86415. });
  86416. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  86417. /**
  86418. * @ignore
  86419. * Specifies if the lens flare pipeline is enabed
  86420. */
  86421. get: function () {
  86422. return this._lensFlareEnabled;
  86423. },
  86424. set: function (enabled) {
  86425. if (this._lensFlareEnabled === enabled) {
  86426. return;
  86427. }
  86428. this._lensFlareEnabled = enabled;
  86429. this._buildPipeline();
  86430. },
  86431. enumerable: true,
  86432. configurable: true
  86433. });
  86434. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  86435. /**
  86436. * @ignore
  86437. * Specifies if the HDR pipeline is enabled
  86438. */
  86439. get: function () {
  86440. return this._hdrEnabled;
  86441. },
  86442. set: function (enabled) {
  86443. if (this._hdrEnabled === enabled) {
  86444. return;
  86445. }
  86446. this._hdrEnabled = enabled;
  86447. this._buildPipeline();
  86448. },
  86449. enumerable: true,
  86450. configurable: true
  86451. });
  86452. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  86453. /**
  86454. * @ignore
  86455. * Specifies if the volumetric lights scattering effect is enabled
  86456. */
  86457. get: function () {
  86458. return this._vlsEnabled;
  86459. },
  86460. set: function (enabled) {
  86461. if (this._vlsEnabled === enabled) {
  86462. return;
  86463. }
  86464. if (enabled) {
  86465. var geometry = this._scene.enableGeometryBufferRenderer();
  86466. if (!geometry) {
  86467. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  86468. return;
  86469. }
  86470. }
  86471. this._vlsEnabled = enabled;
  86472. this._buildPipeline();
  86473. },
  86474. enumerable: true,
  86475. configurable: true
  86476. });
  86477. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  86478. /**
  86479. * @ignore
  86480. * Specifies if the motion blur effect is enabled
  86481. */
  86482. get: function () {
  86483. return this._motionBlurEnabled;
  86484. },
  86485. set: function (enabled) {
  86486. if (this._motionBlurEnabled === enabled) {
  86487. return;
  86488. }
  86489. this._motionBlurEnabled = enabled;
  86490. this._buildPipeline();
  86491. },
  86492. enumerable: true,
  86493. configurable: true
  86494. });
  86495. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  86496. /**
  86497. * Specifies if anti-aliasing is enabled
  86498. */
  86499. get: function () {
  86500. return this._fxaaEnabled;
  86501. },
  86502. set: function (enabled) {
  86503. if (this._fxaaEnabled === enabled) {
  86504. return;
  86505. }
  86506. this._fxaaEnabled = enabled;
  86507. this._buildPipeline();
  86508. },
  86509. enumerable: true,
  86510. configurable: true
  86511. });
  86512. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  86513. /**
  86514. * Specifies the number of steps used to calculate the volumetric lights
  86515. * Typically in interval [50, 200]
  86516. */
  86517. get: function () {
  86518. return this._volumetricLightStepsCount;
  86519. },
  86520. set: function (count) {
  86521. if (this.volumetricLightPostProcess) {
  86522. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  86523. }
  86524. this._volumetricLightStepsCount = count;
  86525. },
  86526. enumerable: true,
  86527. configurable: true
  86528. });
  86529. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  86530. /**
  86531. * Specifies the number of samples used for the motion blur effect
  86532. * Typically in interval [16, 64]
  86533. */
  86534. get: function () {
  86535. return this._motionBlurSamples;
  86536. },
  86537. set: function (samples) {
  86538. if (this.motionBlurPostProcess) {
  86539. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  86540. }
  86541. this._motionBlurSamples = samples;
  86542. },
  86543. enumerable: true,
  86544. configurable: true
  86545. });
  86546. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  86547. /**
  86548. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  86549. */
  86550. get: function () {
  86551. return this._samples;
  86552. },
  86553. set: function (sampleCount) {
  86554. if (this._samples === sampleCount) {
  86555. return;
  86556. }
  86557. this._samples = sampleCount;
  86558. this._buildPipeline();
  86559. },
  86560. enumerable: true,
  86561. configurable: true
  86562. });
  86563. StandardRenderingPipeline.prototype._buildPipeline = function () {
  86564. var _this = this;
  86565. var ratio = this._ratio;
  86566. var scene = this._scene;
  86567. this._disposePostProcesses();
  86568. this._reset();
  86569. // Create pass post-process
  86570. if (!this._basePostProcess) {
  86571. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  86572. this.originalPostProcess.onApply = function (effect) {
  86573. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  86574. };
  86575. }
  86576. else {
  86577. this.originalPostProcess = this._basePostProcess;
  86578. }
  86579. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  86580. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  86581. }
  86582. this._currentDepthOfFieldSource = this.originalPostProcess;
  86583. if (this._bloomEnabled) {
  86584. // Create down sample X4 post-process
  86585. this._createDownSampleX4PostProcess(scene, ratio / 2);
  86586. // Create bright pass post-process
  86587. this._createBrightPassPostProcess(scene, ratio / 2);
  86588. // Create gaussian blur post-processes (down sampling blurs)
  86589. this._createBlurPostProcesses(scene, ratio / 4, 1);
  86590. // Create texture adder post-process
  86591. this._createTextureAdderPostProcess(scene, ratio);
  86592. // Create depth-of-field source post-process
  86593. 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);
  86594. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  86595. }
  86596. if (this._vlsEnabled) {
  86597. // Create volumetric light
  86598. this._createVolumetricLightPostProcess(scene, ratio);
  86599. // Create volumetric light final post-process
  86600. 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);
  86601. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  86602. }
  86603. if (this._lensFlareEnabled) {
  86604. // Create lens flare post-process
  86605. this._createLensFlarePostProcess(scene, ratio);
  86606. // Create depth-of-field source post-process post lens-flare and disable it now
  86607. 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);
  86608. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  86609. }
  86610. if (this._hdrEnabled) {
  86611. // Create luminance
  86612. this._createLuminancePostProcesses(scene, this._floatTextureType);
  86613. // Create HDR
  86614. this._createHdrPostProcess(scene, ratio);
  86615. // Create depth-of-field source post-process post hdr and disable it now
  86616. 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);
  86617. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  86618. }
  86619. if (this._depthOfFieldEnabled) {
  86620. // Create gaussian blur used by depth-of-field
  86621. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  86622. // Create depth-of-field post-process
  86623. this._createDepthOfFieldPostProcess(scene, ratio);
  86624. }
  86625. if (this._motionBlurEnabled) {
  86626. // Create motion blur post-process
  86627. this._createMotionBlurPostProcess(scene, ratio);
  86628. }
  86629. if (this._fxaaEnabled) {
  86630. // Create fxaa post-process
  86631. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86632. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  86633. }
  86634. if (this._cameras !== null) {
  86635. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  86636. }
  86637. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  86638. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  86639. }
  86640. };
  86641. // Down Sample X4 Post-Processs
  86642. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  86643. var _this = this;
  86644. var downSampleX4Offsets = new Array(32);
  86645. 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);
  86646. this.downSampleX4PostProcess.onApply = function (effect) {
  86647. var id = 0;
  86648. var width = _this.downSampleX4PostProcess.width;
  86649. var height = _this.downSampleX4PostProcess.height;
  86650. for (var i = -2; i < 2; i++) {
  86651. for (var j = -2; j < 2; j++) {
  86652. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  86653. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  86654. id += 2;
  86655. }
  86656. }
  86657. effect.setArray2("dsOffsets", downSampleX4Offsets);
  86658. };
  86659. // Add to pipeline
  86660. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  86661. };
  86662. // Brightpass Post-Process
  86663. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  86664. var _this = this;
  86665. var brightOffsets = new Array(8);
  86666. 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);
  86667. this.brightPassPostProcess.onApply = function (effect) {
  86668. var sU = (1.0 / _this.brightPassPostProcess.width);
  86669. var sV = (1.0 / _this.brightPassPostProcess.height);
  86670. brightOffsets[0] = -0.5 * sU;
  86671. brightOffsets[1] = 0.5 * sV;
  86672. brightOffsets[2] = 0.5 * sU;
  86673. brightOffsets[3] = 0.5 * sV;
  86674. brightOffsets[4] = -0.5 * sU;
  86675. brightOffsets[5] = -0.5 * sV;
  86676. brightOffsets[6] = 0.5 * sU;
  86677. brightOffsets[7] = -0.5 * sV;
  86678. effect.setArray2("dsOffsets", brightOffsets);
  86679. effect.setFloat("brightThreshold", _this.brightThreshold);
  86680. };
  86681. // Add to pipeline
  86682. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  86683. };
  86684. // Create blur H&V post-processes
  86685. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  86686. var _this = this;
  86687. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  86688. var engine = scene.getEngine();
  86689. 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);
  86690. 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);
  86691. blurX.onActivateObservable.add(function () {
  86692. var dw = blurX.width / engine.getRenderWidth();
  86693. blurX.kernel = _this[blurWidthKey] * dw;
  86694. });
  86695. blurY.onActivateObservable.add(function () {
  86696. var dw = blurY.height / engine.getRenderHeight();
  86697. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  86698. });
  86699. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  86700. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  86701. this.blurHPostProcesses.push(blurX);
  86702. this.blurVPostProcesses.push(blurY);
  86703. };
  86704. // Create texture adder post-process
  86705. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  86706. var _this = this;
  86707. 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);
  86708. this.textureAdderPostProcess.onApply = function (effect) {
  86709. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  86710. effect.setTexture("lensSampler", _this.lensTexture);
  86711. effect.setFloat("exposure", _this.exposure);
  86712. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  86713. };
  86714. // Add to pipeline
  86715. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  86716. };
  86717. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  86718. var _this = this;
  86719. var geometryRenderer = scene.enableGeometryBufferRenderer();
  86720. geometryRenderer.enablePosition = true;
  86721. var geometry = geometryRenderer.getGBuffer();
  86722. // Base post-process
  86723. 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));
  86724. var depthValues = BABYLON.Vector2.Zero();
  86725. this.volumetricLightPostProcess.onApply = function (effect) {
  86726. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  86727. var generator = _this.sourceLight.getShadowGenerator();
  86728. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  86729. effect.setTexture("positionSampler", geometry.textures[2]);
  86730. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  86731. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  86732. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  86733. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  86734. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  86735. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  86736. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  86737. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  86738. effect.setVector2("depthValues", depthValues);
  86739. }
  86740. };
  86741. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  86742. // Smooth
  86743. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  86744. // Merge
  86745. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  86746. this.volumetricLightMergePostProces.onApply = function (effect) {
  86747. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  86748. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  86749. };
  86750. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  86751. };
  86752. // Create luminance
  86753. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  86754. var _this = this;
  86755. // Create luminance
  86756. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  86757. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  86758. var offsets = [];
  86759. this.luminancePostProcess.onApply = function (effect) {
  86760. var sU = (1.0 / _this.luminancePostProcess.width);
  86761. var sV = (1.0 / _this.luminancePostProcess.height);
  86762. offsets[0] = -0.5 * sU;
  86763. offsets[1] = 0.5 * sV;
  86764. offsets[2] = 0.5 * sU;
  86765. offsets[3] = 0.5 * sV;
  86766. offsets[4] = -0.5 * sU;
  86767. offsets[5] = -0.5 * sV;
  86768. offsets[6] = 0.5 * sU;
  86769. offsets[7] = -0.5 * sV;
  86770. effect.setArray2("lumOffsets", offsets);
  86771. };
  86772. // Add to pipeline
  86773. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  86774. // Create down sample luminance
  86775. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  86776. var size = Math.pow(3, i);
  86777. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  86778. if (i === 0) {
  86779. defines += "#define FINAL_DOWN_SAMPLER";
  86780. }
  86781. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  86782. this.luminanceDownSamplePostProcesses.push(postProcess);
  86783. }
  86784. // Create callbacks and add effects
  86785. var lastLuminance = this.luminancePostProcess;
  86786. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  86787. var downSampleOffsets = new Array(18);
  86788. pp.onApply = function (effect) {
  86789. if (!lastLuminance) {
  86790. return;
  86791. }
  86792. var id = 0;
  86793. for (var x = -1; x < 2; x++) {
  86794. for (var y = -1; y < 2; y++) {
  86795. downSampleOffsets[id] = x / lastLuminance.width;
  86796. downSampleOffsets[id + 1] = y / lastLuminance.height;
  86797. id += 2;
  86798. }
  86799. }
  86800. effect.setArray2("dsOffsets", downSampleOffsets);
  86801. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  86802. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  86803. lastLuminance = _this.luminancePostProcess;
  86804. }
  86805. else {
  86806. lastLuminance = pp;
  86807. }
  86808. };
  86809. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  86810. pp.onAfterRender = function (effect) {
  86811. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  86812. 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);
  86813. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  86814. };
  86815. }
  86816. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  86817. });
  86818. };
  86819. // Create HDR post-process
  86820. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  86821. var _this = this;
  86822. 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);
  86823. var outputLiminance = 1;
  86824. var time = 0;
  86825. var lastTime = 0;
  86826. this.hdrPostProcess.onApply = function (effect) {
  86827. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  86828. time += scene.getEngine().getDeltaTime();
  86829. if (outputLiminance < 0) {
  86830. outputLiminance = _this._hdrCurrentLuminance;
  86831. }
  86832. else {
  86833. var dt = (lastTime - time) / 1000.0;
  86834. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  86835. outputLiminance += _this.hdrDecreaseRate * dt;
  86836. }
  86837. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  86838. outputLiminance -= _this.hdrIncreaseRate * dt;
  86839. }
  86840. else {
  86841. outputLiminance = _this._hdrCurrentLuminance;
  86842. }
  86843. }
  86844. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  86845. effect.setFloat("averageLuminance", outputLiminance);
  86846. lastTime = time;
  86847. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  86848. };
  86849. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  86850. };
  86851. // Create lens flare post-process
  86852. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  86853. var _this = this;
  86854. 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);
  86855. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  86856. this._createBlurPostProcesses(scene, ratio / 4, 2);
  86857. 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);
  86858. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  86859. var resolution = new BABYLON.Vector2(0, 0);
  86860. // Lens flare
  86861. this.lensFlarePostProcess.onApply = function (effect) {
  86862. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  86863. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  86864. effect.setFloat("strength", _this.lensFlareStrength);
  86865. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  86866. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  86867. // Shift
  86868. resolution.x = _this.lensFlarePostProcess.width;
  86869. resolution.y = _this.lensFlarePostProcess.height;
  86870. effect.setVector2("resolution", resolution);
  86871. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  86872. };
  86873. // Compose
  86874. 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);
  86875. 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);
  86876. this.lensFlareComposePostProcess.onApply = function (effect) {
  86877. if (!_this._scene.activeCamera) {
  86878. return;
  86879. }
  86880. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  86881. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  86882. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  86883. // Lens start rotation matrix
  86884. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  86885. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  86886. 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));
  86887. camRot *= 4.0;
  86888. 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);
  86889. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  86890. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  86891. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  86892. };
  86893. };
  86894. // Create depth-of-field post-process
  86895. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  86896. var _this = this;
  86897. 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);
  86898. this.depthOfFieldPostProcess.onApply = function (effect) {
  86899. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  86900. effect.setTexture("depthSampler", _this._getDepthTexture());
  86901. effect.setFloat("distance", _this.depthOfFieldDistance);
  86902. };
  86903. // Add to pipeline
  86904. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  86905. };
  86906. // Create motion blur post-process
  86907. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  86908. var _this = this;
  86909. 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);
  86910. var motionScale = 0;
  86911. var prevViewProjection = BABYLON.Matrix.Identity();
  86912. var invViewProjection = BABYLON.Matrix.Identity();
  86913. var viewProjection = BABYLON.Matrix.Identity();
  86914. var screenSize = BABYLON.Vector2.Zero();
  86915. this.motionBlurPostProcess.onApply = function (effect) {
  86916. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  86917. viewProjection.invertToRef(invViewProjection);
  86918. effect.setMatrix("inverseViewProjection", invViewProjection);
  86919. effect.setMatrix("prevViewProjection", prevViewProjection);
  86920. prevViewProjection = viewProjection;
  86921. screenSize.x = _this.motionBlurPostProcess.width;
  86922. screenSize.y = _this.motionBlurPostProcess.height;
  86923. effect.setVector2("screenSize", screenSize);
  86924. motionScale = scene.getEngine().getFps() / 60.0;
  86925. effect.setFloat("motionScale", motionScale);
  86926. effect.setFloat("motionStrength", _this.motionStrength);
  86927. effect.setTexture("depthSampler", _this._getDepthTexture());
  86928. };
  86929. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  86930. };
  86931. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  86932. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  86933. var renderer = this._scene.enableGeometryBufferRenderer();
  86934. return renderer.getGBuffer().textures[0];
  86935. }
  86936. return this._scene.enableDepthRenderer().getDepthMap();
  86937. };
  86938. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  86939. for (var i = 0; i < this._cameras.length; i++) {
  86940. var camera = this._cameras[i];
  86941. if (this.originalPostProcess) {
  86942. this.originalPostProcess.dispose(camera);
  86943. }
  86944. if (this.downSampleX4PostProcess) {
  86945. this.downSampleX4PostProcess.dispose(camera);
  86946. }
  86947. if (this.brightPassPostProcess) {
  86948. this.brightPassPostProcess.dispose(camera);
  86949. }
  86950. if (this.textureAdderPostProcess) {
  86951. this.textureAdderPostProcess.dispose(camera);
  86952. }
  86953. if (this.textureAdderFinalPostProcess) {
  86954. this.textureAdderFinalPostProcess.dispose(camera);
  86955. }
  86956. if (this.volumetricLightPostProcess) {
  86957. this.volumetricLightPostProcess.dispose(camera);
  86958. }
  86959. if (this.volumetricLightSmoothXPostProcess) {
  86960. this.volumetricLightSmoothXPostProcess.dispose(camera);
  86961. }
  86962. if (this.volumetricLightSmoothYPostProcess) {
  86963. this.volumetricLightSmoothYPostProcess.dispose(camera);
  86964. }
  86965. if (this.volumetricLightMergePostProces) {
  86966. this.volumetricLightMergePostProces.dispose(camera);
  86967. }
  86968. if (this.volumetricLightFinalPostProcess) {
  86969. this.volumetricLightFinalPostProcess.dispose(camera);
  86970. }
  86971. if (this.lensFlarePostProcess) {
  86972. this.lensFlarePostProcess.dispose(camera);
  86973. }
  86974. if (this.lensFlareComposePostProcess) {
  86975. this.lensFlareComposePostProcess.dispose(camera);
  86976. }
  86977. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  86978. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  86979. }
  86980. if (this.luminancePostProcess) {
  86981. this.luminancePostProcess.dispose(camera);
  86982. }
  86983. if (this.hdrPostProcess) {
  86984. this.hdrPostProcess.dispose(camera);
  86985. }
  86986. if (this.hdrFinalPostProcess) {
  86987. this.hdrFinalPostProcess.dispose(camera);
  86988. }
  86989. if (this.depthOfFieldPostProcess) {
  86990. this.depthOfFieldPostProcess.dispose(camera);
  86991. }
  86992. if (this.motionBlurPostProcess) {
  86993. this.motionBlurPostProcess.dispose(camera);
  86994. }
  86995. if (this.fxaaPostProcess) {
  86996. this.fxaaPostProcess.dispose(camera);
  86997. }
  86998. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  86999. this.blurHPostProcesses[j].dispose(camera);
  87000. }
  87001. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  87002. this.blurVPostProcesses[j].dispose(camera);
  87003. }
  87004. }
  87005. this.originalPostProcess = null;
  87006. this.downSampleX4PostProcess = null;
  87007. this.brightPassPostProcess = null;
  87008. this.textureAdderPostProcess = null;
  87009. this.textureAdderFinalPostProcess = null;
  87010. this.volumetricLightPostProcess = null;
  87011. this.volumetricLightSmoothXPostProcess = null;
  87012. this.volumetricLightSmoothYPostProcess = null;
  87013. this.volumetricLightMergePostProces = null;
  87014. this.volumetricLightFinalPostProcess = null;
  87015. this.lensFlarePostProcess = null;
  87016. this.lensFlareComposePostProcess = null;
  87017. this.luminancePostProcess = null;
  87018. this.hdrPostProcess = null;
  87019. this.hdrFinalPostProcess = null;
  87020. this.depthOfFieldPostProcess = null;
  87021. this.motionBlurPostProcess = null;
  87022. this.fxaaPostProcess = null;
  87023. this.luminanceDownSamplePostProcesses = [];
  87024. this.blurHPostProcesses = [];
  87025. this.blurVPostProcesses = [];
  87026. };
  87027. /**
  87028. * Dispose of the pipeline and stop all post processes
  87029. */
  87030. StandardRenderingPipeline.prototype.dispose = function () {
  87031. this._disposePostProcesses();
  87032. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  87033. _super.prototype.dispose.call(this);
  87034. };
  87035. /**
  87036. * Serialize the rendering pipeline (Used when exporting)
  87037. * @returns the serialized object
  87038. */
  87039. StandardRenderingPipeline.prototype.serialize = function () {
  87040. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  87041. if (this.sourceLight) {
  87042. serializationObject.sourceLightId = this.sourceLight.id;
  87043. }
  87044. serializationObject.customType = "StandardRenderingPipeline";
  87045. return serializationObject;
  87046. };
  87047. /**
  87048. * Parse the serialized pipeline
  87049. * @param source Source pipeline.
  87050. * @param scene The scene to load the pipeline to.
  87051. * @param rootUrl The URL of the serialized pipeline.
  87052. * @returns An instantiated pipeline from the serialized object.
  87053. */
  87054. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  87055. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  87056. if (source.sourceLightId) {
  87057. p.sourceLight = scene.getLightByID(source.sourceLightId);
  87058. }
  87059. return p;
  87060. };
  87061. /**
  87062. * Luminance steps
  87063. */
  87064. StandardRenderingPipeline.LuminanceSteps = 6;
  87065. __decorate([
  87066. BABYLON.serialize()
  87067. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  87068. __decorate([
  87069. BABYLON.serialize()
  87070. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  87071. __decorate([
  87072. BABYLON.serialize()
  87073. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  87074. __decorate([
  87075. BABYLON.serialize()
  87076. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  87077. __decorate([
  87078. BABYLON.serializeAsTexture("lensTexture")
  87079. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  87080. __decorate([
  87081. BABYLON.serialize()
  87082. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  87083. __decorate([
  87084. BABYLON.serialize()
  87085. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  87086. __decorate([
  87087. BABYLON.serialize()
  87088. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  87089. __decorate([
  87090. BABYLON.serialize()
  87091. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  87092. __decorate([
  87093. BABYLON.serialize()
  87094. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  87095. __decorate([
  87096. BABYLON.serialize()
  87097. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  87098. __decorate([
  87099. BABYLON.serializeAsTexture("lensColorTexture")
  87100. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  87101. __decorate([
  87102. BABYLON.serialize()
  87103. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  87104. __decorate([
  87105. BABYLON.serialize()
  87106. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  87107. __decorate([
  87108. BABYLON.serialize()
  87109. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  87110. __decorate([
  87111. BABYLON.serialize()
  87112. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  87113. __decorate([
  87114. BABYLON.serializeAsTexture("lensStarTexture")
  87115. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  87116. __decorate([
  87117. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  87118. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  87119. __decorate([
  87120. BABYLON.serialize()
  87121. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  87122. __decorate([
  87123. BABYLON.serialize()
  87124. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  87125. __decorate([
  87126. BABYLON.serialize()
  87127. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  87128. __decorate([
  87129. BABYLON.serialize()
  87130. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  87131. __decorate([
  87132. BABYLON.serialize()
  87133. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  87134. __decorate([
  87135. BABYLON.serialize()
  87136. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  87137. __decorate([
  87138. BABYLON.serialize()
  87139. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  87140. __decorate([
  87141. BABYLON.serialize()
  87142. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  87143. __decorate([
  87144. BABYLON.serialize()
  87145. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  87146. __decorate([
  87147. BABYLON.serialize()
  87148. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  87149. __decorate([
  87150. BABYLON.serialize()
  87151. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  87152. __decorate([
  87153. BABYLON.serialize()
  87154. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  87155. __decorate([
  87156. BABYLON.serialize()
  87157. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  87158. __decorate([
  87159. BABYLON.serialize()
  87160. ], StandardRenderingPipeline.prototype, "samples", null);
  87161. return StandardRenderingPipeline;
  87162. }(BABYLON.PostProcessRenderPipeline));
  87163. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  87164. })(BABYLON || (BABYLON = {}));
  87165. //# sourceMappingURL=standardRenderingPipeline.js.map
  87166. var BABYLON;
  87167. (function (BABYLON) {
  87168. /**
  87169. * Fxaa post process
  87170. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#fxaa
  87171. */
  87172. var FxaaPostProcess = /** @class */ (function (_super) {
  87173. __extends(FxaaPostProcess, _super);
  87174. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  87175. if (camera === void 0) { camera = null; }
  87176. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87177. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  87178. var defines = _this._getDefines();
  87179. _this.updateEffect(defines);
  87180. _this.onApplyObservable.add(function (effect) {
  87181. var texelSize = _this.texelSize;
  87182. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  87183. });
  87184. return _this;
  87185. }
  87186. FxaaPostProcess.prototype._getDefines = function () {
  87187. var engine = this.getEngine();
  87188. if (!engine) {
  87189. return null;
  87190. }
  87191. var glInfo = engine.getGlInfo();
  87192. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  87193. return "#define MALI 1\n";
  87194. }
  87195. return null;
  87196. };
  87197. return FxaaPostProcess;
  87198. }(BABYLON.PostProcess));
  87199. BABYLON.FxaaPostProcess = FxaaPostProcess;
  87200. })(BABYLON || (BABYLON = {}));
  87201. //# sourceMappingURL=fxaaPostProcess.js.map
  87202. var BABYLON;
  87203. (function (BABYLON) {
  87204. /**
  87205. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  87206. */
  87207. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  87208. __extends(ChromaticAberrationPostProcess, _super);
  87209. /**
  87210. * Creates a new instance ChromaticAberrationPostProcess
  87211. * @param name The name of the effect.
  87212. * @param screenWidth The width of the screen to apply the effect on.
  87213. * @param screenHeight The height of the screen to apply the effect on.
  87214. * @param options The required width/height ratio to downsize to before computing the render pass.
  87215. * @param camera The camera to apply the render pass to.
  87216. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87217. * @param engine The engine which the post process will be applied. (default: current engine)
  87218. * @param reusable If the post process can be reused on the same frame. (default: false)
  87219. * @param textureType Type of textures used when performing the post process. (default: 0)
  87220. * @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)
  87221. */
  87222. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87223. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87224. if (blockCompilation === void 0) { blockCompilation = false; }
  87225. 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;
  87226. /**
  87227. * The amount of seperation of rgb channels (default: 30)
  87228. */
  87229. _this.aberrationAmount = 30;
  87230. /**
  87231. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  87232. */
  87233. _this.radialIntensity = 0;
  87234. /**
  87235. * 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))
  87236. */
  87237. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  87238. /**
  87239. * 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))
  87240. */
  87241. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  87242. _this.onApplyObservable.add(function (effect) {
  87243. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  87244. effect.setFloat('screen_width', screenWidth);
  87245. effect.setFloat('screen_height', screenHeight);
  87246. effect.setFloat('radialIntensity', _this.radialIntensity);
  87247. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  87248. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  87249. });
  87250. return _this;
  87251. }
  87252. return ChromaticAberrationPostProcess;
  87253. }(BABYLON.PostProcess));
  87254. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  87255. })(BABYLON || (BABYLON = {}));
  87256. //# sourceMappingURL=chromaticAberrationPostProcess.js.map
  87257. var BABYLON;
  87258. (function (BABYLON) {
  87259. /**
  87260. * The GrainPostProcess adds noise to the image at mid luminance levels
  87261. */
  87262. var GrainPostProcess = /** @class */ (function (_super) {
  87263. __extends(GrainPostProcess, _super);
  87264. /**
  87265. * Creates a new instance of @see GrainPostProcess
  87266. * @param name The name of the effect.
  87267. * @param options The required width/height ratio to downsize to before computing the render pass.
  87268. * @param camera The camera to apply the render pass to.
  87269. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87270. * @param engine The engine which the post process will be applied. (default: current engine)
  87271. * @param reusable If the post process can be reused on the same frame. (default: false)
  87272. * @param textureType Type of textures used when performing the post process. (default: 0)
  87273. * @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)
  87274. */
  87275. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87276. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87277. if (blockCompilation === void 0) { blockCompilation = false; }
  87278. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  87279. /**
  87280. * The intensity of the grain added (default: 30)
  87281. */
  87282. _this.intensity = 30;
  87283. /**
  87284. * If the grain should be randomized on every frame
  87285. */
  87286. _this.animated = false;
  87287. _this.onApplyObservable.add(function (effect) {
  87288. effect.setFloat('intensity', _this.intensity);
  87289. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  87290. });
  87291. return _this;
  87292. }
  87293. return GrainPostProcess;
  87294. }(BABYLON.PostProcess));
  87295. BABYLON.GrainPostProcess = GrainPostProcess;
  87296. })(BABYLON || (BABYLON = {}));
  87297. //# sourceMappingURL=grainPostProcess.js.map
  87298. var BABYLON;
  87299. (function (BABYLON) {
  87300. /**
  87301. * The SharpenPostProcess applies a sharpen kernel to every pixel
  87302. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  87303. */
  87304. var SharpenPostProcess = /** @class */ (function (_super) {
  87305. __extends(SharpenPostProcess, _super);
  87306. /**
  87307. * Creates a new instance ConvolutionPostProcess
  87308. * @param name The name of the effect.
  87309. * @param options The required width/height ratio to downsize to before computing the render pass.
  87310. * @param camera The camera to apply the render pass to.
  87311. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87312. * @param engine The engine which the post process will be applied. (default: current engine)
  87313. * @param reusable If the post process can be reused on the same frame. (default: false)
  87314. * @param textureType Type of textures used when performing the post process. (default: 0)
  87315. * @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)
  87316. */
  87317. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87318. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87319. if (blockCompilation === void 0) { blockCompilation = false; }
  87320. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  87321. /**
  87322. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  87323. */
  87324. _this.colorAmount = 1.0;
  87325. /**
  87326. * How much sharpness should be applied (default: 0.3)
  87327. */
  87328. _this.edgeAmount = 0.3;
  87329. _this.onApply = function (effect) {
  87330. effect.setFloat2("screenSize", _this.width, _this.height);
  87331. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  87332. };
  87333. return _this;
  87334. }
  87335. return SharpenPostProcess;
  87336. }(BABYLON.PostProcess));
  87337. BABYLON.SharpenPostProcess = SharpenPostProcess;
  87338. })(BABYLON || (BABYLON = {}));
  87339. //# sourceMappingURL=sharpenPostProcess.js.map
  87340. var BABYLON;
  87341. (function (BABYLON) {
  87342. /**
  87343. * The Blur Post Process which blurs an image based on a kernel and direction.
  87344. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  87345. */
  87346. var BlurPostProcess = /** @class */ (function (_super) {
  87347. __extends(BlurPostProcess, _super);
  87348. /**
  87349. * Creates a new instance BlurPostProcess
  87350. * @param name The name of the effect.
  87351. * @param direction The direction in which to blur the image.
  87352. * @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.
  87353. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  87354. * @param camera The camera to apply the render pass to.
  87355. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87356. * @param engine The engine which the post process will be applied. (default: current engine)
  87357. * @param reusable If the post process can be reused on the same frame. (default: false)
  87358. * @param textureType Type of textures used when performing the post process. (default: 0)
  87359. * @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)
  87360. */
  87361. function BlurPostProcess(name,
  87362. /** The direction in which to blur the image. */
  87363. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  87364. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  87365. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87366. if (defines === void 0) { defines = ""; }
  87367. if (blockCompilation === void 0) { blockCompilation = false; }
  87368. 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;
  87369. _this.direction = direction;
  87370. _this.blockCompilation = blockCompilation;
  87371. _this._packedFloat = false;
  87372. _this._staticDefines = "";
  87373. _this._staticDefines = defines;
  87374. _this.onApplyObservable.add(function (effect) {
  87375. if (_this._outputTexture) {
  87376. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  87377. }
  87378. else {
  87379. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  87380. }
  87381. });
  87382. _this.kernel = kernel;
  87383. return _this;
  87384. }
  87385. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  87386. /**
  87387. * Gets the length in pixels of the blur sample region
  87388. */
  87389. get: function () {
  87390. return this._idealKernel;
  87391. },
  87392. /**
  87393. * Sets the length in pixels of the blur sample region
  87394. */
  87395. set: function (v) {
  87396. if (this._idealKernel === v) {
  87397. return;
  87398. }
  87399. v = Math.max(v, 1);
  87400. this._idealKernel = v;
  87401. this._kernel = this._nearestBestKernel(v);
  87402. if (!this.blockCompilation) {
  87403. this._updateParameters();
  87404. }
  87405. },
  87406. enumerable: true,
  87407. configurable: true
  87408. });
  87409. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  87410. /**
  87411. * Gets wether or not the blur is unpacking/repacking floats
  87412. */
  87413. get: function () {
  87414. return this._packedFloat;
  87415. },
  87416. /**
  87417. * Sets wether or not the blur needs to unpack/repack floats
  87418. */
  87419. set: function (v) {
  87420. if (this._packedFloat === v) {
  87421. return;
  87422. }
  87423. this._packedFloat = v;
  87424. if (!this.blockCompilation) {
  87425. this._updateParameters();
  87426. }
  87427. },
  87428. enumerable: true,
  87429. configurable: true
  87430. });
  87431. /**
  87432. * Updates the effect with the current post process compile time values and recompiles the shader.
  87433. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  87434. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  87435. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  87436. * @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
  87437. * @param onCompiled Called when the shader has been compiled.
  87438. * @param onError Called if there is an error when compiling a shader.
  87439. */
  87440. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  87441. if (defines === void 0) { defines = null; }
  87442. if (uniforms === void 0) { uniforms = null; }
  87443. if (samplers === void 0) { samplers = null; }
  87444. this._updateParameters(onCompiled, onError);
  87445. };
  87446. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  87447. // Generate sampling offsets and weights
  87448. var N = this._kernel;
  87449. var centerIndex = (N - 1) / 2;
  87450. // Generate Gaussian sampling weights over kernel
  87451. var offsets = [];
  87452. var weights = [];
  87453. var totalWeight = 0;
  87454. for (var i = 0; i < N; i++) {
  87455. var u = i / (N - 1);
  87456. var w = this._gaussianWeight(u * 2.0 - 1);
  87457. offsets[i] = (i - centerIndex);
  87458. weights[i] = w;
  87459. totalWeight += w;
  87460. }
  87461. // Normalize weights
  87462. for (var i = 0; i < weights.length; i++) {
  87463. weights[i] /= totalWeight;
  87464. }
  87465. // Optimize: combine samples to take advantage of hardware linear sampling
  87466. // Walk from left to center, combining pairs (symmetrically)
  87467. var linearSamplingWeights = [];
  87468. var linearSamplingOffsets = [];
  87469. var linearSamplingMap = [];
  87470. for (var i = 0; i <= centerIndex; i += 2) {
  87471. var j = Math.min(i + 1, Math.floor(centerIndex));
  87472. var singleCenterSample = i === j;
  87473. if (singleCenterSample) {
  87474. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  87475. }
  87476. else {
  87477. var sharedCell = j === centerIndex;
  87478. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  87479. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  87480. if (offsetLinear === 0) {
  87481. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  87482. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  87483. }
  87484. else {
  87485. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  87486. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  87487. }
  87488. }
  87489. }
  87490. for (var i = 0; i < linearSamplingMap.length; i++) {
  87491. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  87492. linearSamplingWeights[i] = linearSamplingMap[i].w;
  87493. }
  87494. // Replace with optimized
  87495. offsets = linearSamplingOffsets;
  87496. weights = linearSamplingWeights;
  87497. // Generate shaders
  87498. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  87499. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  87500. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  87501. var defines = "";
  87502. defines += this._staticDefines;
  87503. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  87504. if (this._staticDefines.indexOf("DOF") != -1) {
  87505. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  87506. varyingCount--;
  87507. }
  87508. for (var i = 0; i < varyingCount; i++) {
  87509. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  87510. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  87511. }
  87512. var depCount = 0;
  87513. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  87514. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  87515. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  87516. depCount++;
  87517. }
  87518. if (this.packedFloat) {
  87519. defines += "#define PACKEDFLOAT 1";
  87520. }
  87521. this.blockCompilation = false;
  87522. _super.prototype.updateEffect.call(this, defines, null, null, {
  87523. varyingCount: varyingCount,
  87524. depCount: depCount
  87525. }, onCompiled, onError);
  87526. };
  87527. /**
  87528. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  87529. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  87530. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  87531. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  87532. * The gaps between physical kernels are compensated for in the weighting of the samples
  87533. * @param idealKernel Ideal blur kernel.
  87534. * @return Nearest best kernel.
  87535. */
  87536. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  87537. var v = Math.round(idealKernel);
  87538. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  87539. var k = _a[_i];
  87540. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  87541. return Math.max(k, 3);
  87542. }
  87543. }
  87544. return Math.max(v, 3);
  87545. };
  87546. /**
  87547. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  87548. * @param x The point on the Gaussian distribution to sample.
  87549. * @return the value of the Gaussian function at x.
  87550. */
  87551. BlurPostProcess.prototype._gaussianWeight = function (x) {
  87552. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  87553. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  87554. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  87555. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  87556. // truncated at around 1.3% of peak strength.
  87557. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  87558. var sigma = (1 / 3);
  87559. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  87560. var exponent = -((x * x) / (2.0 * sigma * sigma));
  87561. var weight = (1.0 / denominator) * Math.exp(exponent);
  87562. return weight;
  87563. };
  87564. /**
  87565. * Generates a string that can be used as a floating point number in GLSL.
  87566. * @param x Value to print.
  87567. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  87568. * @return GLSL float string.
  87569. */
  87570. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  87571. if (decimalFigures === void 0) { decimalFigures = 8; }
  87572. return x.toFixed(decimalFigures).replace(/0+$/, '');
  87573. };
  87574. return BlurPostProcess;
  87575. }(BABYLON.PostProcess));
  87576. BABYLON.BlurPostProcess = BlurPostProcess;
  87577. })(BABYLON || (BABYLON = {}));
  87578. //# sourceMappingURL=blurPostProcess.js.map
  87579. var BABYLON;
  87580. (function (BABYLON) {
  87581. /**
  87582. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  87583. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  87584. * based on samples that have a large difference in distance than the center pixel.
  87585. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  87586. */
  87587. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  87588. __extends(DepthOfFieldBlurPostProcess, _super);
  87589. /**
  87590. * Creates a new instance CircleOfConfusionPostProcess
  87591. * @param name The name of the effect.
  87592. * @param scene The scene the effect belongs to.
  87593. * @param direction The direction the blur should be applied.
  87594. * @param kernel The size of the kernel used to blur.
  87595. * @param options The required width/height ratio to downsize to before computing the render pass.
  87596. * @param camera The camera to apply the render pass to.
  87597. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  87598. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  87599. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87600. * @param engine The engine which the post process will be applied. (default: current engine)
  87601. * @param reusable If the post process can be reused on the same frame. (default: false)
  87602. * @param textureType Type of textures used when performing the post process. (default: 0)
  87603. * @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)
  87604. */
  87605. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  87606. if (imageToBlur === void 0) { imageToBlur = null; }
  87607. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  87608. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87609. if (blockCompilation === void 0) { blockCompilation = false; }
  87610. 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;
  87611. _this.direction = direction;
  87612. _this.onApplyObservable.add(function (effect) {
  87613. if (imageToBlur != null) {
  87614. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  87615. }
  87616. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  87617. if (scene.activeCamera) {
  87618. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  87619. }
  87620. });
  87621. return _this;
  87622. }
  87623. return DepthOfFieldBlurPostProcess;
  87624. }(BABYLON.BlurPostProcess));
  87625. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  87626. })(BABYLON || (BABYLON = {}));
  87627. //# sourceMappingURL=depthOfFieldBlurPostProcess.js.map
  87628. var BABYLON;
  87629. (function (BABYLON) {
  87630. /**
  87631. * Options to be set when merging outputs from the default pipeline.
  87632. */
  87633. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  87634. function DepthOfFieldMergePostProcessOptions() {
  87635. }
  87636. return DepthOfFieldMergePostProcessOptions;
  87637. }());
  87638. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  87639. /**
  87640. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  87641. */
  87642. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  87643. __extends(DepthOfFieldMergePostProcess, _super);
  87644. /**
  87645. * Creates a new instance of DepthOfFieldMergePostProcess
  87646. * @param name The name of the effect.
  87647. * @param originalFromInput Post process which's input will be used for the merge.
  87648. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  87649. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  87650. * @param options The required width/height ratio to downsize to before computing the render pass.
  87651. * @param camera The camera to apply the render pass to.
  87652. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87653. * @param engine The engine which the post process will be applied. (default: current engine)
  87654. * @param reusable If the post process can be reused on the same frame. (default: false)
  87655. * @param textureType Type of textures used when performing the post process. (default: 0)
  87656. * @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)
  87657. */
  87658. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87659. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87660. if (blockCompilation === void 0) { blockCompilation = false; }
  87661. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  87662. _this.blurSteps = blurSteps;
  87663. _this.onApplyObservable.add(function (effect) {
  87664. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  87665. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  87666. blurSteps.forEach(function (step, index) {
  87667. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  87668. });
  87669. });
  87670. if (!blockCompilation) {
  87671. _this.updateEffect();
  87672. }
  87673. return _this;
  87674. }
  87675. /**
  87676. * Updates the effect with the current post process compile time values and recompiles the shader.
  87677. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  87678. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  87679. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  87680. * @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
  87681. * @param onCompiled Called when the shader has been compiled.
  87682. * @param onError Called if there is an error when compiling a shader.
  87683. */
  87684. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  87685. if (defines === void 0) { defines = null; }
  87686. if (uniforms === void 0) { uniforms = null; }
  87687. if (samplers === void 0) { samplers = null; }
  87688. if (!defines) {
  87689. defines = "";
  87690. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  87691. }
  87692. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  87693. };
  87694. return DepthOfFieldMergePostProcess;
  87695. }(BABYLON.PostProcess));
  87696. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  87697. })(BABYLON || (BABYLON = {}));
  87698. //# sourceMappingURL=depthOfFieldMergePostProcess.js.map
  87699. var BABYLON;
  87700. (function (BABYLON) {
  87701. /**
  87702. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  87703. */
  87704. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  87705. __extends(CircleOfConfusionPostProcess, _super);
  87706. /**
  87707. * Creates a new instance CircleOfConfusionPostProcess
  87708. * @param name The name of the effect.
  87709. * @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.
  87710. * @param options The required width/height ratio to downsize to before computing the render pass.
  87711. * @param camera The camera to apply the render pass to.
  87712. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87713. * @param engine The engine which the post process will be applied. (default: current engine)
  87714. * @param reusable If the post process can be reused on the same frame. (default: false)
  87715. * @param textureType Type of textures used when performing the post process. (default: 0)
  87716. * @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)
  87717. */
  87718. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87719. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87720. if (blockCompilation === void 0) { blockCompilation = false; }
  87721. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  87722. /**
  87723. * 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.
  87724. */
  87725. _this.lensSize = 50;
  87726. /**
  87727. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  87728. */
  87729. _this.fStop = 1.4;
  87730. /**
  87731. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  87732. */
  87733. _this.focusDistance = 2000;
  87734. /**
  87735. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  87736. */
  87737. _this.focalLength = 50;
  87738. _this._depthTexture = null;
  87739. _this._depthTexture = depthTexture;
  87740. _this.onApplyObservable.add(function (effect) {
  87741. if (!_this._depthTexture) {
  87742. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  87743. return;
  87744. }
  87745. effect.setTexture("depthSampler", _this._depthTexture);
  87746. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  87747. var aperture = _this.lensSize / _this.fStop;
  87748. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  87749. effect.setFloat('focusDistance', _this.focusDistance);
  87750. effect.setFloat('cocPrecalculation', cocPrecalculation);
  87751. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  87752. });
  87753. return _this;
  87754. }
  87755. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  87756. /**
  87757. * 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.
  87758. */
  87759. set: function (value) {
  87760. this._depthTexture = value;
  87761. },
  87762. enumerable: true,
  87763. configurable: true
  87764. });
  87765. return CircleOfConfusionPostProcess;
  87766. }(BABYLON.PostProcess));
  87767. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  87768. })(BABYLON || (BABYLON = {}));
  87769. //# sourceMappingURL=circleOfConfusionPostProcess.js.map
  87770. var BABYLON;
  87771. (function (BABYLON) {
  87772. /**
  87773. * Specifies the level of max blur that should be applied when using the depth of field effect
  87774. */
  87775. var DepthOfFieldEffectBlurLevel;
  87776. (function (DepthOfFieldEffectBlurLevel) {
  87777. /**
  87778. * Subtle blur
  87779. */
  87780. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  87781. /**
  87782. * Medium blur
  87783. */
  87784. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  87785. /**
  87786. * Large blur
  87787. */
  87788. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  87789. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  87790. /**
  87791. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  87792. */
  87793. var DepthOfFieldEffect = /** @class */ (function (_super) {
  87794. __extends(DepthOfFieldEffect, _super);
  87795. /**
  87796. * Creates a new instance DepthOfFieldEffect
  87797. * @param scene The scene the effect belongs to.
  87798. * @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.
  87799. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  87800. * @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)
  87801. */
  87802. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  87803. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  87804. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  87805. if (blockCompilation === void 0) { blockCompilation = false; }
  87806. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  87807. return _this._effects;
  87808. }, true) || this;
  87809. /**
  87810. * @hidden Internal post processes in depth of field effect
  87811. */
  87812. _this._effects = [];
  87813. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  87814. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  87815. // 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)
  87816. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  87817. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  87818. _this._depthOfFieldBlurY = [];
  87819. _this._depthOfFieldBlurX = [];
  87820. var blurCount = 1;
  87821. var kernelSize = 15;
  87822. switch (blurLevel) {
  87823. case DepthOfFieldEffectBlurLevel.High: {
  87824. blurCount = 3;
  87825. kernelSize = 51;
  87826. break;
  87827. }
  87828. case DepthOfFieldEffectBlurLevel.Medium: {
  87829. blurCount = 2;
  87830. kernelSize = 31;
  87831. break;
  87832. }
  87833. default: {
  87834. kernelSize = 15;
  87835. blurCount = 1;
  87836. break;
  87837. }
  87838. }
  87839. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  87840. var ratio = 1.0;
  87841. for (var i = 0; i < blurCount; i++) {
  87842. 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);
  87843. blurY.autoClear = false;
  87844. ratio = 0.75 / Math.pow(2, i);
  87845. 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);
  87846. blurX.autoClear = false;
  87847. _this._depthOfFieldBlurY.push(blurY);
  87848. _this._depthOfFieldBlurX.push(blurX);
  87849. }
  87850. // Set all post processes on the effect.
  87851. _this._effects = [_this._circleOfConfusion];
  87852. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  87853. _this._effects.push(_this._depthOfFieldBlurY[i]);
  87854. _this._effects.push(_this._depthOfFieldBlurX[i]);
  87855. }
  87856. // Merge blurred images with original image based on circleOfConfusion
  87857. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  87858. _this._dofMerge.autoClear = false;
  87859. _this._effects.push(_this._dofMerge);
  87860. return _this;
  87861. }
  87862. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  87863. get: function () {
  87864. return this._circleOfConfusion.focalLength;
  87865. },
  87866. /**
  87867. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  87868. */
  87869. set: function (value) {
  87870. this._circleOfConfusion.focalLength = value;
  87871. },
  87872. enumerable: true,
  87873. configurable: true
  87874. });
  87875. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  87876. get: function () {
  87877. return this._circleOfConfusion.fStop;
  87878. },
  87879. /**
  87880. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  87881. */
  87882. set: function (value) {
  87883. this._circleOfConfusion.fStop = value;
  87884. },
  87885. enumerable: true,
  87886. configurable: true
  87887. });
  87888. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  87889. get: function () {
  87890. return this._circleOfConfusion.focusDistance;
  87891. },
  87892. /**
  87893. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  87894. */
  87895. set: function (value) {
  87896. this._circleOfConfusion.focusDistance = value;
  87897. },
  87898. enumerable: true,
  87899. configurable: true
  87900. });
  87901. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  87902. get: function () {
  87903. return this._circleOfConfusion.lensSize;
  87904. },
  87905. /**
  87906. * 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.
  87907. */
  87908. set: function (value) {
  87909. this._circleOfConfusion.lensSize = value;
  87910. },
  87911. enumerable: true,
  87912. configurable: true
  87913. });
  87914. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  87915. /**
  87916. * 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.
  87917. */
  87918. set: function (value) {
  87919. this._circleOfConfusion.depthTexture = value;
  87920. },
  87921. enumerable: true,
  87922. configurable: true
  87923. });
  87924. /**
  87925. * Disposes each of the internal effects for a given camera.
  87926. * @param camera The camera to dispose the effect on.
  87927. */
  87928. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  87929. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  87930. this._effects[effectIndex].dispose(camera);
  87931. }
  87932. };
  87933. /**
  87934. * @hidden Internal
  87935. */
  87936. DepthOfFieldEffect.prototype._updateEffects = function () {
  87937. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  87938. this._effects[effectIndex].updateEffect();
  87939. }
  87940. };
  87941. /**
  87942. * Internal
  87943. * @returns if all the contained post processes are ready.
  87944. * @hidden
  87945. */
  87946. DepthOfFieldEffect.prototype._isReady = function () {
  87947. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  87948. if (!this._effects[effectIndex].isReady()) {
  87949. return false;
  87950. }
  87951. }
  87952. return true;
  87953. };
  87954. return DepthOfFieldEffect;
  87955. }(BABYLON.PostProcessRenderEffect));
  87956. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  87957. })(BABYLON || (BABYLON = {}));
  87958. //# sourceMappingURL=depthOfFieldEffect.js.map
  87959. var BABYLON;
  87960. (function (BABYLON) {
  87961. /**
  87962. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  87963. */
  87964. var BloomMergePostProcess = /** @class */ (function (_super) {
  87965. __extends(BloomMergePostProcess, _super);
  87966. /**
  87967. * Creates a new instance of @see BloomMergePostProcess
  87968. * @param name The name of the effect.
  87969. * @param originalFromInput Post process which's input will be used for the merge.
  87970. * @param blurred Blurred highlights post process which's output will be used.
  87971. * @param weight Weight of the bloom to be added to the original input.
  87972. * @param options The required width/height ratio to downsize to before computing the render pass.
  87973. * @param camera The camera to apply the render pass to.
  87974. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87975. * @param engine The engine which the post process will be applied. (default: current engine)
  87976. * @param reusable If the post process can be reused on the same frame. (default: false)
  87977. * @param textureType Type of textures used when performing the post process. (default: 0)
  87978. * @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)
  87979. */
  87980. function BloomMergePostProcess(name, originalFromInput, blurred,
  87981. /** Weight of the bloom to be added to the original input. */
  87982. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  87983. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87984. if (blockCompilation === void 0) { blockCompilation = false; }
  87985. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  87986. _this.weight = weight;
  87987. _this.onApplyObservable.add(function (effect) {
  87988. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  87989. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  87990. effect.setFloat("bloomWeight", _this.weight);
  87991. });
  87992. if (!blockCompilation) {
  87993. _this.updateEffect();
  87994. }
  87995. return _this;
  87996. }
  87997. return BloomMergePostProcess;
  87998. }(BABYLON.PostProcess));
  87999. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  88000. })(BABYLON || (BABYLON = {}));
  88001. //# sourceMappingURL=bloomMergePostProcess.js.map
  88002. var BABYLON;
  88003. (function (BABYLON) {
  88004. /**
  88005. * 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.
  88006. */
  88007. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  88008. __extends(ExtractHighlightsPostProcess, _super);
  88009. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  88010. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88011. if (blockCompilation === void 0) { blockCompilation = false; }
  88012. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  88013. /**
  88014. * The luminance threshold, pixels below this value will be set to black.
  88015. */
  88016. _this.threshold = 0.9;
  88017. /** @hidden */
  88018. _this._exposure = 1;
  88019. /**
  88020. * Post process which has the input texture to be used when performing highlight extraction
  88021. * @hidden
  88022. */
  88023. _this._inputPostProcess = null;
  88024. _this.onApplyObservable.add(function (effect) {
  88025. if (_this._inputPostProcess) {
  88026. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  88027. }
  88028. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  88029. effect.setFloat('exposure', _this._exposure);
  88030. });
  88031. return _this;
  88032. }
  88033. return ExtractHighlightsPostProcess;
  88034. }(BABYLON.PostProcess));
  88035. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  88036. })(BABYLON || (BABYLON = {}));
  88037. //# sourceMappingURL=extractHighlightsPostProcess.js.map
  88038. var BABYLON;
  88039. (function (BABYLON) {
  88040. /**
  88041. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  88042. */
  88043. var BloomEffect = /** @class */ (function (_super) {
  88044. __extends(BloomEffect, _super);
  88045. /**
  88046. * Creates a new instance of @see BloomEffect
  88047. * @param scene The scene the effect belongs to.
  88048. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  88049. * @param bloomKernel The size of the kernel to be used when applying the blur.
  88050. * @param bloomWeight The the strength of bloom.
  88051. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  88052. * @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)
  88053. */
  88054. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  88055. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  88056. if (blockCompilation === void 0) { blockCompilation = false; }
  88057. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  88058. return _this._effects;
  88059. }, true) || this;
  88060. _this.bloomScale = bloomScale;
  88061. /**
  88062. * @hidden Internal
  88063. */
  88064. _this._effects = [];
  88065. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  88066. _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);
  88067. _this._blurX.alwaysForcePOT = true;
  88068. _this._blurX.autoClear = false;
  88069. _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);
  88070. _this._blurY.alwaysForcePOT = true;
  88071. _this._blurY.autoClear = false;
  88072. _this.kernel = bloomKernel;
  88073. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  88074. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  88075. _this._merge.autoClear = false;
  88076. _this._effects.push(_this._merge);
  88077. return _this;
  88078. }
  88079. Object.defineProperty(BloomEffect.prototype, "threshold", {
  88080. /**
  88081. * The luminance threshold to find bright areas of the image to bloom.
  88082. */
  88083. get: function () {
  88084. return this._downscale.threshold;
  88085. },
  88086. set: function (value) {
  88087. this._downscale.threshold = value;
  88088. },
  88089. enumerable: true,
  88090. configurable: true
  88091. });
  88092. Object.defineProperty(BloomEffect.prototype, "weight", {
  88093. /**
  88094. * The strength of the bloom.
  88095. */
  88096. get: function () {
  88097. return this._merge.weight;
  88098. },
  88099. set: function (value) {
  88100. this._merge.weight = value;
  88101. },
  88102. enumerable: true,
  88103. configurable: true
  88104. });
  88105. Object.defineProperty(BloomEffect.prototype, "kernel", {
  88106. /**
  88107. * Specifies the size of the bloom blur kernel, relative to the final output size
  88108. */
  88109. get: function () {
  88110. return this._blurX.kernel / this.bloomScale;
  88111. },
  88112. set: function (value) {
  88113. this._blurX.kernel = value * this.bloomScale;
  88114. this._blurY.kernel = value * this.bloomScale;
  88115. },
  88116. enumerable: true,
  88117. configurable: true
  88118. });
  88119. /**
  88120. * Disposes each of the internal effects for a given camera.
  88121. * @param camera The camera to dispose the effect on.
  88122. */
  88123. BloomEffect.prototype.disposeEffects = function (camera) {
  88124. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  88125. this._effects[effectIndex].dispose(camera);
  88126. }
  88127. };
  88128. /**
  88129. * @hidden Internal
  88130. */
  88131. BloomEffect.prototype._updateEffects = function () {
  88132. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  88133. this._effects[effectIndex].updateEffect();
  88134. }
  88135. };
  88136. /**
  88137. * Internal
  88138. * @returns if all the contained post processes are ready.
  88139. * @hidden
  88140. */
  88141. BloomEffect.prototype._isReady = function () {
  88142. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  88143. if (!this._effects[effectIndex].isReady()) {
  88144. return false;
  88145. }
  88146. }
  88147. return true;
  88148. };
  88149. return BloomEffect;
  88150. }(BABYLON.PostProcessRenderEffect));
  88151. BABYLON.BloomEffect = BloomEffect;
  88152. })(BABYLON || (BABYLON = {}));
  88153. //# sourceMappingURL=bloomEffect.js.map
  88154. var BABYLON;
  88155. (function (BABYLON) {
  88156. /**
  88157. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  88158. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  88159. */
  88160. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  88161. __extends(DefaultRenderingPipeline, _super);
  88162. /**
  88163. * @constructor
  88164. * @param name - The rendering pipeline name (default: "")
  88165. * @param hdr - If high dynamic range textures should be used (default: true)
  88166. * @param scene - The scene linked to this pipeline (default: the last created scene)
  88167. * @param cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  88168. * @param automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  88169. */
  88170. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  88171. if (name === void 0) { name = ""; }
  88172. if (hdr === void 0) { hdr = true; }
  88173. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  88174. if (automaticBuild === void 0) { automaticBuild = true; }
  88175. var _this = _super.call(this, scene.getEngine(), name) || this;
  88176. _this._camerasToBeAttached = [];
  88177. /**
  88178. * ID of the sharpen post process,
  88179. */
  88180. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  88181. /**
  88182. * @ignore
  88183. * ID of the image processing post process;
  88184. */
  88185. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  88186. /**
  88187. * @ignore
  88188. * ID of the Fast Approximate Anti-Aliasing post process;
  88189. */
  88190. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  88191. /**
  88192. * ID of the chromatic aberration post process,
  88193. */
  88194. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  88195. /**
  88196. * ID of the grain post process
  88197. */
  88198. _this.GrainPostProcessId = "GrainPostProcessEffect";
  88199. /**
  88200. * Glow post process which adds a glow to emmisive areas of the image
  88201. */
  88202. _this._glowLayer = null;
  88203. /**
  88204. * Animations which can be used to tweak settings over a period of time
  88205. */
  88206. _this.animations = [];
  88207. _this._imageProcessingConfigurationObserver = null;
  88208. // Values
  88209. _this._sharpenEnabled = false;
  88210. _this._bloomEnabled = false;
  88211. _this._depthOfFieldEnabled = false;
  88212. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  88213. _this._fxaaEnabled = false;
  88214. _this._imageProcessingEnabled = true;
  88215. _this._bloomScale = 0.5;
  88216. _this._chromaticAberrationEnabled = false;
  88217. _this._grainEnabled = false;
  88218. _this._buildAllowed = true;
  88219. _this._resizeObserver = null;
  88220. _this._hardwareScaleLevel = 1.0;
  88221. _this._bloomKernel = 64;
  88222. /**
  88223. * Specifies the weight of the bloom in the final rendering
  88224. */
  88225. _this._bloomWeight = 0.15;
  88226. /**
  88227. * Specifies the luma threshold for the area that will be blurred by the bloom
  88228. */
  88229. _this._bloomThreshold = 0.9;
  88230. _this._samples = 1;
  88231. _this._hasCleared = false;
  88232. _this._prevPostProcess = null;
  88233. _this._prevPrevPostProcess = null;
  88234. _this._depthOfFieldSceneObserver = null;
  88235. _this._cameras = cameras || scene.cameras;
  88236. _this._cameras = _this._cameras.slice();
  88237. _this._camerasToBeAttached = _this._cameras.slice();
  88238. _this._buildAllowed = automaticBuild;
  88239. // Initialize
  88240. _this._scene = scene;
  88241. var caps = _this._scene.getEngine().getCaps();
  88242. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  88243. // Misc
  88244. if (_this._hdr) {
  88245. if (caps.textureHalfFloatRender) {
  88246. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88247. }
  88248. else if (caps.textureFloatRender) {
  88249. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88250. }
  88251. }
  88252. else {
  88253. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88254. }
  88255. // Attach
  88256. scene.postProcessRenderPipelineManager.addPipeline(_this);
  88257. var engine = _this._scene.getEngine();
  88258. // Create post processes before hand so they can be modified before enabled.
  88259. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  88260. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  88261. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  88262. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  88263. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  88264. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  88265. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  88266. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  88267. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  88268. _this._resizeObserver = engine.onResizeObservable.add(function () {
  88269. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  88270. _this.bloomKernel = _this.bloomKernel;
  88271. });
  88272. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  88273. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  88274. });
  88275. _this._buildPipeline();
  88276. return _this;
  88277. }
  88278. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  88279. get: function () {
  88280. return this._sharpenEnabled;
  88281. },
  88282. /**
  88283. * Enable or disable the sharpen process from the pipeline
  88284. */
  88285. set: function (enabled) {
  88286. if (this._sharpenEnabled === enabled) {
  88287. return;
  88288. }
  88289. this._sharpenEnabled = enabled;
  88290. this._buildPipeline();
  88291. },
  88292. enumerable: true,
  88293. configurable: true
  88294. });
  88295. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  88296. /**
  88297. * Specifies the size of the bloom blur kernel, relative to the final output size
  88298. */
  88299. get: function () {
  88300. return this._bloomKernel;
  88301. },
  88302. set: function (value) {
  88303. this._bloomKernel = value;
  88304. this.bloom.kernel = value / this._hardwareScaleLevel;
  88305. },
  88306. enumerable: true,
  88307. configurable: true
  88308. });
  88309. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  88310. get: function () {
  88311. return this._bloomWeight;
  88312. },
  88313. /**
  88314. * The strength of the bloom.
  88315. */
  88316. set: function (value) {
  88317. if (this._bloomWeight === value) {
  88318. return;
  88319. }
  88320. this.bloom.weight = value;
  88321. this._bloomWeight = value;
  88322. },
  88323. enumerable: true,
  88324. configurable: true
  88325. });
  88326. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  88327. get: function () {
  88328. return this._bloomThreshold;
  88329. },
  88330. /**
  88331. * The strength of the bloom.
  88332. */
  88333. set: function (value) {
  88334. if (this._bloomThreshold === value) {
  88335. return;
  88336. }
  88337. this.bloom.threshold = value;
  88338. this._bloomThreshold = value;
  88339. },
  88340. enumerable: true,
  88341. configurable: true
  88342. });
  88343. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  88344. get: function () {
  88345. return this._bloomScale;
  88346. },
  88347. /**
  88348. * The scale of the bloom, lower value will provide better performance.
  88349. */
  88350. set: function (value) {
  88351. if (this._bloomScale === value) {
  88352. return;
  88353. }
  88354. this._bloomScale = value;
  88355. // recreate bloom and dispose old as this setting is not dynamic
  88356. this._rebuildBloom();
  88357. this._buildPipeline();
  88358. },
  88359. enumerable: true,
  88360. configurable: true
  88361. });
  88362. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  88363. get: function () {
  88364. return this._bloomEnabled;
  88365. },
  88366. /**
  88367. * Enable or disable the bloom from the pipeline
  88368. */
  88369. set: function (enabled) {
  88370. if (this._bloomEnabled === enabled) {
  88371. return;
  88372. }
  88373. this._bloomEnabled = enabled;
  88374. this._buildPipeline();
  88375. },
  88376. enumerable: true,
  88377. configurable: true
  88378. });
  88379. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  88380. // recreate bloom and dispose old as this setting is not dynamic
  88381. var oldBloom = this.bloom;
  88382. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  88383. this.bloom.threshold = oldBloom.threshold;
  88384. for (var i = 0; i < this._cameras.length; i++) {
  88385. oldBloom.disposeEffects(this._cameras[i]);
  88386. }
  88387. };
  88388. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  88389. /**
  88390. * If the depth of field is enabled.
  88391. */
  88392. get: function () {
  88393. return this._depthOfFieldEnabled;
  88394. },
  88395. set: function (enabled) {
  88396. if (this._depthOfFieldEnabled === enabled) {
  88397. return;
  88398. }
  88399. this._depthOfFieldEnabled = enabled;
  88400. this._buildPipeline();
  88401. },
  88402. enumerable: true,
  88403. configurable: true
  88404. });
  88405. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  88406. /**
  88407. * Blur level of the depth of field effect. (Higher blur will effect performance)
  88408. */
  88409. get: function () {
  88410. return this._depthOfFieldBlurLevel;
  88411. },
  88412. set: function (value) {
  88413. if (this._depthOfFieldBlurLevel === value) {
  88414. return;
  88415. }
  88416. this._depthOfFieldBlurLevel = value;
  88417. // recreate dof and dispose old as this setting is not dynamic
  88418. var oldDof = this.depthOfField;
  88419. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  88420. this.depthOfField.focalLength = oldDof.focalLength;
  88421. this.depthOfField.focusDistance = oldDof.focusDistance;
  88422. this.depthOfField.fStop = oldDof.fStop;
  88423. this.depthOfField.lensSize = oldDof.lensSize;
  88424. for (var i = 0; i < this._cameras.length; i++) {
  88425. oldDof.disposeEffects(this._cameras[i]);
  88426. }
  88427. this._buildPipeline();
  88428. },
  88429. enumerable: true,
  88430. configurable: true
  88431. });
  88432. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  88433. get: function () {
  88434. return this._fxaaEnabled;
  88435. },
  88436. /**
  88437. * If the anti aliasing is enabled.
  88438. */
  88439. set: function (enabled) {
  88440. if (this._fxaaEnabled === enabled) {
  88441. return;
  88442. }
  88443. this._fxaaEnabled = enabled;
  88444. this._buildPipeline();
  88445. },
  88446. enumerable: true,
  88447. configurable: true
  88448. });
  88449. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  88450. get: function () {
  88451. return this._samples;
  88452. },
  88453. /**
  88454. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  88455. */
  88456. set: function (sampleCount) {
  88457. if (this._samples === sampleCount) {
  88458. return;
  88459. }
  88460. this._samples = sampleCount;
  88461. this._buildPipeline();
  88462. },
  88463. enumerable: true,
  88464. configurable: true
  88465. });
  88466. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  88467. get: function () {
  88468. return this._imageProcessingEnabled;
  88469. },
  88470. /**
  88471. * If image processing is enabled.
  88472. */
  88473. set: function (enabled) {
  88474. if (this._imageProcessingEnabled === enabled) {
  88475. return;
  88476. }
  88477. this._imageProcessingEnabled = enabled;
  88478. this._buildPipeline();
  88479. },
  88480. enumerable: true,
  88481. configurable: true
  88482. });
  88483. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  88484. get: function () {
  88485. return this._glowLayer == null;
  88486. },
  88487. /**
  88488. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  88489. */
  88490. set: function (enabled) {
  88491. if (enabled && !this._glowLayer) {
  88492. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  88493. }
  88494. else if (!enabled && this._glowLayer) {
  88495. this._glowLayer.dispose();
  88496. this._glowLayer = null;
  88497. }
  88498. },
  88499. enumerable: true,
  88500. configurable: true
  88501. });
  88502. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  88503. get: function () {
  88504. return this._chromaticAberrationEnabled;
  88505. },
  88506. /**
  88507. * Enable or disable the chromaticAberration process from the pipeline
  88508. */
  88509. set: function (enabled) {
  88510. if (this._chromaticAberrationEnabled === enabled) {
  88511. return;
  88512. }
  88513. this._chromaticAberrationEnabled = enabled;
  88514. this._buildPipeline();
  88515. },
  88516. enumerable: true,
  88517. configurable: true
  88518. });
  88519. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  88520. get: function () {
  88521. return this._grainEnabled;
  88522. },
  88523. /**
  88524. * Enable or disable the grain process from the pipeline
  88525. */
  88526. set: function (enabled) {
  88527. if (this._grainEnabled === enabled) {
  88528. return;
  88529. }
  88530. this._grainEnabled = enabled;
  88531. this._buildPipeline();
  88532. },
  88533. enumerable: true,
  88534. configurable: true
  88535. });
  88536. /**
  88537. * Force the compilation of the entire pipeline.
  88538. */
  88539. DefaultRenderingPipeline.prototype.prepare = function () {
  88540. var previousState = this._buildAllowed;
  88541. this._buildAllowed = true;
  88542. this._buildPipeline();
  88543. this._buildAllowed = previousState;
  88544. };
  88545. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  88546. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  88547. if (this._hasCleared) {
  88548. postProcess.autoClear = false;
  88549. }
  88550. else {
  88551. postProcess.autoClear = true;
  88552. this._scene.autoClear = false;
  88553. this._hasCleared = true;
  88554. }
  88555. if (!skipTextureSharing) {
  88556. if (this._prevPrevPostProcess) {
  88557. postProcess.shareOutputWith(this._prevPrevPostProcess);
  88558. }
  88559. else {
  88560. postProcess.useOwnOutput();
  88561. }
  88562. if (this._prevPostProcess) {
  88563. this._prevPrevPostProcess = this._prevPostProcess;
  88564. }
  88565. this._prevPostProcess = postProcess;
  88566. }
  88567. };
  88568. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  88569. var _this = this;
  88570. if (!this._buildAllowed) {
  88571. return;
  88572. }
  88573. this._scene.autoClear = true;
  88574. var engine = this._scene.getEngine();
  88575. this._disposePostProcesses();
  88576. if (this._cameras !== null) {
  88577. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  88578. // get back cameras to be used to reattach pipeline
  88579. this._cameras = this._camerasToBeAttached.slice();
  88580. }
  88581. this._reset();
  88582. this._prevPostProcess = null;
  88583. this._prevPrevPostProcess = null;
  88584. this._hasCleared = false;
  88585. if (this.depthOfFieldEnabled) {
  88586. // Multi camera suport
  88587. if (this._cameras.length > 1) {
  88588. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  88589. var camera = _a[_i];
  88590. var depthRenderer = this._scene.enableDepthRenderer(camera);
  88591. depthRenderer.useOnlyInActiveCamera = true;
  88592. }
  88593. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  88594. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  88595. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  88596. }
  88597. });
  88598. }
  88599. else {
  88600. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  88601. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  88602. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  88603. }
  88604. if (!this.depthOfField._isReady()) {
  88605. this.depthOfField._updateEffects();
  88606. }
  88607. this.addEffect(this.depthOfField);
  88608. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  88609. }
  88610. else {
  88611. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  88612. }
  88613. if (this.bloomEnabled) {
  88614. if (!this.bloom._isReady()) {
  88615. this.bloom._updateEffects();
  88616. }
  88617. this.addEffect(this.bloom);
  88618. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  88619. }
  88620. if (this._imageProcessingEnabled) {
  88621. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  88622. if (this._hdr) {
  88623. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  88624. this._setAutoClearAndTextureSharing(this.imageProcessing);
  88625. }
  88626. else {
  88627. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  88628. }
  88629. }
  88630. if (this.sharpenEnabled) {
  88631. if (!this.sharpen.isReady()) {
  88632. this.sharpen.updateEffect();
  88633. }
  88634. this.addEffect(this._sharpenEffect);
  88635. this._setAutoClearAndTextureSharing(this.sharpen);
  88636. }
  88637. if (this.grainEnabled) {
  88638. if (!this.grain.isReady()) {
  88639. this.grain.updateEffect();
  88640. }
  88641. this.addEffect(this._grainEffect);
  88642. this._setAutoClearAndTextureSharing(this.grain);
  88643. }
  88644. if (this.chromaticAberrationEnabled) {
  88645. if (!this.chromaticAberration.isReady()) {
  88646. this.chromaticAberration.updateEffect();
  88647. }
  88648. this.addEffect(this._chromaticAberrationEffect);
  88649. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  88650. }
  88651. if (this.fxaaEnabled) {
  88652. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  88653. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  88654. this._setAutoClearAndTextureSharing(this.fxaa, true);
  88655. }
  88656. if (this._cameras !== null) {
  88657. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  88658. }
  88659. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  88660. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  88661. }
  88662. };
  88663. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  88664. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  88665. for (var i = 0; i < this._cameras.length; i++) {
  88666. var camera = this._cameras[i];
  88667. if (this.imageProcessing) {
  88668. this.imageProcessing.dispose(camera);
  88669. }
  88670. if (this.fxaa) {
  88671. this.fxaa.dispose(camera);
  88672. }
  88673. // These are created in the constructor and should not be disposed on every pipeline change
  88674. if (disposeNonRecreated) {
  88675. if (this.sharpen) {
  88676. this.sharpen.dispose(camera);
  88677. }
  88678. if (this.depthOfField) {
  88679. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  88680. this.depthOfField.disposeEffects(camera);
  88681. }
  88682. if (this.bloom) {
  88683. this.bloom.disposeEffects(camera);
  88684. }
  88685. if (this.chromaticAberration) {
  88686. this.chromaticAberration.dispose(camera);
  88687. }
  88688. if (this.grain) {
  88689. this.grain.dispose(camera);
  88690. }
  88691. if (this._glowLayer) {
  88692. this._glowLayer.dispose();
  88693. }
  88694. }
  88695. }
  88696. this.imageProcessing = null;
  88697. this.fxaa = null;
  88698. if (disposeNonRecreated) {
  88699. this.sharpen = null;
  88700. this._sharpenEffect = null;
  88701. this.depthOfField = null;
  88702. this.bloom = null;
  88703. this.chromaticAberration = null;
  88704. this._chromaticAberrationEffect = null;
  88705. this.grain = null;
  88706. this._grainEffect = null;
  88707. this._glowLayer = null;
  88708. }
  88709. };
  88710. /**
  88711. * Adds a camera to the pipeline
  88712. * @param camera the camera to be added
  88713. */
  88714. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  88715. this._camerasToBeAttached.push(camera);
  88716. this._buildPipeline();
  88717. };
  88718. /**
  88719. * Removes a camera from the pipeline
  88720. * @param camera the camera to remove
  88721. */
  88722. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  88723. var index = this._camerasToBeAttached.indexOf(camera);
  88724. this._camerasToBeAttached.splice(index, 1);
  88725. this._buildPipeline();
  88726. };
  88727. /**
  88728. * Dispose of the pipeline and stop all post processes
  88729. */
  88730. DefaultRenderingPipeline.prototype.dispose = function () {
  88731. this._disposePostProcesses(true);
  88732. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  88733. this._scene.autoClear = true;
  88734. if (this._resizeObserver) {
  88735. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  88736. this._resizeObserver = null;
  88737. }
  88738. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  88739. _super.prototype.dispose.call(this);
  88740. };
  88741. /**
  88742. * Serialize the rendering pipeline (Used when exporting)
  88743. * @returns the serialized object
  88744. */
  88745. DefaultRenderingPipeline.prototype.serialize = function () {
  88746. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  88747. serializationObject.customType = "DefaultRenderingPipeline";
  88748. return serializationObject;
  88749. };
  88750. /**
  88751. * Parse the serialized pipeline
  88752. * @param source Source pipeline.
  88753. * @param scene The scene to load the pipeline to.
  88754. * @param rootUrl The URL of the serialized pipeline.
  88755. * @returns An instantiated pipeline from the serialized object.
  88756. */
  88757. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  88758. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  88759. };
  88760. __decorate([
  88761. BABYLON.serialize()
  88762. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  88763. __decorate([
  88764. BABYLON.serialize()
  88765. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  88766. __decorate([
  88767. BABYLON.serialize()
  88768. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  88769. __decorate([
  88770. BABYLON.serialize()
  88771. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  88772. __decorate([
  88773. BABYLON.serialize()
  88774. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  88775. __decorate([
  88776. BABYLON.serialize()
  88777. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  88778. __decorate([
  88779. BABYLON.serialize()
  88780. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  88781. __decorate([
  88782. BABYLON.serialize()
  88783. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  88784. __decorate([
  88785. BABYLON.serialize()
  88786. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  88787. __decorate([
  88788. BABYLON.serialize()
  88789. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  88790. __decorate([
  88791. BABYLON.serialize()
  88792. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  88793. __decorate([
  88794. BABYLON.serialize()
  88795. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  88796. __decorate([
  88797. BABYLON.serialize()
  88798. ], DefaultRenderingPipeline.prototype, "samples", null);
  88799. __decorate([
  88800. BABYLON.serialize()
  88801. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  88802. __decorate([
  88803. BABYLON.serialize()
  88804. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  88805. __decorate([
  88806. BABYLON.serialize()
  88807. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  88808. __decorate([
  88809. BABYLON.serialize()
  88810. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  88811. return DefaultRenderingPipeline;
  88812. }(BABYLON.PostProcessRenderPipeline));
  88813. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  88814. })(BABYLON || (BABYLON = {}));
  88815. //# sourceMappingURL=defaultRenderingPipeline.js.map
  88816. var BABYLON;
  88817. (function (BABYLON) {
  88818. /**
  88819. * @hidden
  88820. */
  88821. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  88822. __extends(ImageProcessingConfigurationDefines, _super);
  88823. function ImageProcessingConfigurationDefines() {
  88824. var _this = _super.call(this) || this;
  88825. _this.IMAGEPROCESSING = false;
  88826. _this.VIGNETTE = false;
  88827. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  88828. _this.VIGNETTEBLENDMODEOPAQUE = false;
  88829. _this.TONEMAPPING = false;
  88830. _this.TONEMAPPING_ACES = false;
  88831. _this.CONTRAST = false;
  88832. _this.COLORCURVES = false;
  88833. _this.COLORGRADING = false;
  88834. _this.COLORGRADING3D = false;
  88835. _this.SAMPLER3DGREENDEPTH = false;
  88836. _this.SAMPLER3DBGRMAP = false;
  88837. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  88838. _this.EXPOSURE = false;
  88839. _this.rebuild();
  88840. return _this;
  88841. }
  88842. return ImageProcessingConfigurationDefines;
  88843. }(BABYLON.MaterialDefines));
  88844. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  88845. /**
  88846. * This groups together the common properties used for image processing either in direct forward pass
  88847. * or through post processing effect depending on the use of the image processing pipeline in your scene
  88848. * or not.
  88849. */
  88850. var ImageProcessingConfiguration = /** @class */ (function () {
  88851. function ImageProcessingConfiguration() {
  88852. /**
  88853. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  88854. */
  88855. this.colorCurves = new BABYLON.ColorCurves();
  88856. this._colorCurvesEnabled = false;
  88857. this._colorGradingEnabled = false;
  88858. this._colorGradingWithGreenDepth = true;
  88859. this._colorGradingBGR = true;
  88860. /** @hidden */
  88861. this._exposure = 1.0;
  88862. this._toneMappingEnabled = false;
  88863. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  88864. this._contrast = 1.0;
  88865. /**
  88866. * Vignette stretch size.
  88867. */
  88868. this.vignetteStretch = 0;
  88869. /**
  88870. * Vignette centre X Offset.
  88871. */
  88872. this.vignetteCentreX = 0;
  88873. /**
  88874. * Vignette centre Y Offset.
  88875. */
  88876. this.vignetteCentreY = 0;
  88877. /**
  88878. * Vignette weight or intensity of the vignette effect.
  88879. */
  88880. this.vignetteWeight = 1.5;
  88881. /**
  88882. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  88883. * if vignetteEnabled is set to true.
  88884. */
  88885. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88886. /**
  88887. * Camera field of view used by the Vignette effect.
  88888. */
  88889. this.vignetteCameraFov = 0.5;
  88890. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  88891. this._vignetteEnabled = false;
  88892. this._applyByPostProcess = false;
  88893. this._isEnabled = true;
  88894. /**
  88895. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  88896. */
  88897. this.onUpdateParameters = new BABYLON.Observable();
  88898. }
  88899. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  88900. /**
  88901. * Gets wether the color curves effect is enabled.
  88902. */
  88903. get: function () {
  88904. return this._colorCurvesEnabled;
  88905. },
  88906. /**
  88907. * Sets wether the color curves effect is enabled.
  88908. */
  88909. set: function (value) {
  88910. if (this._colorCurvesEnabled === value) {
  88911. return;
  88912. }
  88913. this._colorCurvesEnabled = value;
  88914. this._updateParameters();
  88915. },
  88916. enumerable: true,
  88917. configurable: true
  88918. });
  88919. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingTexture", {
  88920. /**
  88921. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  88922. */
  88923. get: function () {
  88924. return this._colorGradingTexture;
  88925. },
  88926. /**
  88927. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  88928. */
  88929. set: function (value) {
  88930. if (this._colorGradingTexture === value) {
  88931. return;
  88932. }
  88933. this._colorGradingTexture = value;
  88934. this._updateParameters();
  88935. },
  88936. enumerable: true,
  88937. configurable: true
  88938. });
  88939. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  88940. /**
  88941. * Gets wether the color grading effect is enabled.
  88942. */
  88943. get: function () {
  88944. return this._colorGradingEnabled;
  88945. },
  88946. /**
  88947. * Sets wether the color grading effect is enabled.
  88948. */
  88949. set: function (value) {
  88950. if (this._colorGradingEnabled === value) {
  88951. return;
  88952. }
  88953. this._colorGradingEnabled = value;
  88954. this._updateParameters();
  88955. },
  88956. enumerable: true,
  88957. configurable: true
  88958. });
  88959. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  88960. /**
  88961. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  88962. */
  88963. get: function () {
  88964. return this._colorGradingWithGreenDepth;
  88965. },
  88966. /**
  88967. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  88968. */
  88969. set: function (value) {
  88970. if (this._colorGradingWithGreenDepth === value) {
  88971. return;
  88972. }
  88973. this._colorGradingWithGreenDepth = value;
  88974. this._updateParameters();
  88975. },
  88976. enumerable: true,
  88977. configurable: true
  88978. });
  88979. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  88980. /**
  88981. * Gets wether the color grading texture contains BGR values.
  88982. */
  88983. get: function () {
  88984. return this._colorGradingBGR;
  88985. },
  88986. /**
  88987. * Sets wether the color grading texture contains BGR values.
  88988. */
  88989. set: function (value) {
  88990. if (this._colorGradingBGR === value) {
  88991. return;
  88992. }
  88993. this._colorGradingBGR = value;
  88994. this._updateParameters();
  88995. },
  88996. enumerable: true,
  88997. configurable: true
  88998. });
  88999. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  89000. /**
  89001. * Gets the Exposure used in the effect.
  89002. */
  89003. get: function () {
  89004. return this._exposure;
  89005. },
  89006. /**
  89007. * Sets the Exposure used in the effect.
  89008. */
  89009. set: function (value) {
  89010. if (this._exposure === value) {
  89011. return;
  89012. }
  89013. this._exposure = value;
  89014. this._updateParameters();
  89015. },
  89016. enumerable: true,
  89017. configurable: true
  89018. });
  89019. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  89020. /**
  89021. * Gets wether the tone mapping effect is enabled.
  89022. */
  89023. get: function () {
  89024. return this._toneMappingEnabled;
  89025. },
  89026. /**
  89027. * Sets wether the tone mapping effect is enabled.
  89028. */
  89029. set: function (value) {
  89030. if (this._toneMappingEnabled === value) {
  89031. return;
  89032. }
  89033. this._toneMappingEnabled = value;
  89034. this._updateParameters();
  89035. },
  89036. enumerable: true,
  89037. configurable: true
  89038. });
  89039. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  89040. /**
  89041. * Gets the type of tone mapping effect.
  89042. */
  89043. get: function () {
  89044. return this._toneMappingType;
  89045. },
  89046. /**
  89047. * Sets the type of tone mapping effect used in BabylonJS.
  89048. */
  89049. set: function (value) {
  89050. if (this._toneMappingType === value) {
  89051. return;
  89052. }
  89053. this._toneMappingType = value;
  89054. this._updateParameters();
  89055. },
  89056. enumerable: true,
  89057. configurable: true
  89058. });
  89059. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  89060. /**
  89061. * Gets the contrast used in the effect.
  89062. */
  89063. get: function () {
  89064. return this._contrast;
  89065. },
  89066. /**
  89067. * Sets the contrast used in the effect.
  89068. */
  89069. set: function (value) {
  89070. if (this._contrast === value) {
  89071. return;
  89072. }
  89073. this._contrast = value;
  89074. this._updateParameters();
  89075. },
  89076. enumerable: true,
  89077. configurable: true
  89078. });
  89079. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  89080. /**
  89081. * Gets the vignette blend mode allowing different kind of effect.
  89082. */
  89083. get: function () {
  89084. return this._vignetteBlendMode;
  89085. },
  89086. /**
  89087. * Sets the vignette blend mode allowing different kind of effect.
  89088. */
  89089. set: function (value) {
  89090. if (this._vignetteBlendMode === value) {
  89091. return;
  89092. }
  89093. this._vignetteBlendMode = value;
  89094. this._updateParameters();
  89095. },
  89096. enumerable: true,
  89097. configurable: true
  89098. });
  89099. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  89100. /**
  89101. * Gets wether the vignette effect is enabled.
  89102. */
  89103. get: function () {
  89104. return this._vignetteEnabled;
  89105. },
  89106. /**
  89107. * Sets wether the vignette effect is enabled.
  89108. */
  89109. set: function (value) {
  89110. if (this._vignetteEnabled === value) {
  89111. return;
  89112. }
  89113. this._vignetteEnabled = value;
  89114. this._updateParameters();
  89115. },
  89116. enumerable: true,
  89117. configurable: true
  89118. });
  89119. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  89120. /**
  89121. * Gets wether the image processing is applied through a post process or not.
  89122. */
  89123. get: function () {
  89124. return this._applyByPostProcess;
  89125. },
  89126. /**
  89127. * Sets wether the image processing is applied through a post process or not.
  89128. */
  89129. set: function (value) {
  89130. if (this._applyByPostProcess === value) {
  89131. return;
  89132. }
  89133. this._applyByPostProcess = value;
  89134. this._updateParameters();
  89135. },
  89136. enumerable: true,
  89137. configurable: true
  89138. });
  89139. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  89140. /**
  89141. * Gets wether the image processing is enabled or not.
  89142. */
  89143. get: function () {
  89144. return this._isEnabled;
  89145. },
  89146. /**
  89147. * Sets wether the image processing is enabled or not.
  89148. */
  89149. set: function (value) {
  89150. if (this._isEnabled === value) {
  89151. return;
  89152. }
  89153. this._isEnabled = value;
  89154. this._updateParameters();
  89155. },
  89156. enumerable: true,
  89157. configurable: true
  89158. });
  89159. /**
  89160. * Method called each time the image processing information changes requires to recompile the effect.
  89161. */
  89162. ImageProcessingConfiguration.prototype._updateParameters = function () {
  89163. this.onUpdateParameters.notifyObservers(this);
  89164. };
  89165. /**
  89166. * Gets the current class name.
  89167. * @return "ImageProcessingConfiguration"
  89168. */
  89169. ImageProcessingConfiguration.prototype.getClassName = function () {
  89170. return "ImageProcessingConfiguration";
  89171. };
  89172. /**
  89173. * Prepare the list of uniforms associated with the Image Processing effects.
  89174. * @param uniforms The list of uniforms used in the effect
  89175. * @param defines the list of defines currently in use
  89176. */
  89177. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  89178. if (defines.EXPOSURE) {
  89179. uniforms.push("exposureLinear");
  89180. }
  89181. if (defines.CONTRAST) {
  89182. uniforms.push("contrast");
  89183. }
  89184. if (defines.COLORGRADING) {
  89185. uniforms.push("colorTransformSettings");
  89186. }
  89187. if (defines.VIGNETTE) {
  89188. uniforms.push("vInverseScreenSize");
  89189. uniforms.push("vignetteSettings1");
  89190. uniforms.push("vignetteSettings2");
  89191. }
  89192. if (defines.COLORCURVES) {
  89193. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  89194. }
  89195. };
  89196. /**
  89197. * Prepare the list of samplers associated with the Image Processing effects.
  89198. * @param samplersList The list of uniforms used in the effect
  89199. * @param defines the list of defines currently in use
  89200. */
  89201. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  89202. if (defines.COLORGRADING) {
  89203. samplersList.push("txColorTransform");
  89204. }
  89205. };
  89206. /**
  89207. * Prepare the list of defines associated to the shader.
  89208. * @param defines the list of defines to complete
  89209. * @param forPostProcess Define if we are currently in post process mode or not
  89210. */
  89211. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  89212. if (forPostProcess === void 0) { forPostProcess = false; }
  89213. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  89214. defines.VIGNETTE = false;
  89215. defines.TONEMAPPING = false;
  89216. defines.TONEMAPPING_ACES = false;
  89217. defines.CONTRAST = false;
  89218. defines.EXPOSURE = false;
  89219. defines.COLORCURVES = false;
  89220. defines.COLORGRADING = false;
  89221. defines.COLORGRADING3D = false;
  89222. defines.IMAGEPROCESSING = false;
  89223. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  89224. return;
  89225. }
  89226. defines.VIGNETTE = this.vignetteEnabled;
  89227. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  89228. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  89229. defines.TONEMAPPING = this.toneMappingEnabled;
  89230. switch (this._toneMappingType) {
  89231. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  89232. defines.TONEMAPPING_ACES = true;
  89233. break;
  89234. }
  89235. defines.CONTRAST = (this.contrast !== 1.0);
  89236. defines.EXPOSURE = (this.exposure !== 1.0);
  89237. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  89238. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  89239. if (defines.COLORGRADING) {
  89240. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  89241. }
  89242. else {
  89243. defines.COLORGRADING3D = false;
  89244. }
  89245. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  89246. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  89247. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  89248. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  89249. };
  89250. /**
  89251. * Returns true if all the image processing information are ready.
  89252. * @returns True if ready, otherwise, false
  89253. */
  89254. ImageProcessingConfiguration.prototype.isReady = function () {
  89255. // Color Grading texure can not be none blocking.
  89256. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  89257. };
  89258. /**
  89259. * Binds the image processing to the shader.
  89260. * @param effect The effect to bind to
  89261. * @param aspectRatio Define the current aspect ratio of the effect
  89262. */
  89263. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  89264. if (aspectRatio === void 0) { aspectRatio = 1; }
  89265. // Color Curves
  89266. if (this._colorCurvesEnabled && this.colorCurves) {
  89267. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  89268. }
  89269. // Vignette
  89270. if (this._vignetteEnabled) {
  89271. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  89272. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  89273. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  89274. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  89275. var vignetteScaleX = vignetteScaleY * aspectRatio;
  89276. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  89277. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  89278. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  89279. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  89280. var vignettePower = -2.0 * this.vignetteWeight;
  89281. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  89282. }
  89283. // Exposure
  89284. effect.setFloat("exposureLinear", this.exposure);
  89285. // Contrast
  89286. effect.setFloat("contrast", this.contrast);
  89287. // Color transform settings
  89288. if (this.colorGradingTexture) {
  89289. effect.setTexture("txColorTransform", this.colorGradingTexture);
  89290. var textureSize = this.colorGradingTexture.getSize().height;
  89291. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  89292. 0.5 / textureSize, // textureOffset
  89293. textureSize, // textureSize
  89294. this.colorGradingTexture.level // weight
  89295. );
  89296. }
  89297. };
  89298. /**
  89299. * Clones the current image processing instance.
  89300. * @return The cloned image processing
  89301. */
  89302. ImageProcessingConfiguration.prototype.clone = function () {
  89303. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  89304. };
  89305. /**
  89306. * Serializes the current image processing instance to a json representation.
  89307. * @return a JSON representation
  89308. */
  89309. ImageProcessingConfiguration.prototype.serialize = function () {
  89310. return BABYLON.SerializationHelper.Serialize(this);
  89311. };
  89312. /**
  89313. * Parses the image processing from a json representation.
  89314. * @param source the JSON source to parse
  89315. * @return The parsed image processing
  89316. */
  89317. ImageProcessingConfiguration.Parse = function (source) {
  89318. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  89319. };
  89320. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  89321. /**
  89322. * Used to apply the vignette as a mix with the pixel color.
  89323. */
  89324. get: function () {
  89325. return this._VIGNETTEMODE_MULTIPLY;
  89326. },
  89327. enumerable: true,
  89328. configurable: true
  89329. });
  89330. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  89331. /**
  89332. * Used to apply the vignette as a replacement of the pixel color.
  89333. */
  89334. get: function () {
  89335. return this._VIGNETTEMODE_OPAQUE;
  89336. },
  89337. enumerable: true,
  89338. configurable: true
  89339. });
  89340. /**
  89341. * Default tone mapping applied in BabylonJS.
  89342. */
  89343. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  89344. /**
  89345. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  89346. * to other engines rendering to increase portability.
  89347. */
  89348. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  89349. // Static constants associated to the image processing.
  89350. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  89351. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  89352. __decorate([
  89353. BABYLON.serializeAsColorCurves()
  89354. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  89355. __decorate([
  89356. BABYLON.serialize()
  89357. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  89358. __decorate([
  89359. BABYLON.serializeAsTexture("colorGradingTexture")
  89360. ], ImageProcessingConfiguration.prototype, "_colorGradingTexture", void 0);
  89361. __decorate([
  89362. BABYLON.serialize()
  89363. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  89364. __decorate([
  89365. BABYLON.serialize()
  89366. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  89367. __decorate([
  89368. BABYLON.serialize()
  89369. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  89370. __decorate([
  89371. BABYLON.serialize()
  89372. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  89373. __decorate([
  89374. BABYLON.serialize()
  89375. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  89376. __decorate([
  89377. BABYLON.serialize()
  89378. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  89379. __decorate([
  89380. BABYLON.serialize()
  89381. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  89382. __decorate([
  89383. BABYLON.serialize()
  89384. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  89385. __decorate([
  89386. BABYLON.serialize()
  89387. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  89388. __decorate([
  89389. BABYLON.serialize()
  89390. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  89391. __decorate([
  89392. BABYLON.serialize()
  89393. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  89394. __decorate([
  89395. BABYLON.serializeAsColor4()
  89396. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  89397. __decorate([
  89398. BABYLON.serialize()
  89399. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  89400. __decorate([
  89401. BABYLON.serialize()
  89402. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  89403. __decorate([
  89404. BABYLON.serialize()
  89405. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  89406. __decorate([
  89407. BABYLON.serialize()
  89408. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  89409. __decorate([
  89410. BABYLON.serialize()
  89411. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  89412. return ImageProcessingConfiguration;
  89413. }());
  89414. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  89415. })(BABYLON || (BABYLON = {}));
  89416. //# sourceMappingURL=imageProcessingConfiguration.js.map
  89417. var BABYLON;
  89418. (function (BABYLON) {
  89419. /**
  89420. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  89421. * It can help converting any input color in a desired output one. This can then be used to create effects
  89422. * from sepia, black and white to sixties or futuristic rendering...
  89423. *
  89424. * The only supported format is currently 3dl.
  89425. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table
  89426. */
  89427. var ColorGradingTexture = /** @class */ (function (_super) {
  89428. __extends(ColorGradingTexture, _super);
  89429. /**
  89430. * Instantiates a ColorGradingTexture from the following parameters.
  89431. *
  89432. * @param url The location of the color gradind data (currently only supporting 3dl)
  89433. * @param scene The scene the texture will be used in
  89434. */
  89435. function ColorGradingTexture(url, scene) {
  89436. var _this = _super.call(this, scene) || this;
  89437. if (!url) {
  89438. return _this;
  89439. }
  89440. _this._engine = scene.getEngine();
  89441. _this._textureMatrix = BABYLON.Matrix.Identity();
  89442. _this.name = url;
  89443. _this.url = url;
  89444. _this.hasAlpha = false;
  89445. _this.isCube = false;
  89446. _this.is3D = _this._engine.webGLVersion > 1;
  89447. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89448. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89449. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89450. _this.anisotropicFilteringLevel = 1;
  89451. _this._texture = _this._getFromCache(url, true);
  89452. if (!_this._texture) {
  89453. if (!scene.useDelayedTextureLoading) {
  89454. _this.loadTexture();
  89455. }
  89456. else {
  89457. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  89458. }
  89459. }
  89460. return _this;
  89461. }
  89462. /**
  89463. * Returns the texture matrix used in most of the material.
  89464. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  89465. */
  89466. ColorGradingTexture.prototype.getTextureMatrix = function () {
  89467. return this._textureMatrix;
  89468. };
  89469. /**
  89470. * Occurs when the file being loaded is a .3dl LUT file.
  89471. */
  89472. ColorGradingTexture.prototype.load3dlTexture = function () {
  89473. var engine = this._engine;
  89474. var texture;
  89475. if (engine.webGLVersion === 1) {
  89476. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89477. }
  89478. else {
  89479. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89480. }
  89481. this._texture = texture;
  89482. var callback = function (text) {
  89483. if (typeof text !== "string") {
  89484. return;
  89485. }
  89486. var data = null;
  89487. var tempData = null;
  89488. var line;
  89489. var lines = text.split('\n');
  89490. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  89491. var maxColor = 0;
  89492. for (var i = 0; i < lines.length; i++) {
  89493. line = lines[i];
  89494. if (!ColorGradingTexture._noneEmptyLineRegex.test(line)) {
  89495. continue;
  89496. }
  89497. if (line.indexOf('#') === 0) {
  89498. continue;
  89499. }
  89500. var words = line.split(" ");
  89501. if (size === 0) {
  89502. // Number of space + one
  89503. size = words.length;
  89504. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  89505. tempData = new Float32Array(size * size * size * 4);
  89506. continue;
  89507. }
  89508. if (size != 0) {
  89509. var r = Math.max(parseInt(words[0]), 0);
  89510. var g = Math.max(parseInt(words[1]), 0);
  89511. var b = Math.max(parseInt(words[2]), 0);
  89512. maxColor = Math.max(r, maxColor);
  89513. maxColor = Math.max(g, maxColor);
  89514. maxColor = Math.max(b, maxColor);
  89515. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  89516. if (tempData) {
  89517. tempData[pixelStorageIndex + 0] = r;
  89518. tempData[pixelStorageIndex + 1] = g;
  89519. tempData[pixelStorageIndex + 2] = b;
  89520. }
  89521. // Keep for reference in case of back compat problems.
  89522. // pixelIndexSlice++;
  89523. // if (pixelIndexSlice % size == 0) {
  89524. // pixelIndexH++;
  89525. // pixelIndexSlice = 0;
  89526. // if (pixelIndexH % size == 0) {
  89527. // pixelIndexW++;
  89528. // pixelIndexH = 0;
  89529. // }
  89530. // }
  89531. pixelIndexH++;
  89532. if (pixelIndexH % size == 0) {
  89533. pixelIndexSlice++;
  89534. pixelIndexH = 0;
  89535. if (pixelIndexSlice % size == 0) {
  89536. pixelIndexW++;
  89537. pixelIndexSlice = 0;
  89538. }
  89539. }
  89540. }
  89541. }
  89542. if (tempData && data) {
  89543. for (var i = 0; i < tempData.length; i++) {
  89544. if (i > 0 && (i + 1) % 4 === 0) {
  89545. data[i] = 255;
  89546. }
  89547. else {
  89548. var value = tempData[i];
  89549. data[i] = (value / maxColor * 255);
  89550. }
  89551. }
  89552. }
  89553. if (texture.is3D) {
  89554. texture.updateSize(size, size, size);
  89555. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  89556. }
  89557. else {
  89558. texture.updateSize(size * size, size);
  89559. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  89560. }
  89561. };
  89562. var scene = this.getScene();
  89563. if (scene) {
  89564. scene._loadFile(this.url, callback);
  89565. }
  89566. else {
  89567. this._engine._loadFile(this.url, callback);
  89568. }
  89569. return this._texture;
  89570. };
  89571. /**
  89572. * Starts the loading process of the texture.
  89573. */
  89574. ColorGradingTexture.prototype.loadTexture = function () {
  89575. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  89576. this.load3dlTexture();
  89577. }
  89578. };
  89579. /**
  89580. * Clones the color gradind texture.
  89581. */
  89582. ColorGradingTexture.prototype.clone = function () {
  89583. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  89584. // Base texture
  89585. newTexture.level = this.level;
  89586. return newTexture;
  89587. };
  89588. /**
  89589. * Called during delayed load for textures.
  89590. */
  89591. ColorGradingTexture.prototype.delayLoad = function () {
  89592. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  89593. return;
  89594. }
  89595. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  89596. this._texture = this._getFromCache(this.url, true);
  89597. if (!this._texture) {
  89598. this.loadTexture();
  89599. }
  89600. };
  89601. /**
  89602. * Parses a color grading texture serialized by Babylon.
  89603. * @param parsedTexture The texture information being parsedTexture
  89604. * @param scene The scene to load the texture in
  89605. * @param rootUrl The root url of the data assets to load
  89606. * @return A color gradind texture
  89607. */
  89608. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  89609. var texture = null;
  89610. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  89611. texture = new ColorGradingTexture(parsedTexture.name, scene);
  89612. texture.name = parsedTexture.name;
  89613. texture.level = parsedTexture.level;
  89614. }
  89615. return texture;
  89616. };
  89617. /**
  89618. * Serializes the LUT texture to json format.
  89619. */
  89620. ColorGradingTexture.prototype.serialize = function () {
  89621. if (!this.name) {
  89622. return null;
  89623. }
  89624. var serializationObject = {};
  89625. serializationObject.name = this.name;
  89626. serializationObject.level = this.level;
  89627. serializationObject.customType = "BABYLON.ColorGradingTexture";
  89628. return serializationObject;
  89629. };
  89630. /**
  89631. * Empty line regex stored for GC.
  89632. */
  89633. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  89634. return ColorGradingTexture;
  89635. }(BABYLON.BaseTexture));
  89636. BABYLON.ColorGradingTexture = ColorGradingTexture;
  89637. })(BABYLON || (BABYLON = {}));
  89638. //# sourceMappingURL=colorGradingTexture.js.map
  89639. var BABYLON;
  89640. (function (BABYLON) {
  89641. /**
  89642. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  89643. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  89644. * 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;
  89645. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  89646. */
  89647. var ColorCurves = /** @class */ (function () {
  89648. function ColorCurves() {
  89649. this._dirty = true;
  89650. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  89651. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  89652. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  89653. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  89654. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  89655. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  89656. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  89657. this._globalHue = 30;
  89658. this._globalDensity = 0;
  89659. this._globalSaturation = 0;
  89660. this._globalExposure = 0;
  89661. this._highlightsHue = 30;
  89662. this._highlightsDensity = 0;
  89663. this._highlightsSaturation = 0;
  89664. this._highlightsExposure = 0;
  89665. this._midtonesHue = 30;
  89666. this._midtonesDensity = 0;
  89667. this._midtonesSaturation = 0;
  89668. this._midtonesExposure = 0;
  89669. this._shadowsHue = 30;
  89670. this._shadowsDensity = 0;
  89671. this._shadowsSaturation = 0;
  89672. this._shadowsExposure = 0;
  89673. }
  89674. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  89675. /**
  89676. * Gets the global Hue value.
  89677. * 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).
  89678. */
  89679. get: function () {
  89680. return this._globalHue;
  89681. },
  89682. /**
  89683. * Sets the global Hue value.
  89684. * 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).
  89685. */
  89686. set: function (value) {
  89687. this._globalHue = value;
  89688. this._dirty = true;
  89689. },
  89690. enumerable: true,
  89691. configurable: true
  89692. });
  89693. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  89694. /**
  89695. * Gets the global Density value.
  89696. * 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.
  89697. * Values less than zero provide a filter of opposite hue.
  89698. */
  89699. get: function () {
  89700. return this._globalDensity;
  89701. },
  89702. /**
  89703. * Sets the global Density value.
  89704. * 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.
  89705. * Values less than zero provide a filter of opposite hue.
  89706. */
  89707. set: function (value) {
  89708. this._globalDensity = value;
  89709. this._dirty = true;
  89710. },
  89711. enumerable: true,
  89712. configurable: true
  89713. });
  89714. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  89715. /**
  89716. * Gets the global Saturation value.
  89717. * 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.
  89718. */
  89719. get: function () {
  89720. return this._globalSaturation;
  89721. },
  89722. /**
  89723. * Sets the global Saturation value.
  89724. * 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.
  89725. */
  89726. set: function (value) {
  89727. this._globalSaturation = value;
  89728. this._dirty = true;
  89729. },
  89730. enumerable: true,
  89731. configurable: true
  89732. });
  89733. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  89734. /**
  89735. * Gets the global Exposure value.
  89736. * 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.
  89737. */
  89738. get: function () {
  89739. return this._globalExposure;
  89740. },
  89741. /**
  89742. * Sets the global Exposure value.
  89743. * 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.
  89744. */
  89745. set: function (value) {
  89746. this._globalExposure = value;
  89747. this._dirty = true;
  89748. },
  89749. enumerable: true,
  89750. configurable: true
  89751. });
  89752. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  89753. /**
  89754. * Gets the highlights Hue value.
  89755. * 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).
  89756. */
  89757. get: function () {
  89758. return this._highlightsHue;
  89759. },
  89760. /**
  89761. * Sets the highlights Hue value.
  89762. * 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).
  89763. */
  89764. set: function (value) {
  89765. this._highlightsHue = value;
  89766. this._dirty = true;
  89767. },
  89768. enumerable: true,
  89769. configurable: true
  89770. });
  89771. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  89772. /**
  89773. * Gets the highlights Density value.
  89774. * 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.
  89775. * Values less than zero provide a filter of opposite hue.
  89776. */
  89777. get: function () {
  89778. return this._highlightsDensity;
  89779. },
  89780. /**
  89781. * Sets the highlights Density value.
  89782. * 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.
  89783. * Values less than zero provide a filter of opposite hue.
  89784. */
  89785. set: function (value) {
  89786. this._highlightsDensity = value;
  89787. this._dirty = true;
  89788. },
  89789. enumerable: true,
  89790. configurable: true
  89791. });
  89792. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  89793. /**
  89794. * Gets the highlights Saturation value.
  89795. * 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.
  89796. */
  89797. get: function () {
  89798. return this._highlightsSaturation;
  89799. },
  89800. /**
  89801. * Sets the highlights Saturation value.
  89802. * 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.
  89803. */
  89804. set: function (value) {
  89805. this._highlightsSaturation = value;
  89806. this._dirty = true;
  89807. },
  89808. enumerable: true,
  89809. configurable: true
  89810. });
  89811. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  89812. /**
  89813. * Gets the highlights Exposure value.
  89814. * 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.
  89815. */
  89816. get: function () {
  89817. return this._highlightsExposure;
  89818. },
  89819. /**
  89820. * Sets the highlights Exposure value.
  89821. * 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.
  89822. */
  89823. set: function (value) {
  89824. this._highlightsExposure = value;
  89825. this._dirty = true;
  89826. },
  89827. enumerable: true,
  89828. configurable: true
  89829. });
  89830. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  89831. /**
  89832. * Gets the midtones Hue value.
  89833. * 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).
  89834. */
  89835. get: function () {
  89836. return this._midtonesHue;
  89837. },
  89838. /**
  89839. * Sets the midtones Hue value.
  89840. * 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).
  89841. */
  89842. set: function (value) {
  89843. this._midtonesHue = value;
  89844. this._dirty = true;
  89845. },
  89846. enumerable: true,
  89847. configurable: true
  89848. });
  89849. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  89850. /**
  89851. * Gets the midtones Density value.
  89852. * 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.
  89853. * Values less than zero provide a filter of opposite hue.
  89854. */
  89855. get: function () {
  89856. return this._midtonesDensity;
  89857. },
  89858. /**
  89859. * Sets the midtones Density value.
  89860. * 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.
  89861. * Values less than zero provide a filter of opposite hue.
  89862. */
  89863. set: function (value) {
  89864. this._midtonesDensity = value;
  89865. this._dirty = true;
  89866. },
  89867. enumerable: true,
  89868. configurable: true
  89869. });
  89870. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  89871. /**
  89872. * Gets the midtones Saturation value.
  89873. * 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.
  89874. */
  89875. get: function () {
  89876. return this._midtonesSaturation;
  89877. },
  89878. /**
  89879. * Sets the midtones Saturation value.
  89880. * 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.
  89881. */
  89882. set: function (value) {
  89883. this._midtonesSaturation = value;
  89884. this._dirty = true;
  89885. },
  89886. enumerable: true,
  89887. configurable: true
  89888. });
  89889. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  89890. /**
  89891. * Gets the midtones Exposure value.
  89892. * 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.
  89893. */
  89894. get: function () {
  89895. return this._midtonesExposure;
  89896. },
  89897. /**
  89898. * Sets the midtones Exposure value.
  89899. * 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.
  89900. */
  89901. set: function (value) {
  89902. this._midtonesExposure = value;
  89903. this._dirty = true;
  89904. },
  89905. enumerable: true,
  89906. configurable: true
  89907. });
  89908. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  89909. /**
  89910. * Gets the shadows Hue value.
  89911. * 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).
  89912. */
  89913. get: function () {
  89914. return this._shadowsHue;
  89915. },
  89916. /**
  89917. * Sets the shadows Hue value.
  89918. * 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).
  89919. */
  89920. set: function (value) {
  89921. this._shadowsHue = value;
  89922. this._dirty = true;
  89923. },
  89924. enumerable: true,
  89925. configurable: true
  89926. });
  89927. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  89928. /**
  89929. * Gets the shadows Density value.
  89930. * 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.
  89931. * Values less than zero provide a filter of opposite hue.
  89932. */
  89933. get: function () {
  89934. return this._shadowsDensity;
  89935. },
  89936. /**
  89937. * Sets the shadows Density value.
  89938. * 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.
  89939. * Values less than zero provide a filter of opposite hue.
  89940. */
  89941. set: function (value) {
  89942. this._shadowsDensity = value;
  89943. this._dirty = true;
  89944. },
  89945. enumerable: true,
  89946. configurable: true
  89947. });
  89948. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  89949. /**
  89950. * Gets the shadows Saturation value.
  89951. * 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.
  89952. */
  89953. get: function () {
  89954. return this._shadowsSaturation;
  89955. },
  89956. /**
  89957. * Sets the shadows Saturation value.
  89958. * 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.
  89959. */
  89960. set: function (value) {
  89961. this._shadowsSaturation = value;
  89962. this._dirty = true;
  89963. },
  89964. enumerable: true,
  89965. configurable: true
  89966. });
  89967. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  89968. /**
  89969. * Gets the shadows Exposure value.
  89970. * 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.
  89971. */
  89972. get: function () {
  89973. return this._shadowsExposure;
  89974. },
  89975. /**
  89976. * Sets the shadows Exposure value.
  89977. * 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.
  89978. */
  89979. set: function (value) {
  89980. this._shadowsExposure = value;
  89981. this._dirty = true;
  89982. },
  89983. enumerable: true,
  89984. configurable: true
  89985. });
  89986. /**
  89987. * Returns the class name
  89988. * @returns The class name
  89989. */
  89990. ColorCurves.prototype.getClassName = function () {
  89991. return "ColorCurves";
  89992. };
  89993. /**
  89994. * Binds the color curves to the shader.
  89995. * @param colorCurves The color curve to bind
  89996. * @param effect The effect to bind to
  89997. * @param positiveUniform The positive uniform shader parameter
  89998. * @param neutralUniform The neutral uniform shader parameter
  89999. * @param negativeUniform The negative uniform shader parameter
  90000. */
  90001. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  90002. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  90003. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  90004. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  90005. if (colorCurves._dirty) {
  90006. colorCurves._dirty = false;
  90007. // Fill in global info.
  90008. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  90009. // Compute highlights info.
  90010. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  90011. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  90012. // Compute midtones info.
  90013. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  90014. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  90015. // Compute shadows info.
  90016. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  90017. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  90018. // Compute deltas (neutral is midtones).
  90019. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  90020. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  90021. }
  90022. if (effect) {
  90023. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  90024. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  90025. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  90026. }
  90027. };
  90028. /**
  90029. * Prepare the list of uniforms associated with the ColorCurves effects.
  90030. * @param uniformsList The list of uniforms used in the effect
  90031. */
  90032. ColorCurves.PrepareUniforms = function (uniformsList) {
  90033. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  90034. };
  90035. /**
  90036. * Returns color grading data based on a hue, density, saturation and exposure value.
  90037. * @param filterHue The hue of the color filter.
  90038. * @param filterDensity The density of the color filter.
  90039. * @param saturation The saturation.
  90040. * @param exposure The exposure.
  90041. * @param result The result data container.
  90042. */
  90043. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  90044. if (hue == null) {
  90045. return;
  90046. }
  90047. hue = ColorCurves.clamp(hue, 0, 360);
  90048. density = ColorCurves.clamp(density, -100, 100);
  90049. saturation = ColorCurves.clamp(saturation, -100, 100);
  90050. exposure = ColorCurves.clamp(exposure, -100, 100);
  90051. // Remap the slider/config filter density with non-linear mapping and also scale by half
  90052. // so that the maximum filter density is only 50% control. This provides fine control
  90053. // for small values and reasonable range.
  90054. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  90055. density *= 0.5;
  90056. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  90057. if (density < 0) {
  90058. density *= -1;
  90059. hue = (hue + 180) % 360;
  90060. }
  90061. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  90062. result.scaleToRef(2, result);
  90063. result.a = 1 + 0.01 * saturation;
  90064. };
  90065. /**
  90066. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  90067. * @param value The input slider value in range [-100,100].
  90068. * @returns Adjusted value.
  90069. */
  90070. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  90071. value /= 100;
  90072. var x = Math.abs(value);
  90073. x = Math.pow(x, 2);
  90074. if (value < 0) {
  90075. x *= -1;
  90076. }
  90077. x *= 100;
  90078. return x;
  90079. };
  90080. /**
  90081. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  90082. * @param hue The hue (H) input.
  90083. * @param saturation The saturation (S) input.
  90084. * @param brightness The brightness (B) input.
  90085. * @result An RGBA color represented as Vector4.
  90086. */
  90087. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  90088. var h = ColorCurves.clamp(hue, 0, 360);
  90089. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  90090. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  90091. if (s === 0) {
  90092. result.r = v;
  90093. result.g = v;
  90094. result.b = v;
  90095. }
  90096. else {
  90097. // sector 0 to 5
  90098. h /= 60;
  90099. var i = Math.floor(h);
  90100. // fractional part of h
  90101. var f = h - i;
  90102. var p = v * (1 - s);
  90103. var q = v * (1 - s * f);
  90104. var t = v * (1 - s * (1 - f));
  90105. switch (i) {
  90106. case 0:
  90107. result.r = v;
  90108. result.g = t;
  90109. result.b = p;
  90110. break;
  90111. case 1:
  90112. result.r = q;
  90113. result.g = v;
  90114. result.b = p;
  90115. break;
  90116. case 2:
  90117. result.r = p;
  90118. result.g = v;
  90119. result.b = t;
  90120. break;
  90121. case 3:
  90122. result.r = p;
  90123. result.g = q;
  90124. result.b = v;
  90125. break;
  90126. case 4:
  90127. result.r = t;
  90128. result.g = p;
  90129. result.b = v;
  90130. break;
  90131. default: // case 5:
  90132. result.r = v;
  90133. result.g = p;
  90134. result.b = q;
  90135. break;
  90136. }
  90137. }
  90138. result.a = 1;
  90139. };
  90140. /**
  90141. * Returns a value clamped between min and max
  90142. * @param value The value to clamp
  90143. * @param min The minimum of value
  90144. * @param max The maximum of value
  90145. * @returns The clamped value.
  90146. */
  90147. ColorCurves.clamp = function (value, min, max) {
  90148. return Math.min(Math.max(value, min), max);
  90149. };
  90150. /**
  90151. * Clones the current color curve instance.
  90152. * @return The cloned curves
  90153. */
  90154. ColorCurves.prototype.clone = function () {
  90155. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  90156. };
  90157. /**
  90158. * Serializes the current color curve instance to a json representation.
  90159. * @return a JSON representation
  90160. */
  90161. ColorCurves.prototype.serialize = function () {
  90162. return BABYLON.SerializationHelper.Serialize(this);
  90163. };
  90164. /**
  90165. * Parses the color curve from a json representation.
  90166. * @param source the JSON source to parse
  90167. * @return The parsed curves
  90168. */
  90169. ColorCurves.Parse = function (source) {
  90170. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  90171. };
  90172. __decorate([
  90173. BABYLON.serialize()
  90174. ], ColorCurves.prototype, "_globalHue", void 0);
  90175. __decorate([
  90176. BABYLON.serialize()
  90177. ], ColorCurves.prototype, "_globalDensity", void 0);
  90178. __decorate([
  90179. BABYLON.serialize()
  90180. ], ColorCurves.prototype, "_globalSaturation", void 0);
  90181. __decorate([
  90182. BABYLON.serialize()
  90183. ], ColorCurves.prototype, "_globalExposure", void 0);
  90184. __decorate([
  90185. BABYLON.serialize()
  90186. ], ColorCurves.prototype, "_highlightsHue", void 0);
  90187. __decorate([
  90188. BABYLON.serialize()
  90189. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  90190. __decorate([
  90191. BABYLON.serialize()
  90192. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  90193. __decorate([
  90194. BABYLON.serialize()
  90195. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  90196. __decorate([
  90197. BABYLON.serialize()
  90198. ], ColorCurves.prototype, "_midtonesHue", void 0);
  90199. __decorate([
  90200. BABYLON.serialize()
  90201. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  90202. __decorate([
  90203. BABYLON.serialize()
  90204. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  90205. __decorate([
  90206. BABYLON.serialize()
  90207. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  90208. return ColorCurves;
  90209. }());
  90210. BABYLON.ColorCurves = ColorCurves;
  90211. })(BABYLON || (BABYLON = {}));
  90212. //# sourceMappingURL=colorCurves.js.map
  90213. var BABYLON;
  90214. (function (BABYLON) {
  90215. /**
  90216. * Post process which applies a refractin texture
  90217. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  90218. */
  90219. var RefractionPostProcess = /** @class */ (function (_super) {
  90220. __extends(RefractionPostProcess, _super);
  90221. /**
  90222. * Initializes the RefractionPostProcess
  90223. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  90224. * @param name The name of the effect.
  90225. * @param refractionTextureUrl Url of the refraction texture to use
  90226. * @param color the base color of the refraction (used to taint the rendering)
  90227. * @param depth simulated refraction depth
  90228. * @param colorLevel the coefficient of the base color (0 to remove base color tainting)
  90229. * @param camera The camera to apply the render pass to.
  90230. * @param options The required width/height ratio to downsize to before computing the render pass.
  90231. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90232. * @param engine The engine which the post process will be applied. (default: current engine)
  90233. * @param reusable If the post process can be reused on the same frame. (default: false)
  90234. */
  90235. function RefractionPostProcess(name, refractionTextureUrl,
  90236. /** the base color of the refraction (used to taint the rendering) */
  90237. color,
  90238. /** simulated refraction depth */
  90239. depth,
  90240. /** the coefficient of the base color (0 to remove base color tainting) */
  90241. colorLevel, options, camera, samplingMode, engine, reusable) {
  90242. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  90243. _this.color = color;
  90244. _this.depth = depth;
  90245. _this.colorLevel = colorLevel;
  90246. _this._ownRefractionTexture = true;
  90247. _this.onActivateObservable.add(function (cam) {
  90248. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  90249. });
  90250. _this.onApplyObservable.add(function (effect) {
  90251. effect.setColor3("baseColor", _this.color);
  90252. effect.setFloat("depth", _this.depth);
  90253. effect.setFloat("colorLevel", _this.colorLevel);
  90254. effect.setTexture("refractionSampler", _this._refTexture);
  90255. });
  90256. return _this;
  90257. }
  90258. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  90259. /**
  90260. * Gets or sets the refraction texture
  90261. * Please note that you are responsible for disposing the texture if you set it manually
  90262. */
  90263. get: function () {
  90264. return this._refTexture;
  90265. },
  90266. set: function (value) {
  90267. if (this._refTexture && this._ownRefractionTexture) {
  90268. this._refTexture.dispose();
  90269. }
  90270. this._refTexture = value;
  90271. this._ownRefractionTexture = false;
  90272. },
  90273. enumerable: true,
  90274. configurable: true
  90275. });
  90276. // Methods
  90277. /**
  90278. * Disposes of the post process
  90279. * @param camera Camera to dispose post process on
  90280. */
  90281. RefractionPostProcess.prototype.dispose = function (camera) {
  90282. if (this._refTexture && this._ownRefractionTexture) {
  90283. this._refTexture.dispose();
  90284. this._refTexture = null;
  90285. }
  90286. _super.prototype.dispose.call(this, camera);
  90287. };
  90288. return RefractionPostProcess;
  90289. }(BABYLON.PostProcess));
  90290. BABYLON.RefractionPostProcess = RefractionPostProcess;
  90291. })(BABYLON || (BABYLON = {}));
  90292. //# sourceMappingURL=refractionPostProcess.js.map
  90293. var BABYLON;
  90294. (function (BABYLON) {
  90295. /**
  90296. * Post process used to render in black and white
  90297. */
  90298. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  90299. __extends(BlackAndWhitePostProcess, _super);
  90300. /**
  90301. * Creates a black and white post process
  90302. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#black-and-white
  90303. * @param name The name of the effect.
  90304. * @param options The required width/height ratio to downsize to before computing the render pass.
  90305. * @param camera The camera to apply the render pass to.
  90306. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90307. * @param engine The engine which the post process will be applied. (default: current engine)
  90308. * @param reusable If the post process can be reused on the same frame. (default: false)
  90309. */
  90310. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  90311. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  90312. /**
  90313. * Linear about to convert he result to black and white (default: 1)
  90314. */
  90315. _this.degree = 1;
  90316. _this.onApplyObservable.add(function (effect) {
  90317. effect.setFloat("degree", _this.degree);
  90318. });
  90319. return _this;
  90320. }
  90321. return BlackAndWhitePostProcess;
  90322. }(BABYLON.PostProcess));
  90323. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  90324. })(BABYLON || (BABYLON = {}));
  90325. //# sourceMappingURL=blackAndWhitePostProcess.js.map
  90326. var BABYLON;
  90327. (function (BABYLON) {
  90328. /**
  90329. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  90330. * input texture to perform effects such as edge detection or sharpening
  90331. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  90332. */
  90333. var ConvolutionPostProcess = /** @class */ (function (_super) {
  90334. __extends(ConvolutionPostProcess, _super);
  90335. /**
  90336. * Creates a new instance ConvolutionPostProcess
  90337. * @param name The name of the effect.
  90338. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  90339. * @param options The required width/height ratio to downsize to before computing the render pass.
  90340. * @param camera The camera to apply the render pass to.
  90341. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90342. * @param engine The engine which the post process will be applied. (default: current engine)
  90343. * @param reusable If the post process can be reused on the same frame. (default: false)
  90344. * @param textureType Type of textures used when performing the post process. (default: 0)
  90345. */
  90346. function ConvolutionPostProcess(name,
  90347. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  90348. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  90349. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  90350. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  90351. _this.kernel = kernel;
  90352. _this.onApply = function (effect) {
  90353. effect.setFloat2("screenSize", _this.width, _this.height);
  90354. effect.setArray("kernel", _this.kernel);
  90355. };
  90356. return _this;
  90357. }
  90358. // Statics
  90359. /**
  90360. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90361. */
  90362. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  90363. /**
  90364. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90365. */
  90366. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  90367. /**
  90368. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90369. */
  90370. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  90371. /**
  90372. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90373. */
  90374. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  90375. /**
  90376. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90377. */
  90378. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  90379. /**
  90380. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  90381. */
  90382. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  90383. return ConvolutionPostProcess;
  90384. }(BABYLON.PostProcess));
  90385. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  90386. })(BABYLON || (BABYLON = {}));
  90387. //# sourceMappingURL=convolutionPostProcess.js.map
  90388. var BABYLON;
  90389. (function (BABYLON) {
  90390. /**
  90391. * Applies a kernel filter to the image
  90392. */
  90393. var FilterPostProcess = /** @class */ (function (_super) {
  90394. __extends(FilterPostProcess, _super);
  90395. /**
  90396. *
  90397. * @param name The name of the effect.
  90398. * @param kernelMatrix The matrix to be applied to the image
  90399. * @param options The required width/height ratio to downsize to before computing the render pass.
  90400. * @param camera The camera to apply the render pass to.
  90401. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90402. * @param engine The engine which the post process will be applied. (default: current engine)
  90403. * @param reusable If the post process can be reused on the same frame. (default: false)
  90404. */
  90405. function FilterPostProcess(name,
  90406. /** The matrix to be applied to the image */
  90407. kernelMatrix, options, camera, samplingMode, engine, reusable) {
  90408. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  90409. _this.kernelMatrix = kernelMatrix;
  90410. _this.onApply = function (effect) {
  90411. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  90412. };
  90413. return _this;
  90414. }
  90415. return FilterPostProcess;
  90416. }(BABYLON.PostProcess));
  90417. BABYLON.FilterPostProcess = FilterPostProcess;
  90418. })(BABYLON || (BABYLON = {}));
  90419. //# sourceMappingURL=filterPostProcess.js.map
  90420. var BABYLON;
  90421. (function (BABYLON) {
  90422. /**
  90423. * Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  90424. */
  90425. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  90426. __extends(VolumetricLightScatteringPostProcess, _super);
  90427. /**
  90428. * @constructor
  90429. * @param name The post-process name
  90430. * @param ratio The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  90431. * @param camera The camera that the post-process will be attached to
  90432. * @param mesh The mesh used to create the light scattering
  90433. * @param samples The post-process quality, default 100
  90434. * @param samplingModeThe post-process filtering mode
  90435. * @param engine The babylon engine
  90436. * @param reusable If the post-process is reusable
  90437. * @param scene The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  90438. */
  90439. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  90440. if (samples === void 0) { samples = 100; }
  90441. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  90442. 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;
  90443. _this._screenCoordinates = BABYLON.Vector2.Zero();
  90444. /**
  90445. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  90446. */
  90447. _this.customMeshPosition = BABYLON.Vector3.Zero();
  90448. /**
  90449. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  90450. */
  90451. _this.useCustomMeshPosition = false;
  90452. /**
  90453. * If the post-process should inverse the light scattering direction
  90454. */
  90455. _this.invert = true;
  90456. /**
  90457. * Array containing the excluded meshes not rendered in the internal pass
  90458. */
  90459. _this.excludedMeshes = new Array();
  90460. /**
  90461. * Controls the overall intensity of the post-process
  90462. */
  90463. _this.exposure = 0.3;
  90464. /**
  90465. * Dissipates each sample's contribution in range [0, 1]
  90466. */
  90467. _this.decay = 0.96815;
  90468. /**
  90469. * Controls the overall intensity of each sample
  90470. */
  90471. _this.weight = 0.58767;
  90472. /**
  90473. * Controls the density of each sample
  90474. */
  90475. _this.density = 0.926;
  90476. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  90477. engine = scene.getEngine();
  90478. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  90479. // Configure mesh
  90480. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  90481. // Configure
  90482. _this._createPass(scene, ratio.passRatio || ratio);
  90483. _this.onActivate = function (camera) {
  90484. if (!_this.isSupported) {
  90485. _this.dispose(camera);
  90486. }
  90487. _this.onActivate = null;
  90488. };
  90489. _this.onApplyObservable.add(function (effect) {
  90490. _this._updateMeshScreenCoordinates(scene);
  90491. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  90492. effect.setFloat("exposure", _this.exposure);
  90493. effect.setFloat("decay", _this.decay);
  90494. effect.setFloat("weight", _this.weight);
  90495. effect.setFloat("density", _this.density);
  90496. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  90497. });
  90498. return _this;
  90499. }
  90500. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  90501. /**
  90502. * @hidden
  90503. * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
  90504. */
  90505. get: function () {
  90506. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  90507. return false;
  90508. },
  90509. set: function (useDiffuseColor) {
  90510. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  90511. },
  90512. enumerable: true,
  90513. configurable: true
  90514. });
  90515. /**
  90516. * Returns the string "VolumetricLightScatteringPostProcess"
  90517. * @returns "VolumetricLightScatteringPostProcess"
  90518. */
  90519. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  90520. return "VolumetricLightScatteringPostProcess";
  90521. };
  90522. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  90523. var mesh = subMesh.getMesh();
  90524. // Render this.mesh as default
  90525. if (mesh === this.mesh && mesh.material) {
  90526. return mesh.material.isReady(mesh);
  90527. }
  90528. var defines = [];
  90529. var attribs = [BABYLON.VertexBuffer.PositionKind];
  90530. var material = subMesh.getMaterial();
  90531. // Alpha test
  90532. if (material) {
  90533. if (material.needAlphaTesting()) {
  90534. defines.push("#define ALPHATEST");
  90535. }
  90536. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90537. attribs.push(BABYLON.VertexBuffer.UVKind);
  90538. defines.push("#define UV1");
  90539. }
  90540. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  90541. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90542. defines.push("#define UV2");
  90543. }
  90544. }
  90545. // Bones
  90546. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90547. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90548. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90549. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90550. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  90551. }
  90552. else {
  90553. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90554. }
  90555. // Instances
  90556. if (useInstances) {
  90557. defines.push("#define INSTANCES");
  90558. attribs.push("world0");
  90559. attribs.push("world1");
  90560. attribs.push("world2");
  90561. attribs.push("world3");
  90562. }
  90563. // Get correct effect
  90564. var join = defines.join("\n");
  90565. if (this._cachedDefines !== join) {
  90566. this._cachedDefines = join;
  90567. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  90568. }
  90569. return this._volumetricLightScatteringPass.isReady();
  90570. };
  90571. /**
  90572. * Sets the new light position for light scattering effect
  90573. * @param position The new custom light position
  90574. */
  90575. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  90576. this.customMeshPosition = position;
  90577. };
  90578. /**
  90579. * Returns the light position for light scattering effect
  90580. * @return Vector3 The custom light position
  90581. */
  90582. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  90583. return this.customMeshPosition;
  90584. };
  90585. /**
  90586. * Disposes the internal assets and detaches the post-process from the camera
  90587. */
  90588. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  90589. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  90590. if (rttIndex !== -1) {
  90591. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  90592. }
  90593. this._volumetricLightScatteringRTT.dispose();
  90594. _super.prototype.dispose.call(this, camera);
  90595. };
  90596. /**
  90597. * Returns the render target texture used by the post-process
  90598. * @return the render target texture used by the post-process
  90599. */
  90600. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  90601. return this._volumetricLightScatteringRTT;
  90602. };
  90603. // Private methods
  90604. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  90605. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  90606. return true;
  90607. }
  90608. return false;
  90609. };
  90610. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  90611. var _this = this;
  90612. var engine = scene.getEngine();
  90613. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  90614. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90615. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90616. this._volumetricLightScatteringRTT.renderList = null;
  90617. this._volumetricLightScatteringRTT.renderParticles = false;
  90618. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  90619. var camera = this.getCamera();
  90620. if (camera) {
  90621. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  90622. }
  90623. else {
  90624. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  90625. }
  90626. // Custom render function for submeshes
  90627. var renderSubMesh = function (subMesh) {
  90628. var mesh = subMesh.getRenderingMesh();
  90629. if (_this._meshExcluded(mesh)) {
  90630. return;
  90631. }
  90632. var material = subMesh.getMaterial();
  90633. if (!material) {
  90634. return;
  90635. }
  90636. var scene = mesh.getScene();
  90637. var engine = scene.getEngine();
  90638. // Culling
  90639. engine.setState(material.backFaceCulling);
  90640. // Managing instances
  90641. var batch = mesh._getInstancesRenderList(subMesh._id);
  90642. if (batch.mustReturn) {
  90643. return;
  90644. }
  90645. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  90646. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  90647. var effect = _this._volumetricLightScatteringPass;
  90648. if (mesh === _this.mesh) {
  90649. if (subMesh.effect) {
  90650. effect = subMesh.effect;
  90651. }
  90652. else {
  90653. effect = material.getEffect();
  90654. }
  90655. }
  90656. engine.enableEffect(effect);
  90657. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  90658. if (mesh === _this.mesh) {
  90659. material.bind(mesh.getWorldMatrix(), mesh);
  90660. }
  90661. else {
  90662. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  90663. // Alpha test
  90664. if (material && material.needAlphaTesting()) {
  90665. var alphaTexture = material.getAlphaTestTexture();
  90666. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  90667. if (alphaTexture) {
  90668. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  90669. }
  90670. }
  90671. // Bones
  90672. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90673. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90674. }
  90675. }
  90676. // Draw
  90677. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  90678. }
  90679. };
  90680. // Render target texture callbacks
  90681. var savedSceneClearColor;
  90682. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  90683. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  90684. savedSceneClearColor = scene.clearColor;
  90685. scene.clearColor = sceneClearColor;
  90686. });
  90687. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  90688. scene.clearColor = savedSceneClearColor;
  90689. });
  90690. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  90691. var engine = scene.getEngine();
  90692. var index;
  90693. if (depthOnlySubMeshes.length) {
  90694. engine.setColorWrite(false);
  90695. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  90696. renderSubMesh(depthOnlySubMeshes.data[index]);
  90697. }
  90698. engine.setColorWrite(true);
  90699. }
  90700. for (index = 0; index < opaqueSubMeshes.length; index++) {
  90701. renderSubMesh(opaqueSubMeshes.data[index]);
  90702. }
  90703. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  90704. renderSubMesh(alphaTestSubMeshes.data[index]);
  90705. }
  90706. if (transparentSubMeshes.length) {
  90707. // Sort sub meshes
  90708. for (index = 0; index < transparentSubMeshes.length; index++) {
  90709. var submesh = transparentSubMeshes.data[index];
  90710. var boundingInfo = submesh.getBoundingInfo();
  90711. if (boundingInfo && scene.activeCamera) {
  90712. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  90713. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  90714. }
  90715. }
  90716. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  90717. sortedArray.sort(function (a, b) {
  90718. // Alpha index first
  90719. if (a._alphaIndex > b._alphaIndex) {
  90720. return 1;
  90721. }
  90722. if (a._alphaIndex < b._alphaIndex) {
  90723. return -1;
  90724. }
  90725. // Then distance to camera
  90726. if (a._distanceToCamera < b._distanceToCamera) {
  90727. return 1;
  90728. }
  90729. if (a._distanceToCamera > b._distanceToCamera) {
  90730. return -1;
  90731. }
  90732. return 0;
  90733. });
  90734. // Render sub meshes
  90735. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  90736. for (index = 0; index < sortedArray.length; index++) {
  90737. renderSubMesh(sortedArray[index]);
  90738. }
  90739. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  90740. }
  90741. };
  90742. };
  90743. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  90744. var transform = scene.getTransformMatrix();
  90745. var meshPosition;
  90746. if (this.useCustomMeshPosition) {
  90747. meshPosition = this.customMeshPosition;
  90748. }
  90749. else if (this.attachedNode) {
  90750. meshPosition = this.attachedNode.position;
  90751. }
  90752. else {
  90753. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  90754. }
  90755. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  90756. this._screenCoordinates.x = pos.x / this._viewPort.width;
  90757. this._screenCoordinates.y = pos.y / this._viewPort.height;
  90758. if (this.invert) {
  90759. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  90760. }
  90761. };
  90762. // Static methods
  90763. /**
  90764. * Creates a default mesh for the Volumeric Light Scattering post-process
  90765. * @param name The mesh name
  90766. * @param scene The scene where to create the mesh
  90767. * @return the default mesh
  90768. */
  90769. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  90770. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  90771. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  90772. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  90773. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  90774. mesh.material = material;
  90775. return mesh;
  90776. };
  90777. __decorate([
  90778. BABYLON.serializeAsVector3()
  90779. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  90780. __decorate([
  90781. BABYLON.serialize()
  90782. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  90783. __decorate([
  90784. BABYLON.serialize()
  90785. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  90786. __decorate([
  90787. BABYLON.serializeAsMeshReference()
  90788. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  90789. __decorate([
  90790. BABYLON.serialize()
  90791. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  90792. __decorate([
  90793. BABYLON.serialize()
  90794. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  90795. __decorate([
  90796. BABYLON.serialize()
  90797. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  90798. __decorate([
  90799. BABYLON.serialize()
  90800. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  90801. __decorate([
  90802. BABYLON.serialize()
  90803. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  90804. return VolumetricLightScatteringPostProcess;
  90805. }(BABYLON.PostProcess));
  90806. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  90807. })(BABYLON || (BABYLON = {}));
  90808. //# sourceMappingURL=volumetricLightScatteringPostProcess.js.map
  90809. var BABYLON;
  90810. (function (BABYLON) {
  90811. /**
  90812. *
  90813. * This post-process allows the modification of rendered colors by using
  90814. * a 'look-up table' (LUT). This effect is also called Color Grading.
  90815. *
  90816. * The object needs to be provided an url to a texture containing the color
  90817. * look-up table: the texture must be 256 pixels wide and 16 pixels high.
  90818. * Use an image editing software to tweak the LUT to match your needs.
  90819. *
  90820. * For an example of a color LUT, see here:
  90821. * @see http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  90822. * For explanations on color grading, see here:
  90823. * @see http://udn.epicgames.com/Three/ColorGrading.html
  90824. *
  90825. */
  90826. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  90827. __extends(ColorCorrectionPostProcess, _super);
  90828. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  90829. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  90830. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  90831. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  90832. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90833. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90834. _this.onApply = function (effect) {
  90835. effect.setTexture("colorTable", _this._colorTableTexture);
  90836. };
  90837. return _this;
  90838. }
  90839. return ColorCorrectionPostProcess;
  90840. }(BABYLON.PostProcess));
  90841. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  90842. })(BABYLON || (BABYLON = {}));
  90843. //# sourceMappingURL=colorCorrectionPostProcess.js.map
  90844. var BABYLON;
  90845. (function (BABYLON) {
  90846. /** Defines operator used for tonemapping */
  90847. var TonemappingOperator;
  90848. (function (TonemappingOperator) {
  90849. /** Hable */
  90850. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  90851. /** Reinhard */
  90852. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  90853. /** HejiDawson */
  90854. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  90855. /** Photographic */
  90856. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  90857. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  90858. /**
  90859. * Defines a post process to apply tone mapping
  90860. */
  90861. var TonemapPostProcess = /** @class */ (function (_super) {
  90862. __extends(TonemapPostProcess, _super);
  90863. /**
  90864. * Creates a new TonemapPostProcess
  90865. * @param name defines the name of the postprocess
  90866. * @param _operator defines the operator to use
  90867. * @param exposureAdjustment defines the required exposure adjustement
  90868. * @param camera defines the camera to use (can be null)
  90869. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  90870. * @param engine defines the hosting engine (can be ignore if camera is set)
  90871. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  90872. */
  90873. function TonemapPostProcess(name, _operator,
  90874. /** Defines the required exposure adjustement */
  90875. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  90876. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  90877. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  90878. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  90879. _this._operator = _operator;
  90880. _this.exposureAdjustment = exposureAdjustment;
  90881. var defines = "#define ";
  90882. if (_this._operator === TonemappingOperator.Hable) {
  90883. defines += "HABLE_TONEMAPPING";
  90884. }
  90885. else if (_this._operator === TonemappingOperator.Reinhard) {
  90886. defines += "REINHARD_TONEMAPPING";
  90887. }
  90888. else if (_this._operator === TonemappingOperator.HejiDawson) {
  90889. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  90890. }
  90891. else if (_this._operator === TonemappingOperator.Photographic) {
  90892. defines += "PHOTOGRAPHIC_TONEMAPPING";
  90893. }
  90894. //sadly a second call to create the effect.
  90895. _this.updateEffect(defines);
  90896. _this.onApply = function (effect) {
  90897. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  90898. };
  90899. return _this;
  90900. }
  90901. return TonemapPostProcess;
  90902. }(BABYLON.PostProcess));
  90903. BABYLON.TonemapPostProcess = TonemapPostProcess;
  90904. })(BABYLON || (BABYLON = {}));
  90905. //# sourceMappingURL=tonemapPostProcess.js.map
  90906. var BABYLON;
  90907. (function (BABYLON) {
  90908. /**
  90909. * DisplayPassPostProcess which produces an output the same as it's input
  90910. */
  90911. var DisplayPassPostProcess = /** @class */ (function (_super) {
  90912. __extends(DisplayPassPostProcess, _super);
  90913. /**
  90914. * Creates the DisplayPassPostProcess
  90915. * @param name The name of the effect.
  90916. * @param options The required width/height ratio to downsize to before computing the render pass.
  90917. * @param camera The camera to apply the render pass to.
  90918. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90919. * @param engine The engine which the post process will be applied. (default: current engine)
  90920. * @param reusable If the post process can be reused on the same frame. (default: false)
  90921. */
  90922. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  90923. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  90924. }
  90925. return DisplayPassPostProcess;
  90926. }(BABYLON.PostProcess));
  90927. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  90928. })(BABYLON || (BABYLON = {}));
  90929. //# sourceMappingURL=displayPassPostProcess.js.map
  90930. var BABYLON;
  90931. (function (BABYLON) {
  90932. /**
  90933. * Extracts highlights from the image
  90934. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  90935. */
  90936. var HighlightsPostProcess = /** @class */ (function (_super) {
  90937. __extends(HighlightsPostProcess, _super);
  90938. /**
  90939. * Extracts highlights from the image
  90940. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  90941. * @param name The name of the effect.
  90942. * @param options The required width/height ratio to downsize to before computing the render pass.
  90943. * @param camera The camera to apply the render pass to.
  90944. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  90945. * @param engine The engine which the post process will be applied. (default: current engine)
  90946. * @param reusable If the post process can be reused on the same frame. (default: false)
  90947. * @param textureType Type of texture for the post process (default: Engine.TEXTURETYPE_UNSIGNED_INT)
  90948. */
  90949. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  90950. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  90951. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  90952. }
  90953. return HighlightsPostProcess;
  90954. }(BABYLON.PostProcess));
  90955. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  90956. })(BABYLON || (BABYLON = {}));
  90957. //# sourceMappingURL=highlightsPostProcess.js.map
  90958. var BABYLON;
  90959. (function (BABYLON) {
  90960. /**
  90961. * ImageProcessingPostProcess
  90962. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#imageprocessing
  90963. */
  90964. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  90965. __extends(ImageProcessingPostProcess, _super);
  90966. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  90967. if (camera === void 0) { camera = null; }
  90968. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  90969. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  90970. _this._fromLinearSpace = true;
  90971. /**
  90972. * Defines cache preventing GC.
  90973. */
  90974. _this._defines = {
  90975. IMAGEPROCESSING: false,
  90976. VIGNETTE: false,
  90977. VIGNETTEBLENDMODEMULTIPLY: false,
  90978. VIGNETTEBLENDMODEOPAQUE: false,
  90979. TONEMAPPING: false,
  90980. TONEMAPPING_ACES: false,
  90981. CONTRAST: false,
  90982. COLORCURVES: false,
  90983. COLORGRADING: false,
  90984. COLORGRADING3D: false,
  90985. FROMLINEARSPACE: false,
  90986. SAMPLER3DGREENDEPTH: false,
  90987. SAMPLER3DBGRMAP: false,
  90988. IMAGEPROCESSINGPOSTPROCESS: false,
  90989. EXPOSURE: false,
  90990. };
  90991. // Setup the configuration as forced by the constructor. This would then not force the
  90992. // scene materials output in linear space and let untouched the default forward pass.
  90993. if (imageProcessingConfiguration) {
  90994. imageProcessingConfiguration.applyByPostProcess = true;
  90995. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  90996. // This will cause the shader to be compiled
  90997. _this.fromLinearSpace = false;
  90998. }
  90999. // Setup the default processing configuration to the scene.
  91000. else {
  91001. _this._attachImageProcessingConfiguration(null, true);
  91002. _this.imageProcessingConfiguration.applyByPostProcess = true;
  91003. }
  91004. _this.onApply = function (effect) {
  91005. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  91006. };
  91007. return _this;
  91008. }
  91009. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  91010. /**
  91011. * Gets the image processing configuration used either in this material.
  91012. */
  91013. get: function () {
  91014. return this._imageProcessingConfiguration;
  91015. },
  91016. /**
  91017. * Sets the Default image processing configuration used either in the this material.
  91018. *
  91019. * If sets to null, the scene one is in use.
  91020. */
  91021. set: function (value) {
  91022. this._attachImageProcessingConfiguration(value);
  91023. },
  91024. enumerable: true,
  91025. configurable: true
  91026. });
  91027. /**
  91028. * Attaches a new image processing configuration to the PBR Material.
  91029. * @param configuration
  91030. */
  91031. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  91032. var _this = this;
  91033. if (doNotBuild === void 0) { doNotBuild = false; }
  91034. if (configuration === this._imageProcessingConfiguration) {
  91035. return;
  91036. }
  91037. // Detaches observer.
  91038. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91039. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91040. }
  91041. // Pick the scene configuration if needed.
  91042. if (!configuration) {
  91043. var scene = null;
  91044. var engine = this.getEngine();
  91045. var camera = this.getCamera();
  91046. if (camera) {
  91047. scene = camera.getScene();
  91048. }
  91049. else if (engine && engine.scenes) {
  91050. var scenes = engine.scenes;
  91051. scene = scenes[scenes.length - 1];
  91052. }
  91053. else {
  91054. scene = BABYLON.Engine.LastCreatedScene;
  91055. }
  91056. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  91057. }
  91058. else {
  91059. this._imageProcessingConfiguration = configuration;
  91060. }
  91061. // Attaches observer.
  91062. if (this._imageProcessingConfiguration) {
  91063. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  91064. _this._updateParameters();
  91065. });
  91066. }
  91067. // Ensure the effect will be rebuilt.
  91068. if (!doNotBuild) {
  91069. this._updateParameters();
  91070. }
  91071. };
  91072. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  91073. /**
  91074. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  91075. */
  91076. get: function () {
  91077. return this.imageProcessingConfiguration.colorCurves;
  91078. },
  91079. /**
  91080. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  91081. */
  91082. set: function (value) {
  91083. this.imageProcessingConfiguration.colorCurves = value;
  91084. },
  91085. enumerable: true,
  91086. configurable: true
  91087. });
  91088. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  91089. /**
  91090. * Gets wether the color curves effect is enabled.
  91091. */
  91092. get: function () {
  91093. return this.imageProcessingConfiguration.colorCurvesEnabled;
  91094. },
  91095. /**
  91096. * Sets wether the color curves effect is enabled.
  91097. */
  91098. set: function (value) {
  91099. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  91100. },
  91101. enumerable: true,
  91102. configurable: true
  91103. });
  91104. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  91105. /**
  91106. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  91107. */
  91108. get: function () {
  91109. return this.imageProcessingConfiguration.colorGradingTexture;
  91110. },
  91111. /**
  91112. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  91113. */
  91114. set: function (value) {
  91115. this.imageProcessingConfiguration.colorGradingTexture = value;
  91116. },
  91117. enumerable: true,
  91118. configurable: true
  91119. });
  91120. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  91121. /**
  91122. * Gets wether the color grading effect is enabled.
  91123. */
  91124. get: function () {
  91125. return this.imageProcessingConfiguration.colorGradingEnabled;
  91126. },
  91127. /**
  91128. * Gets wether the color grading effect is enabled.
  91129. */
  91130. set: function (value) {
  91131. this.imageProcessingConfiguration.colorGradingEnabled = value;
  91132. },
  91133. enumerable: true,
  91134. configurable: true
  91135. });
  91136. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  91137. /**
  91138. * Gets exposure used in the effect.
  91139. */
  91140. get: function () {
  91141. return this.imageProcessingConfiguration.exposure;
  91142. },
  91143. /**
  91144. * Sets exposure used in the effect.
  91145. */
  91146. set: function (value) {
  91147. this.imageProcessingConfiguration.exposure = value;
  91148. },
  91149. enumerable: true,
  91150. configurable: true
  91151. });
  91152. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  91153. /**
  91154. * Gets wether tonemapping is enabled or not.
  91155. */
  91156. get: function () {
  91157. return this._imageProcessingConfiguration.toneMappingEnabled;
  91158. },
  91159. /**
  91160. * Sets wether tonemapping is enabled or not
  91161. */
  91162. set: function (value) {
  91163. this._imageProcessingConfiguration.toneMappingEnabled = value;
  91164. },
  91165. enumerable: true,
  91166. configurable: true
  91167. });
  91168. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  91169. /**
  91170. * Gets contrast used in the effect.
  91171. */
  91172. get: function () {
  91173. return this.imageProcessingConfiguration.contrast;
  91174. },
  91175. /**
  91176. * Sets contrast used in the effect.
  91177. */
  91178. set: function (value) {
  91179. this.imageProcessingConfiguration.contrast = value;
  91180. },
  91181. enumerable: true,
  91182. configurable: true
  91183. });
  91184. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  91185. /**
  91186. * Gets Vignette stretch size.
  91187. */
  91188. get: function () {
  91189. return this.imageProcessingConfiguration.vignetteStretch;
  91190. },
  91191. /**
  91192. * Sets Vignette stretch size.
  91193. */
  91194. set: function (value) {
  91195. this.imageProcessingConfiguration.vignetteStretch = value;
  91196. },
  91197. enumerable: true,
  91198. configurable: true
  91199. });
  91200. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  91201. /**
  91202. * Gets Vignette centre X Offset.
  91203. */
  91204. get: function () {
  91205. return this.imageProcessingConfiguration.vignetteCentreX;
  91206. },
  91207. /**
  91208. * Sets Vignette centre X Offset.
  91209. */
  91210. set: function (value) {
  91211. this.imageProcessingConfiguration.vignetteCentreX = value;
  91212. },
  91213. enumerable: true,
  91214. configurable: true
  91215. });
  91216. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  91217. /**
  91218. * Gets Vignette centre Y Offset.
  91219. */
  91220. get: function () {
  91221. return this.imageProcessingConfiguration.vignetteCentreY;
  91222. },
  91223. /**
  91224. * Sets Vignette centre Y Offset.
  91225. */
  91226. set: function (value) {
  91227. this.imageProcessingConfiguration.vignetteCentreY = value;
  91228. },
  91229. enumerable: true,
  91230. configurable: true
  91231. });
  91232. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  91233. /**
  91234. * Gets Vignette weight or intensity of the vignette effect.
  91235. */
  91236. get: function () {
  91237. return this.imageProcessingConfiguration.vignetteWeight;
  91238. },
  91239. /**
  91240. * Sets Vignette weight or intensity of the vignette effect.
  91241. */
  91242. set: function (value) {
  91243. this.imageProcessingConfiguration.vignetteWeight = value;
  91244. },
  91245. enumerable: true,
  91246. configurable: true
  91247. });
  91248. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  91249. /**
  91250. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  91251. * if vignetteEnabled is set to true.
  91252. */
  91253. get: function () {
  91254. return this.imageProcessingConfiguration.vignetteColor;
  91255. },
  91256. /**
  91257. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  91258. * if vignetteEnabled is set to true.
  91259. */
  91260. set: function (value) {
  91261. this.imageProcessingConfiguration.vignetteColor = value;
  91262. },
  91263. enumerable: true,
  91264. configurable: true
  91265. });
  91266. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  91267. /**
  91268. * Gets Camera field of view used by the Vignette effect.
  91269. */
  91270. get: function () {
  91271. return this.imageProcessingConfiguration.vignetteCameraFov;
  91272. },
  91273. /**
  91274. * Sets Camera field of view used by the Vignette effect.
  91275. */
  91276. set: function (value) {
  91277. this.imageProcessingConfiguration.vignetteCameraFov = value;
  91278. },
  91279. enumerable: true,
  91280. configurable: true
  91281. });
  91282. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  91283. /**
  91284. * Gets the vignette blend mode allowing different kind of effect.
  91285. */
  91286. get: function () {
  91287. return this.imageProcessingConfiguration.vignetteBlendMode;
  91288. },
  91289. /**
  91290. * Sets the vignette blend mode allowing different kind of effect.
  91291. */
  91292. set: function (value) {
  91293. this.imageProcessingConfiguration.vignetteBlendMode = value;
  91294. },
  91295. enumerable: true,
  91296. configurable: true
  91297. });
  91298. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  91299. /**
  91300. * Gets wether the vignette effect is enabled.
  91301. */
  91302. get: function () {
  91303. return this.imageProcessingConfiguration.vignetteEnabled;
  91304. },
  91305. /**
  91306. * Sets wether the vignette effect is enabled.
  91307. */
  91308. set: function (value) {
  91309. this.imageProcessingConfiguration.vignetteEnabled = value;
  91310. },
  91311. enumerable: true,
  91312. configurable: true
  91313. });
  91314. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  91315. /**
  91316. * Gets wether the input of the processing is in Gamma or Linear Space.
  91317. */
  91318. get: function () {
  91319. return this._fromLinearSpace;
  91320. },
  91321. /**
  91322. * Sets wether the input of the processing is in Gamma or Linear Space.
  91323. */
  91324. set: function (value) {
  91325. if (this._fromLinearSpace === value) {
  91326. return;
  91327. }
  91328. this._fromLinearSpace = value;
  91329. this._updateParameters();
  91330. },
  91331. enumerable: true,
  91332. configurable: true
  91333. });
  91334. /**
  91335. * "ImageProcessingPostProcess"
  91336. * @returns "ImageProcessingPostProcess"
  91337. */
  91338. ImageProcessingPostProcess.prototype.getClassName = function () {
  91339. return "ImageProcessingPostProcess";
  91340. };
  91341. ImageProcessingPostProcess.prototype._updateParameters = function () {
  91342. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  91343. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  91344. var defines = "";
  91345. for (var define in this._defines) {
  91346. if (this._defines[define]) {
  91347. defines += "#define " + define + ";\r\n";
  91348. }
  91349. }
  91350. var samplers = ["textureSampler"];
  91351. var uniforms = ["scale"];
  91352. if (BABYLON.ImageProcessingConfiguration) {
  91353. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  91354. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  91355. }
  91356. this.updateEffect(defines, uniforms, samplers);
  91357. };
  91358. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  91359. _super.prototype.dispose.call(this, camera);
  91360. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91361. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91362. }
  91363. if (this._imageProcessingConfiguration) {
  91364. this.imageProcessingConfiguration.applyByPostProcess = false;
  91365. }
  91366. };
  91367. __decorate([
  91368. BABYLON.serialize()
  91369. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  91370. return ImageProcessingPostProcess;
  91371. }(BABYLON.PostProcess));
  91372. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  91373. })(BABYLON || (BABYLON = {}));
  91374. //# sourceMappingURL=imageProcessingPostProcess.js.map
  91375. var BABYLON;
  91376. (function (BABYLON) {
  91377. /**
  91378. * The Motion Blur Post Process which blurs an image based on the objects velocity in scene.
  91379. * Velocity can be affected by each object's rotation, position and scale depending on the transformation speed.
  91380. * As an example, all you have to do is to create the post-process:
  91381. * var mb = new BABYLON.MotionBlurPostProcess(
  91382. * 'mb', // The name of the effect.
  91383. * scene, // The scene containing the objects to blur according to their velocity.
  91384. * 1.0, // The required width/height ratio to downsize to before computing the render pass.
  91385. * camera // The camera to apply the render pass to.
  91386. * );
  91387. * Then, all objects moving, rotating and/or scaling will be blurred depending on the transformation speed.
  91388. */
  91389. var MotionBlurPostProcess = /** @class */ (function (_super) {
  91390. __extends(MotionBlurPostProcess, _super);
  91391. /**
  91392. * Creates a new instance MotionBlurPostProcess
  91393. * @param name The name of the effect.
  91394. * @param scene The scene containing the objects to blur according to their velocity.
  91395. * @param options The required width/height ratio to downsize to before computing the render pass.
  91396. * @param camera The camera to apply the render pass to.
  91397. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  91398. * @param engine The engine which the post process will be applied. (default: current engine)
  91399. * @param reusable If the post process can be reused on the same frame. (default: false)
  91400. * @param textureType Type of textures used when performing the post process. (default: 0)
  91401. * @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)
  91402. */
  91403. function MotionBlurPostProcess(name, scene, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  91404. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  91405. if (blockCompilation === void 0) { blockCompilation = false; }
  91406. var _this = _super.call(this, name, "motionBlur", ["motionStrength", "motionScale", "screenSize"], ["velocitySampler"], options, camera, samplingMode, engine, reusable, "#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0", textureType, undefined, null, blockCompilation) || this;
  91407. /**
  91408. * Defines how much the image is blurred by the movement. Default value is equal to 1
  91409. */
  91410. _this.motionStrength = 1;
  91411. _this._motionBlurSamples = 32;
  91412. _this._geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  91413. if (!_this._geometryBufferRenderer) {
  91414. // Geometry buffer renderer is not supported. So, work as a passthrough.
  91415. BABYLON.Tools.Warn("Multiple Render Target support needed to compute object based motion blur");
  91416. _this.updateEffect();
  91417. }
  91418. else {
  91419. // Geometry buffer renderer is supported.
  91420. _this._geometryBufferRenderer.enableVelocity = true;
  91421. _this.onApply = function (effect) {
  91422. effect.setVector2("screenSize", new BABYLON.Vector2(_this.width, _this.height));
  91423. effect.setFloat("motionScale", scene.getAnimationRatio());
  91424. effect.setFloat("motionStrength", _this.motionStrength);
  91425. if (_this._geometryBufferRenderer) {
  91426. var velocityIndex = _this._geometryBufferRenderer.getTextureIndex(BABYLON.GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE);
  91427. effect.setTexture("velocitySampler", _this._geometryBufferRenderer.getGBuffer().textures[velocityIndex]);
  91428. }
  91429. };
  91430. }
  91431. return _this;
  91432. }
  91433. Object.defineProperty(MotionBlurPostProcess.prototype, "motionBlurSamples", {
  91434. /**
  91435. * Gets the number of iterations are used for motion blur quality. Default value is equal to 32
  91436. */
  91437. get: function () {
  91438. return this._motionBlurSamples;
  91439. },
  91440. /**
  91441. * Sets the number of iterations to be used for motion blur quality
  91442. */
  91443. set: function (samples) {
  91444. this._motionBlurSamples = samples;
  91445. if (this._geometryBufferRenderer) {
  91446. this.updateEffect("#define GEOMETRY_SUPPORTED\n#define SAMPLES " + samples.toFixed(1));
  91447. }
  91448. },
  91449. enumerable: true,
  91450. configurable: true
  91451. });
  91452. /**
  91453. * Disposes the post process.
  91454. * @param camera The camera to dispose the post process on.
  91455. */
  91456. MotionBlurPostProcess.prototype.dispose = function (camera) {
  91457. if (this._geometryBufferRenderer) {
  91458. // Clear previous transformation matrices dictionary used to compute objects velocities
  91459. this._geometryBufferRenderer._previousTransformationMatrices = {};
  91460. }
  91461. _super.prototype.dispose.call(this, camera);
  91462. };
  91463. return MotionBlurPostProcess;
  91464. }(BABYLON.PostProcess));
  91465. BABYLON.MotionBlurPostProcess = MotionBlurPostProcess;
  91466. })(BABYLON || (BABYLON = {}));
  91467. //# sourceMappingURL=motionBlurPostProcess.js.map
  91468. var BABYLON;
  91469. (function (BABYLON) {
  91470. /**
  91471. * Class used to store bone information
  91472. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  91473. */
  91474. var Bone = /** @class */ (function (_super) {
  91475. __extends(Bone, _super);
  91476. /**
  91477. * Create a new bone
  91478. * @param name defines the bone name
  91479. * @param skeleton defines the parent skeleton
  91480. * @param parentBone defines the parent (can be null if the bone is the root)
  91481. * @param localMatrix defines the local matrix
  91482. * @param restPose defines the rest pose matrix
  91483. * @param baseMatrix defines the base matrix
  91484. * @param index defines index of the bone in the hiearchy
  91485. */
  91486. function Bone(
  91487. /**
  91488. * defines the bone name
  91489. */
  91490. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  91491. if (parentBone === void 0) { parentBone = null; }
  91492. if (localMatrix === void 0) { localMatrix = null; }
  91493. if (restPose === void 0) { restPose = null; }
  91494. if (baseMatrix === void 0) { baseMatrix = null; }
  91495. if (index === void 0) { index = null; }
  91496. var _this = _super.call(this, name, skeleton.getScene(), false) || this;
  91497. _this.name = name;
  91498. /**
  91499. * Gets the list of child bones
  91500. */
  91501. _this.children = new Array();
  91502. /** Gets the animations associated with this bone */
  91503. _this.animations = new Array();
  91504. /**
  91505. * @hidden Internal only
  91506. * Set this value to map this bone to a different index in the transform matrices
  91507. * Set this value to -1 to exclude the bone from the transform matrices
  91508. */
  91509. _this._index = null;
  91510. _this._absoluteTransform = new BABYLON.Matrix();
  91511. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  91512. _this._scalingDeterminant = 1;
  91513. _this._worldTransform = new BABYLON.Matrix();
  91514. _this._needToDecompose = true;
  91515. _this._needToCompose = false;
  91516. _this._skeleton = skeleton;
  91517. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  91518. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  91519. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  91520. _this._index = index;
  91521. skeleton.bones.push(_this);
  91522. _this.setParent(parentBone, false);
  91523. if (baseMatrix || localMatrix) {
  91524. _this._updateDifferenceMatrix();
  91525. }
  91526. return _this;
  91527. }
  91528. Object.defineProperty(Bone.prototype, "_matrix", {
  91529. /** @hidden */
  91530. get: function () {
  91531. this._compose();
  91532. return this._localMatrix;
  91533. },
  91534. /** @hidden */
  91535. set: function (value) {
  91536. this._localMatrix.copyFrom(value);
  91537. this._needToDecompose = true;
  91538. },
  91539. enumerable: true,
  91540. configurable: true
  91541. });
  91542. // Members
  91543. /**
  91544. * Gets the parent skeleton
  91545. * @returns a skeleton
  91546. */
  91547. Bone.prototype.getSkeleton = function () {
  91548. return this._skeleton;
  91549. };
  91550. /**
  91551. * Gets parent bone
  91552. * @returns a bone or null if the bone is the root of the bone hierarchy
  91553. */
  91554. Bone.prototype.getParent = function () {
  91555. return this._parent;
  91556. };
  91557. /**
  91558. * Sets the parent bone
  91559. * @param parent defines the parent (can be null if the bone is the root)
  91560. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  91561. */
  91562. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  91563. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  91564. if (this._parent === parent) {
  91565. return;
  91566. }
  91567. if (this._parent) {
  91568. var index = this._parent.children.indexOf(this);
  91569. if (index !== -1) {
  91570. this._parent.children.splice(index, 1);
  91571. }
  91572. }
  91573. this._parent = parent;
  91574. if (this._parent) {
  91575. this._parent.children.push(this);
  91576. }
  91577. if (updateDifferenceMatrix) {
  91578. this._updateDifferenceMatrix();
  91579. }
  91580. this.markAsDirty();
  91581. };
  91582. /**
  91583. * Gets the local matrix
  91584. * @returns a matrix
  91585. */
  91586. Bone.prototype.getLocalMatrix = function () {
  91587. this._compose();
  91588. return this._localMatrix;
  91589. };
  91590. /**
  91591. * Gets the base matrix (initial matrix which remains unchanged)
  91592. * @returns a matrix
  91593. */
  91594. Bone.prototype.getBaseMatrix = function () {
  91595. return this._baseMatrix;
  91596. };
  91597. /**
  91598. * Gets the rest pose matrix
  91599. * @returns a matrix
  91600. */
  91601. Bone.prototype.getRestPose = function () {
  91602. return this._restPose;
  91603. };
  91604. /**
  91605. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  91606. */
  91607. Bone.prototype.getWorldMatrix = function () {
  91608. return this._worldTransform;
  91609. };
  91610. /**
  91611. * Sets the local matrix to rest pose matrix
  91612. */
  91613. Bone.prototype.returnToRest = function () {
  91614. this.updateMatrix(this._restPose.clone());
  91615. };
  91616. /**
  91617. * Gets the inverse of the absolute transform matrix.
  91618. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  91619. * @returns a matrix
  91620. */
  91621. Bone.prototype.getInvertedAbsoluteTransform = function () {
  91622. return this._invertedAbsoluteTransform;
  91623. };
  91624. /**
  91625. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  91626. * @returns a matrix
  91627. */
  91628. Bone.prototype.getAbsoluteTransform = function () {
  91629. return this._absoluteTransform;
  91630. };
  91631. Object.defineProperty(Bone.prototype, "position", {
  91632. // Properties (matches AbstractMesh properties)
  91633. /** Gets or sets current position (in local space) */
  91634. get: function () {
  91635. this._decompose();
  91636. return this._localPosition;
  91637. },
  91638. set: function (newPosition) {
  91639. this._decompose();
  91640. this._localPosition.copyFrom(newPosition);
  91641. this._markAsDirtyAndCompose();
  91642. },
  91643. enumerable: true,
  91644. configurable: true
  91645. });
  91646. Object.defineProperty(Bone.prototype, "rotation", {
  91647. /** Gets or sets current rotation (in local space) */
  91648. get: function () {
  91649. return this.getRotation();
  91650. },
  91651. set: function (newRotation) {
  91652. this.setRotation(newRotation);
  91653. },
  91654. enumerable: true,
  91655. configurable: true
  91656. });
  91657. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  91658. /** Gets or sets current rotation quaternion (in local space) */
  91659. get: function () {
  91660. this._decompose();
  91661. return this._localRotation;
  91662. },
  91663. set: function (newRotation) {
  91664. this.setRotationQuaternion(newRotation);
  91665. },
  91666. enumerable: true,
  91667. configurable: true
  91668. });
  91669. Object.defineProperty(Bone.prototype, "scaling", {
  91670. /** Gets or sets current scaling (in local space) */
  91671. get: function () {
  91672. return this.getScale();
  91673. },
  91674. set: function (newScaling) {
  91675. this.setScale(newScaling);
  91676. },
  91677. enumerable: true,
  91678. configurable: true
  91679. });
  91680. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  91681. /**
  91682. * Gets the animation properties override
  91683. */
  91684. get: function () {
  91685. return this._skeleton.animationPropertiesOverride;
  91686. },
  91687. enumerable: true,
  91688. configurable: true
  91689. });
  91690. // Methods
  91691. Bone.prototype._decompose = function () {
  91692. if (!this._needToDecompose) {
  91693. return;
  91694. }
  91695. this._needToDecompose = false;
  91696. if (!this._localScaling) {
  91697. this._localScaling = BABYLON.Vector3.Zero();
  91698. this._localRotation = BABYLON.Quaternion.Zero();
  91699. this._localPosition = BABYLON.Vector3.Zero();
  91700. }
  91701. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  91702. };
  91703. Bone.prototype._compose = function () {
  91704. if (!this._needToCompose) {
  91705. return;
  91706. }
  91707. this._needToCompose = false;
  91708. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  91709. };
  91710. /**
  91711. * Update the base and local matrices
  91712. * @param matrix defines the new base or local matrix
  91713. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  91714. * @param updateLocalMatrix defines if the local matrix should be updated
  91715. */
  91716. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  91717. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  91718. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  91719. this._baseMatrix.copyFrom(matrix);
  91720. if (updateDifferenceMatrix) {
  91721. this._updateDifferenceMatrix();
  91722. }
  91723. if (updateLocalMatrix) {
  91724. this._localMatrix.copyFrom(matrix);
  91725. this._markAsDirtyAndDecompose();
  91726. }
  91727. else {
  91728. this.markAsDirty();
  91729. }
  91730. };
  91731. /** @hidden */
  91732. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  91733. if (updateChildren === void 0) { updateChildren = true; }
  91734. if (!rootMatrix) {
  91735. rootMatrix = this._baseMatrix;
  91736. }
  91737. if (this._parent) {
  91738. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  91739. }
  91740. else {
  91741. this._absoluteTransform.copyFrom(rootMatrix);
  91742. }
  91743. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  91744. if (updateChildren) {
  91745. for (var index = 0; index < this.children.length; index++) {
  91746. this.children[index]._updateDifferenceMatrix();
  91747. }
  91748. }
  91749. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  91750. };
  91751. /**
  91752. * Flag the bone as dirty (Forcing it to update everything)
  91753. */
  91754. Bone.prototype.markAsDirty = function () {
  91755. this._currentRenderId++;
  91756. this._childRenderId++;
  91757. this._skeleton._markAsDirty();
  91758. };
  91759. Bone.prototype._markAsDirtyAndCompose = function () {
  91760. this.markAsDirty();
  91761. this._needToCompose = true;
  91762. };
  91763. Bone.prototype._markAsDirtyAndDecompose = function () {
  91764. this.markAsDirty();
  91765. this._needToDecompose = true;
  91766. };
  91767. /**
  91768. * Copy an animation range from another bone
  91769. * @param source defines the source bone
  91770. * @param rangeName defines the range name to copy
  91771. * @param frameOffset defines the frame offset
  91772. * @param rescaleAsRequired defines if rescaling must be applied if required
  91773. * @param skelDimensionsRatio defines the scaling ratio
  91774. * @returns true if operation was successful
  91775. */
  91776. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  91777. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  91778. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  91779. // all animation may be coming from a library skeleton, so may need to create animation
  91780. if (this.animations.length === 0) {
  91781. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  91782. this.animations[0].setKeys([]);
  91783. }
  91784. // get animation info / verify there is such a range from the source bone
  91785. var sourceRange = source.animations[0].getRange(rangeName);
  91786. if (!sourceRange) {
  91787. return false;
  91788. }
  91789. var from = sourceRange.from;
  91790. var to = sourceRange.to;
  91791. var sourceKeys = source.animations[0].getKeys();
  91792. // rescaling prep
  91793. var sourceBoneLength = source.length;
  91794. var sourceParent = source.getParent();
  91795. var parent = this.getParent();
  91796. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  91797. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  91798. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  91799. var destKeys = this.animations[0].getKeys();
  91800. // loop vars declaration
  91801. var orig;
  91802. var origTranslation;
  91803. var mat;
  91804. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  91805. orig = sourceKeys[key];
  91806. if (orig.frame >= from && orig.frame <= to) {
  91807. if (rescaleAsRequired) {
  91808. mat = orig.value.clone();
  91809. // scale based on parent ratio, when bone has parent
  91810. if (parentScalingReqd) {
  91811. origTranslation = mat.getTranslation();
  91812. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  91813. // scale based on skeleton dimension ratio when root bone, and value is passed
  91814. }
  91815. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  91816. origTranslation = mat.getTranslation();
  91817. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  91818. // use original when root bone, and no data for skelDimensionsRatio
  91819. }
  91820. else {
  91821. mat = orig.value;
  91822. }
  91823. }
  91824. else {
  91825. mat = orig.value;
  91826. }
  91827. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  91828. }
  91829. }
  91830. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  91831. return true;
  91832. };
  91833. /**
  91834. * Translate the bone in local or world space
  91835. * @param vec The amount to translate the bone
  91836. * @param space The space that the translation is in
  91837. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91838. */
  91839. Bone.prototype.translate = function (vec, space, mesh) {
  91840. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91841. var lm = this.getLocalMatrix();
  91842. if (space == BABYLON.Space.LOCAL) {
  91843. lm.addAtIndex(12, vec.x);
  91844. lm.addAtIndex(13, vec.y);
  91845. lm.addAtIndex(14, vec.z);
  91846. }
  91847. else {
  91848. var wm = null;
  91849. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  91850. if (mesh) {
  91851. wm = mesh.getWorldMatrix();
  91852. }
  91853. this._skeleton.computeAbsoluteTransforms();
  91854. var tmat = Bone._tmpMats[0];
  91855. var tvec = Bone._tmpVecs[0];
  91856. if (this._parent) {
  91857. if (mesh && wm) {
  91858. tmat.copyFrom(this._parent.getAbsoluteTransform());
  91859. tmat.multiplyToRef(wm, tmat);
  91860. }
  91861. else {
  91862. tmat.copyFrom(this._parent.getAbsoluteTransform());
  91863. }
  91864. }
  91865. tmat.setTranslationFromFloats(0, 0, 0);
  91866. tmat.invert();
  91867. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  91868. lm.addAtIndex(12, tvec.x);
  91869. lm.addAtIndex(13, tvec.y);
  91870. lm.addAtIndex(14, tvec.z);
  91871. }
  91872. this._markAsDirtyAndDecompose();
  91873. };
  91874. /**
  91875. * Set the postion of the bone in local or world space
  91876. * @param position The position to set the bone
  91877. * @param space The space that the position is in
  91878. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91879. */
  91880. Bone.prototype.setPosition = function (position, space, mesh) {
  91881. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91882. var lm = this.getLocalMatrix();
  91883. if (space == BABYLON.Space.LOCAL) {
  91884. lm.setTranslationFromFloats(position.x, position.y, position.z);
  91885. }
  91886. else {
  91887. var wm = null;
  91888. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  91889. if (mesh) {
  91890. wm = mesh.getWorldMatrix();
  91891. }
  91892. this._skeleton.computeAbsoluteTransforms();
  91893. var tmat = Bone._tmpMats[0];
  91894. var vec = Bone._tmpVecs[0];
  91895. if (this._parent) {
  91896. if (mesh && wm) {
  91897. tmat.copyFrom(this._parent.getAbsoluteTransform());
  91898. tmat.multiplyToRef(wm, tmat);
  91899. }
  91900. else {
  91901. tmat.copyFrom(this._parent.getAbsoluteTransform());
  91902. }
  91903. }
  91904. tmat.invert();
  91905. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  91906. lm.setTranslationFromFloats(vec.x, vec.y, vec.z);
  91907. }
  91908. this._markAsDirtyAndDecompose();
  91909. };
  91910. /**
  91911. * Set the absolute position of the bone (world space)
  91912. * @param position The position to set the bone
  91913. * @param mesh The mesh that this bone is attached to
  91914. */
  91915. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  91916. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  91917. };
  91918. /**
  91919. * Scale the bone on the x, y and z axes (in local space)
  91920. * @param x The amount to scale the bone on the x axis
  91921. * @param y The amount to scale the bone on the y axis
  91922. * @param z The amount to scale the bone on the z axis
  91923. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  91924. */
  91925. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  91926. if (scaleChildren === void 0) { scaleChildren = false; }
  91927. var locMat = this.getLocalMatrix();
  91928. // Apply new scaling on top of current local matrix
  91929. var scaleMat = Bone._tmpMats[0];
  91930. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  91931. scaleMat.multiplyToRef(locMat, locMat);
  91932. // Invert scaling matrix and apply the inverse to all children
  91933. scaleMat.invert();
  91934. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  91935. var child = _a[_i];
  91936. var cm = child.getLocalMatrix();
  91937. cm.multiplyToRef(scaleMat, cm);
  91938. cm.multiplyAtIndex(12, x);
  91939. cm.multiplyAtIndex(13, y);
  91940. cm.multiplyAtIndex(14, z);
  91941. child._markAsDirtyAndDecompose();
  91942. }
  91943. this._markAsDirtyAndDecompose();
  91944. if (scaleChildren) {
  91945. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  91946. var child = _c[_b];
  91947. child.scale(x, y, z, scaleChildren);
  91948. }
  91949. }
  91950. };
  91951. /**
  91952. * Set the bone scaling in local space
  91953. * @param scale defines the scaling vector
  91954. */
  91955. Bone.prototype.setScale = function (scale) {
  91956. this._decompose();
  91957. this._localScaling.copyFrom(scale);
  91958. this._markAsDirtyAndCompose();
  91959. };
  91960. /**
  91961. * Gets the current scaling in local space
  91962. * @returns the current scaling vector
  91963. */
  91964. Bone.prototype.getScale = function () {
  91965. this._decompose();
  91966. return this._localScaling;
  91967. };
  91968. /**
  91969. * Gets the current scaling in local space and stores it in a target vector
  91970. * @param result defines the target vector
  91971. */
  91972. Bone.prototype.getScaleToRef = function (result) {
  91973. this._decompose();
  91974. result.copyFrom(this._localScaling);
  91975. };
  91976. /**
  91977. * Set the yaw, pitch, and roll of the bone in local or world space
  91978. * @param yaw The rotation of the bone on the y axis
  91979. * @param pitch The rotation of the bone on the x axis
  91980. * @param roll The rotation of the bone on the z axis
  91981. * @param space The space that the axes of rotation are in
  91982. * @param mesh The mesh that this bone is attached to. This is only used in world space
  91983. */
  91984. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  91985. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  91986. if (space === BABYLON.Space.LOCAL) {
  91987. var quat = Bone._tmpQuat;
  91988. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  91989. this.setRotationQuaternion(quat, space, mesh);
  91990. return;
  91991. }
  91992. var rotMatInv = Bone._tmpMats[0];
  91993. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  91994. return;
  91995. }
  91996. var rotMat = Bone._tmpMats[1];
  91997. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  91998. rotMatInv.multiplyToRef(rotMat, rotMat);
  91999. this._rotateWithMatrix(rotMat, space, mesh);
  92000. };
  92001. /**
  92002. * Add a rotation to the bone on an axis in local or world space
  92003. * @param axis The axis to rotate the bone on
  92004. * @param amount The amount to rotate the bone
  92005. * @param space The space that the axis is in
  92006. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92007. */
  92008. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  92009. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92010. var rmat = Bone._tmpMats[0];
  92011. rmat.setTranslationFromFloats(0, 0, 0);
  92012. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  92013. this._rotateWithMatrix(rmat, space, mesh);
  92014. };
  92015. /**
  92016. * Set the rotation of the bone to a particular axis angle in local or world space
  92017. * @param axis The axis to rotate the bone on
  92018. * @param angle The angle that the bone should be rotated to
  92019. * @param space The space that the axis is in
  92020. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92021. */
  92022. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  92023. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92024. if (space === BABYLON.Space.LOCAL) {
  92025. var quat = Bone._tmpQuat;
  92026. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  92027. this.setRotationQuaternion(quat, space, mesh);
  92028. return;
  92029. }
  92030. var rotMatInv = Bone._tmpMats[0];
  92031. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  92032. return;
  92033. }
  92034. var rotMat = Bone._tmpMats[1];
  92035. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  92036. rotMatInv.multiplyToRef(rotMat, rotMat);
  92037. this._rotateWithMatrix(rotMat, space, mesh);
  92038. };
  92039. /**
  92040. * Set the euler rotation of the bone in local of world space
  92041. * @param rotation The euler rotation that the bone should be set to
  92042. * @param space The space that the rotation is in
  92043. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92044. */
  92045. Bone.prototype.setRotation = function (rotation, space, mesh) {
  92046. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92047. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  92048. };
  92049. /**
  92050. * Set the quaternion rotation of the bone in local of world space
  92051. * @param quat The quaternion rotation that the bone should be set to
  92052. * @param space The space that the rotation is in
  92053. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92054. */
  92055. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  92056. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92057. if (space === BABYLON.Space.LOCAL) {
  92058. this._decompose();
  92059. this._localRotation.copyFrom(quat);
  92060. this._markAsDirtyAndCompose();
  92061. return;
  92062. }
  92063. var rotMatInv = Bone._tmpMats[0];
  92064. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  92065. return;
  92066. }
  92067. var rotMat = Bone._tmpMats[1];
  92068. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  92069. rotMatInv.multiplyToRef(rotMat, rotMat);
  92070. this._rotateWithMatrix(rotMat, space, mesh);
  92071. };
  92072. /**
  92073. * Set the rotation matrix of the bone in local of world space
  92074. * @param rotMat The rotation matrix that the bone should be set to
  92075. * @param space The space that the rotation is in
  92076. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92077. */
  92078. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  92079. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92080. if (space === BABYLON.Space.LOCAL) {
  92081. var quat = Bone._tmpQuat;
  92082. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  92083. this.setRotationQuaternion(quat, space, mesh);
  92084. return;
  92085. }
  92086. var rotMatInv = Bone._tmpMats[0];
  92087. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  92088. return;
  92089. }
  92090. var rotMat2 = Bone._tmpMats[1];
  92091. rotMat2.copyFrom(rotMat);
  92092. rotMatInv.multiplyToRef(rotMat, rotMat2);
  92093. this._rotateWithMatrix(rotMat2, space, mesh);
  92094. };
  92095. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  92096. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92097. var lmat = this.getLocalMatrix();
  92098. var lx = lmat.m[12];
  92099. var ly = lmat.m[13];
  92100. var lz = lmat.m[14];
  92101. var parent = this.getParent();
  92102. var parentScale = Bone._tmpMats[3];
  92103. var parentScaleInv = Bone._tmpMats[4];
  92104. if (parent && space == BABYLON.Space.WORLD) {
  92105. if (mesh) {
  92106. parentScale.copyFrom(mesh.getWorldMatrix());
  92107. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  92108. }
  92109. else {
  92110. parentScale.copyFrom(parent.getAbsoluteTransform());
  92111. }
  92112. parentScaleInv.copyFrom(parentScale);
  92113. parentScaleInv.invert();
  92114. lmat.multiplyToRef(parentScale, lmat);
  92115. lmat.multiplyToRef(rmat, lmat);
  92116. lmat.multiplyToRef(parentScaleInv, lmat);
  92117. }
  92118. else {
  92119. if (space == BABYLON.Space.WORLD && mesh) {
  92120. parentScale.copyFrom(mesh.getWorldMatrix());
  92121. parentScaleInv.copyFrom(parentScale);
  92122. parentScaleInv.invert();
  92123. lmat.multiplyToRef(parentScale, lmat);
  92124. lmat.multiplyToRef(rmat, lmat);
  92125. lmat.multiplyToRef(parentScaleInv, lmat);
  92126. }
  92127. else {
  92128. lmat.multiplyToRef(rmat, lmat);
  92129. }
  92130. }
  92131. lmat.setTranslationFromFloats(lx, ly, lz);
  92132. this.computeAbsoluteTransforms();
  92133. this._markAsDirtyAndDecompose();
  92134. };
  92135. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  92136. var scaleMatrix = Bone._tmpMats[2];
  92137. rotMatInv.copyFrom(this.getAbsoluteTransform());
  92138. if (mesh) {
  92139. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  92140. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  92141. }
  92142. rotMatInv.invert();
  92143. if (isNaN(rotMatInv.m[0])) {
  92144. // Matrix failed to invert.
  92145. // This can happen if scale is zero for example.
  92146. return false;
  92147. }
  92148. scaleMatrix.multiplyAtIndex(0, this._scalingDeterminant);
  92149. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  92150. return true;
  92151. };
  92152. /**
  92153. * Get the position of the bone in local or world space
  92154. * @param space The space that the returned position is in
  92155. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92156. * @returns The position of the bone
  92157. */
  92158. Bone.prototype.getPosition = function (space, mesh) {
  92159. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92160. if (mesh === void 0) { mesh = null; }
  92161. var pos = BABYLON.Vector3.Zero();
  92162. this.getPositionToRef(space, mesh, pos);
  92163. return pos;
  92164. };
  92165. /**
  92166. * Copy the position of the bone to a vector3 in local or world space
  92167. * @param space The space that the returned position is in
  92168. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92169. * @param result The vector3 to copy the position to
  92170. */
  92171. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  92172. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92173. if (space == BABYLON.Space.LOCAL) {
  92174. var lm = this.getLocalMatrix();
  92175. result.x = lm.m[12];
  92176. result.y = lm.m[13];
  92177. result.z = lm.m[14];
  92178. }
  92179. else {
  92180. var wm = null;
  92181. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92182. if (mesh) {
  92183. wm = mesh.getWorldMatrix();
  92184. }
  92185. this._skeleton.computeAbsoluteTransforms();
  92186. var tmat = Bone._tmpMats[0];
  92187. if (mesh && wm) {
  92188. tmat.copyFrom(this.getAbsoluteTransform());
  92189. tmat.multiplyToRef(wm, tmat);
  92190. }
  92191. else {
  92192. tmat = this.getAbsoluteTransform();
  92193. }
  92194. result.x = tmat.m[12];
  92195. result.y = tmat.m[13];
  92196. result.z = tmat.m[14];
  92197. }
  92198. };
  92199. /**
  92200. * Get the absolute position of the bone (world space)
  92201. * @param mesh The mesh that this bone is attached to
  92202. * @returns The absolute position of the bone
  92203. */
  92204. Bone.prototype.getAbsolutePosition = function (mesh) {
  92205. if (mesh === void 0) { mesh = null; }
  92206. var pos = BABYLON.Vector3.Zero();
  92207. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  92208. return pos;
  92209. };
  92210. /**
  92211. * Copy the absolute position of the bone (world space) to the result param
  92212. * @param mesh The mesh that this bone is attached to
  92213. * @param result The vector3 to copy the absolute position to
  92214. */
  92215. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  92216. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  92217. };
  92218. /**
  92219. * Compute the absolute transforms of this bone and its children
  92220. */
  92221. Bone.prototype.computeAbsoluteTransforms = function () {
  92222. this._compose();
  92223. if (this._parent) {
  92224. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  92225. }
  92226. else {
  92227. this._absoluteTransform.copyFrom(this._localMatrix);
  92228. var poseMatrix = this._skeleton.getPoseMatrix();
  92229. if (poseMatrix) {
  92230. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  92231. }
  92232. }
  92233. var children = this.children;
  92234. var len = children.length;
  92235. for (var i = 0; i < len; i++) {
  92236. children[i].computeAbsoluteTransforms();
  92237. }
  92238. };
  92239. /**
  92240. * Get the world direction from an axis that is in the local space of the bone
  92241. * @param localAxis The local direction that is used to compute the world direction
  92242. * @param mesh The mesh that this bone is attached to
  92243. * @returns The world direction
  92244. */
  92245. Bone.prototype.getDirection = function (localAxis, mesh) {
  92246. if (mesh === void 0) { mesh = null; }
  92247. var result = BABYLON.Vector3.Zero();
  92248. this.getDirectionToRef(localAxis, mesh, result);
  92249. return result;
  92250. };
  92251. /**
  92252. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  92253. * @param localAxis The local direction that is used to compute the world direction
  92254. * @param mesh The mesh that this bone is attached to
  92255. * @param result The vector3 that the world direction will be copied to
  92256. */
  92257. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  92258. if (mesh === void 0) { mesh = null; }
  92259. var wm = null;
  92260. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92261. if (mesh) {
  92262. wm = mesh.getWorldMatrix();
  92263. }
  92264. this._skeleton.computeAbsoluteTransforms();
  92265. var mat = Bone._tmpMats[0];
  92266. mat.copyFrom(this.getAbsoluteTransform());
  92267. if (mesh && wm) {
  92268. mat.multiplyToRef(wm, mat);
  92269. }
  92270. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  92271. result.normalize();
  92272. };
  92273. /**
  92274. * Get the euler rotation of the bone in local or world space
  92275. * @param space The space that the rotation should be in
  92276. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92277. * @returns The euler rotation
  92278. */
  92279. Bone.prototype.getRotation = function (space, mesh) {
  92280. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92281. if (mesh === void 0) { mesh = null; }
  92282. var result = BABYLON.Vector3.Zero();
  92283. this.getRotationToRef(space, mesh, result);
  92284. return result;
  92285. };
  92286. /**
  92287. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  92288. * @param space The space that the rotation should be in
  92289. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92290. * @param result The vector3 that the rotation should be copied to
  92291. */
  92292. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  92293. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92294. if (mesh === void 0) { mesh = null; }
  92295. var quat = Bone._tmpQuat;
  92296. this.getRotationQuaternionToRef(space, mesh, quat);
  92297. quat.toEulerAnglesToRef(result);
  92298. };
  92299. /**
  92300. * Get the quaternion rotation of the bone in either local or world space
  92301. * @param space The space that the rotation should be in
  92302. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92303. * @returns The quaternion rotation
  92304. */
  92305. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  92306. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92307. if (mesh === void 0) { mesh = null; }
  92308. var result = BABYLON.Quaternion.Identity();
  92309. this.getRotationQuaternionToRef(space, mesh, result);
  92310. return result;
  92311. };
  92312. /**
  92313. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  92314. * @param space The space that the rotation should be in
  92315. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92316. * @param result The quaternion that the rotation should be copied to
  92317. */
  92318. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  92319. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92320. if (mesh === void 0) { mesh = null; }
  92321. if (space == BABYLON.Space.LOCAL) {
  92322. this._decompose();
  92323. result.copyFrom(this._localRotation);
  92324. }
  92325. else {
  92326. var mat = Bone._tmpMats[0];
  92327. var amat = this.getAbsoluteTransform();
  92328. if (mesh) {
  92329. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  92330. }
  92331. else {
  92332. mat.copyFrom(amat);
  92333. }
  92334. mat.multiplyAtIndex(0, this._scalingDeterminant);
  92335. mat.multiplyAtIndex(1, this._scalingDeterminant);
  92336. mat.multiplyAtIndex(2, this._scalingDeterminant);
  92337. mat.decompose(undefined, result, undefined);
  92338. }
  92339. };
  92340. /**
  92341. * Get the rotation matrix of the bone in local or world space
  92342. * @param space The space that the rotation should be in
  92343. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92344. * @returns The rotation matrix
  92345. */
  92346. Bone.prototype.getRotationMatrix = function (space, mesh) {
  92347. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92348. var result = BABYLON.Matrix.Identity();
  92349. this.getRotationMatrixToRef(space, mesh, result);
  92350. return result;
  92351. };
  92352. /**
  92353. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  92354. * @param space The space that the rotation should be in
  92355. * @param mesh The mesh that this bone is attached to. This is only used in world space
  92356. * @param result The quaternion that the rotation should be copied to
  92357. */
  92358. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  92359. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  92360. if (space == BABYLON.Space.LOCAL) {
  92361. this.getLocalMatrix().getRotationMatrixToRef(result);
  92362. }
  92363. else {
  92364. var mat = Bone._tmpMats[0];
  92365. var amat = this.getAbsoluteTransform();
  92366. if (mesh) {
  92367. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  92368. }
  92369. else {
  92370. mat.copyFrom(amat);
  92371. }
  92372. mat.multiplyAtIndex(0, this._scalingDeterminant);
  92373. mat.multiplyAtIndex(1, this._scalingDeterminant);
  92374. mat.multiplyAtIndex(2, this._scalingDeterminant);
  92375. mat.getRotationMatrixToRef(result);
  92376. }
  92377. };
  92378. /**
  92379. * Get the world position of a point that is in the local space of the bone
  92380. * @param position The local position
  92381. * @param mesh The mesh that this bone is attached to
  92382. * @returns The world position
  92383. */
  92384. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  92385. if (mesh === void 0) { mesh = null; }
  92386. var result = BABYLON.Vector3.Zero();
  92387. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  92388. return result;
  92389. };
  92390. /**
  92391. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  92392. * @param position The local position
  92393. * @param mesh The mesh that this bone is attached to
  92394. * @param result The vector3 that the world position should be copied to
  92395. */
  92396. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  92397. if (mesh === void 0) { mesh = null; }
  92398. var wm = null;
  92399. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92400. if (mesh) {
  92401. wm = mesh.getWorldMatrix();
  92402. }
  92403. this._skeleton.computeAbsoluteTransforms();
  92404. var tmat = Bone._tmpMats[0];
  92405. if (mesh && wm) {
  92406. tmat.copyFrom(this.getAbsoluteTransform());
  92407. tmat.multiplyToRef(wm, tmat);
  92408. }
  92409. else {
  92410. tmat = this.getAbsoluteTransform();
  92411. }
  92412. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  92413. };
  92414. /**
  92415. * Get the local position of a point that is in world space
  92416. * @param position The world position
  92417. * @param mesh The mesh that this bone is attached to
  92418. * @returns The local position
  92419. */
  92420. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  92421. if (mesh === void 0) { mesh = null; }
  92422. var result = BABYLON.Vector3.Zero();
  92423. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  92424. return result;
  92425. };
  92426. /**
  92427. * Get the local position of a point that is in world space and copy it to the result param
  92428. * @param position The world position
  92429. * @param mesh The mesh that this bone is attached to
  92430. * @param result The vector3 that the local position should be copied to
  92431. */
  92432. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  92433. if (mesh === void 0) { mesh = null; }
  92434. var wm = null;
  92435. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  92436. if (mesh) {
  92437. wm = mesh.getWorldMatrix();
  92438. }
  92439. this._skeleton.computeAbsoluteTransforms();
  92440. var tmat = Bone._tmpMats[0];
  92441. tmat.copyFrom(this.getAbsoluteTransform());
  92442. if (mesh && wm) {
  92443. tmat.multiplyToRef(wm, tmat);
  92444. }
  92445. tmat.invert();
  92446. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  92447. };
  92448. Bone._tmpVecs = BABYLON.Tools.BuildArray(2, BABYLON.Vector3.Zero);
  92449. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  92450. Bone._tmpMats = BABYLON.Tools.BuildArray(5, BABYLON.Matrix.Identity);
  92451. return Bone;
  92452. }(BABYLON.Node));
  92453. BABYLON.Bone = Bone;
  92454. })(BABYLON || (BABYLON = {}));
  92455. //# sourceMappingURL=bone.js.map
  92456. var BABYLON;
  92457. (function (BABYLON) {
  92458. /**
  92459. * Class used to apply inverse kinematics to bones
  92460. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  92461. */
  92462. var BoneIKController = /** @class */ (function () {
  92463. /**
  92464. * Creates a new BoneIKController
  92465. * @param mesh defines the mesh to control
  92466. * @param bone defines the bone to control
  92467. * @param options defines options to set up the controller
  92468. */
  92469. function BoneIKController(mesh, bone, options) {
  92470. /**
  92471. * Gets or sets the target position
  92472. */
  92473. this.targetPosition = BABYLON.Vector3.Zero();
  92474. /**
  92475. * Gets or sets the pole target position
  92476. */
  92477. this.poleTargetPosition = BABYLON.Vector3.Zero();
  92478. /**
  92479. * Gets or sets the pole target local offset
  92480. */
  92481. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  92482. /**
  92483. * Gets or sets the pole angle
  92484. */
  92485. this.poleAngle = 0;
  92486. /**
  92487. * 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)
  92488. */
  92489. this.slerpAmount = 1;
  92490. this._bone1Quat = BABYLON.Quaternion.Identity();
  92491. this._bone1Mat = BABYLON.Matrix.Identity();
  92492. this._bone2Ang = Math.PI;
  92493. this._maxAngle = Math.PI;
  92494. this._rightHandedSystem = false;
  92495. this._bendAxis = BABYLON.Vector3.Right();
  92496. this._slerping = false;
  92497. this._adjustRoll = 0;
  92498. this._bone2 = bone;
  92499. this._bone1 = bone.getParent();
  92500. if (!this._bone1) {
  92501. return;
  92502. }
  92503. this.mesh = mesh;
  92504. var bonePos = bone.getPosition();
  92505. if (bone.getAbsoluteTransform().determinant() > 0) {
  92506. this._rightHandedSystem = true;
  92507. this._bendAxis.x = 0;
  92508. this._bendAxis.y = 0;
  92509. this._bendAxis.z = -1;
  92510. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  92511. this._adjustRoll = Math.PI * .5;
  92512. this._bendAxis.z = 1;
  92513. }
  92514. }
  92515. if (this._bone1.length) {
  92516. var boneScale1 = this._bone1.getScale();
  92517. var boneScale2 = this._bone2.getScale();
  92518. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  92519. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  92520. }
  92521. else if (this._bone1.children[0]) {
  92522. mesh.computeWorldMatrix(true);
  92523. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  92524. var pos2 = this._bone2.getAbsolutePosition(mesh);
  92525. var pos3 = this._bone1.getAbsolutePosition(mesh);
  92526. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  92527. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  92528. }
  92529. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  92530. this.maxAngle = Math.PI;
  92531. if (options) {
  92532. if (options.targetMesh) {
  92533. this.targetMesh = options.targetMesh;
  92534. this.targetMesh.computeWorldMatrix(true);
  92535. }
  92536. if (options.poleTargetMesh) {
  92537. this.poleTargetMesh = options.poleTargetMesh;
  92538. this.poleTargetMesh.computeWorldMatrix(true);
  92539. }
  92540. else if (options.poleTargetBone) {
  92541. this.poleTargetBone = options.poleTargetBone;
  92542. }
  92543. else if (this._bone1.getParent()) {
  92544. this.poleTargetBone = this._bone1.getParent();
  92545. }
  92546. if (options.poleTargetLocalOffset) {
  92547. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  92548. }
  92549. if (options.poleAngle) {
  92550. this.poleAngle = options.poleAngle;
  92551. }
  92552. if (options.bendAxis) {
  92553. this._bendAxis.copyFrom(options.bendAxis);
  92554. }
  92555. if (options.maxAngle) {
  92556. this.maxAngle = options.maxAngle;
  92557. }
  92558. if (options.slerpAmount) {
  92559. this.slerpAmount = options.slerpAmount;
  92560. }
  92561. }
  92562. }
  92563. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  92564. /**
  92565. * Gets or sets maximum allowed angle
  92566. */
  92567. get: function () {
  92568. return this._maxAngle;
  92569. },
  92570. set: function (value) {
  92571. this._setMaxAngle(value);
  92572. },
  92573. enumerable: true,
  92574. configurable: true
  92575. });
  92576. BoneIKController.prototype._setMaxAngle = function (ang) {
  92577. if (ang < 0) {
  92578. ang = 0;
  92579. }
  92580. if (ang > Math.PI || ang == undefined) {
  92581. ang = Math.PI;
  92582. }
  92583. this._maxAngle = ang;
  92584. var a = this._bone1Length;
  92585. var b = this._bone2Length;
  92586. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  92587. };
  92588. /**
  92589. * Force the controller to update the bones
  92590. */
  92591. BoneIKController.prototype.update = function () {
  92592. var bone1 = this._bone1;
  92593. if (!bone1) {
  92594. return;
  92595. }
  92596. var target = this.targetPosition;
  92597. var poleTarget = this.poleTargetPosition;
  92598. var mat1 = BoneIKController._tmpMats[0];
  92599. var mat2 = BoneIKController._tmpMats[1];
  92600. if (this.targetMesh) {
  92601. target.copyFrom(this.targetMesh.getAbsolutePosition());
  92602. }
  92603. if (this.poleTargetBone) {
  92604. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  92605. }
  92606. else if (this.poleTargetMesh) {
  92607. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  92608. }
  92609. var bonePos = BoneIKController._tmpVecs[0];
  92610. var zaxis = BoneIKController._tmpVecs[1];
  92611. var xaxis = BoneIKController._tmpVecs[2];
  92612. var yaxis = BoneIKController._tmpVecs[3];
  92613. var upAxis = BoneIKController._tmpVecs[4];
  92614. var _tmpQuat = BoneIKController._tmpQuat;
  92615. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  92616. poleTarget.subtractToRef(bonePos, upAxis);
  92617. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  92618. upAxis.y = 1;
  92619. }
  92620. else {
  92621. upAxis.normalize();
  92622. }
  92623. target.subtractToRef(bonePos, yaxis);
  92624. yaxis.normalize();
  92625. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  92626. zaxis.normalize();
  92627. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  92628. xaxis.normalize();
  92629. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  92630. var a = this._bone1Length;
  92631. var b = this._bone2Length;
  92632. var c = BABYLON.Vector3.Distance(bonePos, target);
  92633. if (this._maxReach > 0) {
  92634. c = Math.min(this._maxReach, c);
  92635. }
  92636. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  92637. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  92638. if (acosa > 1) {
  92639. acosa = 1;
  92640. }
  92641. if (acosb > 1) {
  92642. acosb = 1;
  92643. }
  92644. if (acosa < -1) {
  92645. acosa = -1;
  92646. }
  92647. if (acosb < -1) {
  92648. acosb = -1;
  92649. }
  92650. var angA = Math.acos(acosa);
  92651. var angB = Math.acos(acosb);
  92652. var angC = -angA - angB;
  92653. if (this._rightHandedSystem) {
  92654. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  92655. mat2.multiplyToRef(mat1, mat1);
  92656. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  92657. mat2.multiplyToRef(mat1, mat1);
  92658. }
  92659. else {
  92660. var _tmpVec = BoneIKController._tmpVecs[5];
  92661. _tmpVec.copyFrom(this._bendAxis);
  92662. _tmpVec.x *= -1;
  92663. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  92664. mat2.multiplyToRef(mat1, mat1);
  92665. }
  92666. if (this.poleAngle) {
  92667. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  92668. mat1.multiplyToRef(mat2, mat1);
  92669. }
  92670. if (this._bone1) {
  92671. if (this.slerpAmount < 1) {
  92672. if (!this._slerping) {
  92673. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  92674. }
  92675. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  92676. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  92677. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  92678. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  92679. this._slerping = true;
  92680. }
  92681. else {
  92682. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  92683. this._bone1Mat.copyFrom(mat1);
  92684. this._slerping = false;
  92685. }
  92686. }
  92687. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  92688. this._bone2Ang = angC;
  92689. };
  92690. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  92691. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  92692. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  92693. return BoneIKController;
  92694. }());
  92695. BABYLON.BoneIKController = BoneIKController;
  92696. })(BABYLON || (BABYLON = {}));
  92697. //# sourceMappingURL=boneIKController.js.map
  92698. var BABYLON;
  92699. (function (BABYLON) {
  92700. /**
  92701. * Class used to make a bone look toward a point in space
  92702. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  92703. */
  92704. var BoneLookController = /** @class */ (function () {
  92705. /**
  92706. * Create a BoneLookController
  92707. * @param mesh the mesh that the bone belongs to
  92708. * @param bone the bone that will be looking to the target
  92709. * @param target the target Vector3 to look at
  92710. * @param settings optional settings:
  92711. * * maxYaw: the maximum angle the bone will yaw to
  92712. * * minYaw: the minimum angle the bone will yaw to
  92713. * * maxPitch: the maximum angle the bone will pitch to
  92714. * * minPitch: the minimum angle the bone will yaw to
  92715. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  92716. * * upAxis: the up axis of the coordinate system
  92717. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  92718. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  92719. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  92720. * * adjustYaw: used to make an adjustment to the yaw of the bone
  92721. * * adjustPitch: used to make an adjustment to the pitch of the bone
  92722. * * adjustRoll: used to make an adjustment to the roll of the bone
  92723. **/
  92724. function BoneLookController(mesh, bone, target, options) {
  92725. /**
  92726. * The up axis of the coordinate system that is used when the bone is rotated
  92727. */
  92728. this.upAxis = BABYLON.Vector3.Up();
  92729. /**
  92730. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  92731. */
  92732. this.upAxisSpace = BABYLON.Space.LOCAL;
  92733. /**
  92734. * Used to make an adjustment to the yaw of the bone
  92735. */
  92736. this.adjustYaw = 0;
  92737. /**
  92738. * Used to make an adjustment to the pitch of the bone
  92739. */
  92740. this.adjustPitch = 0;
  92741. /**
  92742. * Used to make an adjustment to the roll of the bone
  92743. */
  92744. this.adjustRoll = 0;
  92745. /**
  92746. * 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)
  92747. */
  92748. this.slerpAmount = 1;
  92749. this._boneQuat = BABYLON.Quaternion.Identity();
  92750. this._slerping = false;
  92751. this._firstFrameSkipped = false;
  92752. this._fowardAxis = BABYLON.Vector3.Forward();
  92753. this.mesh = mesh;
  92754. this.bone = bone;
  92755. this.target = target;
  92756. if (options) {
  92757. if (options.adjustYaw) {
  92758. this.adjustYaw = options.adjustYaw;
  92759. }
  92760. if (options.adjustPitch) {
  92761. this.adjustPitch = options.adjustPitch;
  92762. }
  92763. if (options.adjustRoll) {
  92764. this.adjustRoll = options.adjustRoll;
  92765. }
  92766. if (options.maxYaw != null) {
  92767. this.maxYaw = options.maxYaw;
  92768. }
  92769. else {
  92770. this.maxYaw = Math.PI;
  92771. }
  92772. if (options.minYaw != null) {
  92773. this.minYaw = options.minYaw;
  92774. }
  92775. else {
  92776. this.minYaw = -Math.PI;
  92777. }
  92778. if (options.maxPitch != null) {
  92779. this.maxPitch = options.maxPitch;
  92780. }
  92781. else {
  92782. this.maxPitch = Math.PI;
  92783. }
  92784. if (options.minPitch != null) {
  92785. this.minPitch = options.minPitch;
  92786. }
  92787. else {
  92788. this.minPitch = -Math.PI;
  92789. }
  92790. if (options.slerpAmount != null) {
  92791. this.slerpAmount = options.slerpAmount;
  92792. }
  92793. if (options.upAxis != null) {
  92794. this.upAxis = options.upAxis;
  92795. }
  92796. if (options.upAxisSpace != null) {
  92797. this.upAxisSpace = options.upAxisSpace;
  92798. }
  92799. if (options.yawAxis != null || options.pitchAxis != null) {
  92800. var newYawAxis = BABYLON.Axis.Y;
  92801. var newPitchAxis = BABYLON.Axis.X;
  92802. if (options.yawAxis != null) {
  92803. newYawAxis = options.yawAxis.clone();
  92804. newYawAxis.normalize();
  92805. }
  92806. if (options.pitchAxis != null) {
  92807. newPitchAxis = options.pitchAxis.clone();
  92808. newPitchAxis.normalize();
  92809. }
  92810. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  92811. this._transformYawPitch = BABYLON.Matrix.Identity();
  92812. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  92813. this._transformYawPitchInv = this._transformYawPitch.clone();
  92814. this._transformYawPitch.invert();
  92815. }
  92816. }
  92817. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  92818. this.upAxisSpace = BABYLON.Space.LOCAL;
  92819. }
  92820. }
  92821. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  92822. /**
  92823. * Gets or sets the minimum yaw angle that the bone can look to
  92824. */
  92825. get: function () {
  92826. return this._minYaw;
  92827. },
  92828. set: function (value) {
  92829. this._minYaw = value;
  92830. this._minYawSin = Math.sin(value);
  92831. this._minYawCos = Math.cos(value);
  92832. if (this._maxYaw != null) {
  92833. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  92834. this._yawRange = this._maxYaw - this._minYaw;
  92835. }
  92836. },
  92837. enumerable: true,
  92838. configurable: true
  92839. });
  92840. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  92841. /**
  92842. * Gets or sets the maximum yaw angle that the bone can look to
  92843. */
  92844. get: function () {
  92845. return this._maxYaw;
  92846. },
  92847. set: function (value) {
  92848. this._maxYaw = value;
  92849. this._maxYawSin = Math.sin(value);
  92850. this._maxYawCos = Math.cos(value);
  92851. if (this._minYaw != null) {
  92852. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  92853. this._yawRange = this._maxYaw - this._minYaw;
  92854. }
  92855. },
  92856. enumerable: true,
  92857. configurable: true
  92858. });
  92859. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  92860. /**
  92861. * Gets or sets the minimum pitch angle that the bone can look to
  92862. */
  92863. get: function () {
  92864. return this._minPitch;
  92865. },
  92866. set: function (value) {
  92867. this._minPitch = value;
  92868. this._minPitchTan = Math.tan(value);
  92869. },
  92870. enumerable: true,
  92871. configurable: true
  92872. });
  92873. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  92874. /**
  92875. * Gets or sets the maximum pitch angle that the bone can look to
  92876. */
  92877. get: function () {
  92878. return this._maxPitch;
  92879. },
  92880. set: function (value) {
  92881. this._maxPitch = value;
  92882. this._maxPitchTan = Math.tan(value);
  92883. },
  92884. enumerable: true,
  92885. configurable: true
  92886. });
  92887. /**
  92888. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  92889. */
  92890. BoneLookController.prototype.update = function () {
  92891. //skip the first frame when slerping so that the mesh rotation is correct
  92892. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  92893. this._firstFrameSkipped = true;
  92894. return;
  92895. }
  92896. var bone = this.bone;
  92897. var bonePos = BoneLookController._tmpVecs[0];
  92898. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  92899. var target = this.target;
  92900. var _tmpMat1 = BoneLookController._tmpMats[0];
  92901. var _tmpMat2 = BoneLookController._tmpMats[1];
  92902. var mesh = this.mesh;
  92903. var parentBone = bone.getParent();
  92904. var upAxis = BoneLookController._tmpVecs[1];
  92905. upAxis.copyFrom(this.upAxis);
  92906. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  92907. if (this._transformYawPitch) {
  92908. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  92909. }
  92910. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  92911. }
  92912. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  92913. mesh.getDirectionToRef(upAxis, upAxis);
  92914. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  92915. upAxis.normalize();
  92916. }
  92917. }
  92918. var checkYaw = false;
  92919. var checkPitch = false;
  92920. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  92921. checkYaw = true;
  92922. }
  92923. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  92924. checkPitch = true;
  92925. }
  92926. if (checkYaw || checkPitch) {
  92927. var spaceMat = BoneLookController._tmpMats[2];
  92928. var spaceMatInv = BoneLookController._tmpMats[3];
  92929. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  92930. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  92931. }
  92932. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  92933. spaceMat.copyFrom(mesh.getWorldMatrix());
  92934. }
  92935. else {
  92936. var forwardAxis = BoneLookController._tmpVecs[2];
  92937. forwardAxis.copyFrom(this._fowardAxis);
  92938. if (this._transformYawPitch) {
  92939. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  92940. }
  92941. if (parentBone) {
  92942. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  92943. }
  92944. else {
  92945. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  92946. }
  92947. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  92948. rightAxis.normalize();
  92949. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  92950. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  92951. }
  92952. spaceMat.invertToRef(spaceMatInv);
  92953. var xzlen = null;
  92954. if (checkPitch) {
  92955. var localTarget = BoneLookController._tmpVecs[3];
  92956. target.subtractToRef(bonePos, localTarget);
  92957. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  92958. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  92959. var pitch = Math.atan2(localTarget.y, xzlen);
  92960. var newPitch = pitch;
  92961. if (pitch > this._maxPitch) {
  92962. localTarget.y = this._maxPitchTan * xzlen;
  92963. newPitch = this._maxPitch;
  92964. }
  92965. else if (pitch < this._minPitch) {
  92966. localTarget.y = this._minPitchTan * xzlen;
  92967. newPitch = this._minPitch;
  92968. }
  92969. if (pitch != newPitch) {
  92970. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  92971. localTarget.addInPlace(bonePos);
  92972. target = localTarget;
  92973. }
  92974. }
  92975. if (checkYaw) {
  92976. var localTarget = BoneLookController._tmpVecs[4];
  92977. target.subtractToRef(bonePos, localTarget);
  92978. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  92979. var yaw = Math.atan2(localTarget.x, localTarget.z);
  92980. var newYaw = yaw;
  92981. if (yaw > this._maxYaw || yaw < this._minYaw) {
  92982. if (xzlen == null) {
  92983. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  92984. }
  92985. if (this._yawRange > Math.PI) {
  92986. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  92987. localTarget.z = this._maxYawCos * xzlen;
  92988. localTarget.x = this._maxYawSin * xzlen;
  92989. newYaw = this._maxYaw;
  92990. }
  92991. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  92992. localTarget.z = this._minYawCos * xzlen;
  92993. localTarget.x = this._minYawSin * xzlen;
  92994. newYaw = this._minYaw;
  92995. }
  92996. }
  92997. else {
  92998. if (yaw > this._maxYaw) {
  92999. localTarget.z = this._maxYawCos * xzlen;
  93000. localTarget.x = this._maxYawSin * xzlen;
  93001. newYaw = this._maxYaw;
  93002. }
  93003. else if (yaw < this._minYaw) {
  93004. localTarget.z = this._minYawCos * xzlen;
  93005. localTarget.x = this._minYawSin * xzlen;
  93006. newYaw = this._minYaw;
  93007. }
  93008. }
  93009. }
  93010. if (this._slerping && this._yawRange > Math.PI) {
  93011. //are we going to be crossing into the min/max region?
  93012. var boneFwd = BoneLookController._tmpVecs[8];
  93013. boneFwd.copyFrom(BABYLON.Axis.Z);
  93014. if (this._transformYawPitch) {
  93015. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  93016. }
  93017. var boneRotMat = BoneLookController._tmpMats[4];
  93018. this._boneQuat.toRotationMatrix(boneRotMat);
  93019. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  93020. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  93021. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  93022. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  93023. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  93024. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  93025. if (angBtwTar > angBtwMidYaw) {
  93026. if (xzlen == null) {
  93027. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  93028. }
  93029. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  93030. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  93031. if (angBtwMin < angBtwMax) {
  93032. newYaw = boneYaw + Math.PI * .75;
  93033. localTarget.z = Math.cos(newYaw) * xzlen;
  93034. localTarget.x = Math.sin(newYaw) * xzlen;
  93035. }
  93036. else {
  93037. newYaw = boneYaw - Math.PI * .75;
  93038. localTarget.z = Math.cos(newYaw) * xzlen;
  93039. localTarget.x = Math.sin(newYaw) * xzlen;
  93040. }
  93041. }
  93042. }
  93043. if (yaw != newYaw) {
  93044. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  93045. localTarget.addInPlace(bonePos);
  93046. target = localTarget;
  93047. }
  93048. }
  93049. }
  93050. var zaxis = BoneLookController._tmpVecs[5];
  93051. var xaxis = BoneLookController._tmpVecs[6];
  93052. var yaxis = BoneLookController._tmpVecs[7];
  93053. var _tmpQuat = BoneLookController._tmpQuat;
  93054. target.subtractToRef(bonePos, zaxis);
  93055. zaxis.normalize();
  93056. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  93057. xaxis.normalize();
  93058. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  93059. yaxis.normalize();
  93060. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  93061. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  93062. return;
  93063. }
  93064. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  93065. return;
  93066. }
  93067. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  93068. return;
  93069. }
  93070. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  93071. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  93072. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  93073. }
  93074. if (this.slerpAmount < 1) {
  93075. if (!this._slerping) {
  93076. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  93077. }
  93078. if (this._transformYawPitch) {
  93079. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  93080. }
  93081. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  93082. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  93083. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  93084. this._slerping = true;
  93085. }
  93086. else {
  93087. if (this._transformYawPitch) {
  93088. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  93089. }
  93090. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  93091. this._slerping = false;
  93092. }
  93093. };
  93094. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  93095. var angDiff = ang2 - ang1;
  93096. angDiff %= Math.PI * 2;
  93097. if (angDiff > Math.PI) {
  93098. angDiff -= Math.PI * 2;
  93099. }
  93100. else if (angDiff < -Math.PI) {
  93101. angDiff += Math.PI * 2;
  93102. }
  93103. return angDiff;
  93104. };
  93105. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  93106. ang1 %= (2 * Math.PI);
  93107. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  93108. ang2 %= (2 * Math.PI);
  93109. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  93110. var ab = 0;
  93111. if (ang1 < ang2) {
  93112. ab = ang2 - ang1;
  93113. }
  93114. else {
  93115. ab = ang1 - ang2;
  93116. }
  93117. if (ab > Math.PI) {
  93118. ab = Math.PI * 2 - ab;
  93119. }
  93120. return ab;
  93121. };
  93122. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  93123. ang %= (2 * Math.PI);
  93124. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  93125. ang1 %= (2 * Math.PI);
  93126. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  93127. ang2 %= (2 * Math.PI);
  93128. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  93129. if (ang1 < ang2) {
  93130. if (ang > ang1 && ang < ang2) {
  93131. return true;
  93132. }
  93133. }
  93134. else {
  93135. if (ang > ang2 && ang < ang1) {
  93136. return true;
  93137. }
  93138. }
  93139. return false;
  93140. };
  93141. BoneLookController._tmpVecs = BABYLON.Tools.BuildArray(10, BABYLON.Vector3.Zero);
  93142. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  93143. BoneLookController._tmpMats = BABYLON.Tools.BuildArray(5, BABYLON.Matrix.Identity);
  93144. return BoneLookController;
  93145. }());
  93146. BABYLON.BoneLookController = BoneLookController;
  93147. })(BABYLON || (BABYLON = {}));
  93148. //# sourceMappingURL=boneLookController.js.map
  93149. var BABYLON;
  93150. (function (BABYLON) {
  93151. /**
  93152. * Class used to handle skinning animations
  93153. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  93154. */
  93155. var Skeleton = /** @class */ (function () {
  93156. /**
  93157. * Creates a new skeleton
  93158. * @param name defines the skeleton name
  93159. * @param id defines the skeleton Id
  93160. * @param scene defines the hosting scene
  93161. */
  93162. function Skeleton(
  93163. /** defines the skeleton name */
  93164. name,
  93165. /** defines the skeleton Id */
  93166. id, scene) {
  93167. this.name = name;
  93168. this.id = id;
  93169. /**
  93170. * Gets the list of child bones
  93171. */
  93172. this.bones = new Array();
  93173. /**
  93174. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  93175. */
  93176. this.needInitialSkinMatrix = false;
  93177. this._isDirty = true;
  93178. this._meshesWithPoseMatrix = new Array();
  93179. this._identity = BABYLON.Matrix.Identity();
  93180. this._ranges = {};
  93181. this._lastAbsoluteTransformsUpdateId = -1;
  93182. this._canUseTextureForBones = false;
  93183. /**
  93184. * Specifies if the skeleton should be serialized
  93185. */
  93186. this.doNotSerialize = false;
  93187. /**
  93188. * Gets or sets a boolean indicating that bone matrices should be stored as a texture instead of using shader uniforms (default is true).
  93189. * Please note that this option is not available when needInitialSkinMatrix === true or if the hardware does not support it
  93190. */
  93191. this.useTextureToStoreBoneMatrices = true;
  93192. this._animationPropertiesOverride = null;
  93193. // Events
  93194. /**
  93195. * An observable triggered before computing the skeleton's matrices
  93196. */
  93197. this.onBeforeComputeObservable = new BABYLON.Observable();
  93198. this.bones = [];
  93199. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93200. this._scene.skeletons.push(this);
  93201. //make sure it will recalculate the matrix next time prepare is called.
  93202. this._isDirty = true;
  93203. var engineCaps = this._scene.getEngine().getCaps();
  93204. this._canUseTextureForBones = engineCaps.textureFloat && engineCaps.maxVertexTextureImageUnits > 0;
  93205. }
  93206. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  93207. /**
  93208. * Gets or sets the animation properties override
  93209. */
  93210. get: function () {
  93211. if (!this._animationPropertiesOverride) {
  93212. return this._scene.animationPropertiesOverride;
  93213. }
  93214. return this._animationPropertiesOverride;
  93215. },
  93216. set: function (value) {
  93217. this._animationPropertiesOverride = value;
  93218. },
  93219. enumerable: true,
  93220. configurable: true
  93221. });
  93222. Object.defineProperty(Skeleton.prototype, "isUsingTextureForMatrices", {
  93223. /**
  93224. * Gets a boolean indicating that the skeleton effectively stores matrices into a texture
  93225. */
  93226. get: function () {
  93227. return this.useTextureToStoreBoneMatrices && this._canUseTextureForBones && !this.needInitialSkinMatrix;
  93228. },
  93229. enumerable: true,
  93230. configurable: true
  93231. });
  93232. // Members
  93233. /**
  93234. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  93235. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  93236. * @returns a Float32Array containing matrices data
  93237. */
  93238. Skeleton.prototype.getTransformMatrices = function (mesh) {
  93239. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  93240. return mesh._bonesTransformMatrices;
  93241. }
  93242. if (!this._transformMatrices) {
  93243. this.prepare();
  93244. }
  93245. return this._transformMatrices;
  93246. };
  93247. /**
  93248. * Gets the list of transform matrices to send to shaders inside a texture (one matrix per bone)
  93249. * @returns a raw texture containing the data
  93250. */
  93251. Skeleton.prototype.getTransformMatrixTexture = function () {
  93252. return this._transformMatrixTexture;
  93253. };
  93254. /**
  93255. * Gets the current hosting scene
  93256. * @returns a scene object
  93257. */
  93258. Skeleton.prototype.getScene = function () {
  93259. return this._scene;
  93260. };
  93261. // Methods
  93262. /**
  93263. * Gets a string representing the current skeleton data
  93264. * @param fullDetails defines a boolean indicating if we want a verbose version
  93265. * @returns a string representing the current skeleton data
  93266. */
  93267. Skeleton.prototype.toString = function (fullDetails) {
  93268. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  93269. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  93270. if (fullDetails) {
  93271. ret += ", Ranges: {";
  93272. var first = true;
  93273. for (var name_1 in this._ranges) {
  93274. if (first) {
  93275. ret += ", ";
  93276. first = false;
  93277. }
  93278. ret += name_1;
  93279. }
  93280. ret += "}";
  93281. }
  93282. return ret;
  93283. };
  93284. /**
  93285. * Get bone's index searching by name
  93286. * @param name defines bone's name to search for
  93287. * @return the indice of the bone. Returns -1 if not found
  93288. */
  93289. Skeleton.prototype.getBoneIndexByName = function (name) {
  93290. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  93291. if (this.bones[boneIndex].name === name) {
  93292. return boneIndex;
  93293. }
  93294. }
  93295. return -1;
  93296. };
  93297. /**
  93298. * Creater a new animation range
  93299. * @param name defines the name of the range
  93300. * @param from defines the start key
  93301. * @param to defines the end key
  93302. */
  93303. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  93304. // check name not already in use
  93305. if (!this._ranges[name]) {
  93306. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  93307. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  93308. if (this.bones[i].animations[0]) {
  93309. this.bones[i].animations[0].createRange(name, from, to);
  93310. }
  93311. }
  93312. }
  93313. };
  93314. /**
  93315. * Delete a specific animation range
  93316. * @param name defines the name of the range
  93317. * @param deleteFrames defines if frames must be removed as well
  93318. */
  93319. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  93320. if (deleteFrames === void 0) { deleteFrames = true; }
  93321. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  93322. if (this.bones[i].animations[0]) {
  93323. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  93324. }
  93325. }
  93326. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  93327. };
  93328. /**
  93329. * Gets a specific animation range
  93330. * @param name defines the name of the range to look for
  93331. * @returns the requested animation range or null if not found
  93332. */
  93333. Skeleton.prototype.getAnimationRange = function (name) {
  93334. return this._ranges[name];
  93335. };
  93336. /**
  93337. * Gets the list of all animation ranges defined on this skeleton
  93338. * @returns an array
  93339. */
  93340. Skeleton.prototype.getAnimationRanges = function () {
  93341. var animationRanges = [];
  93342. var name;
  93343. var i = 0;
  93344. for (name in this._ranges) {
  93345. animationRanges[i] = this._ranges[name];
  93346. i++;
  93347. }
  93348. return animationRanges;
  93349. };
  93350. /**
  93351. * Copy animation range from a source skeleton.
  93352. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  93353. * @param source defines the source skeleton
  93354. * @param name defines the name of the range to copy
  93355. * @param rescaleAsRequired defines if rescaling must be applied if required
  93356. * @returns true if operation was successful
  93357. */
  93358. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  93359. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  93360. if (this._ranges[name] || !source.getAnimationRange(name)) {
  93361. return false;
  93362. }
  93363. var ret = true;
  93364. var frameOffset = this._getHighestAnimationFrame() + 1;
  93365. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  93366. var boneDict = {};
  93367. var sourceBones = source.bones;
  93368. var nBones;
  93369. var i;
  93370. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  93371. boneDict[sourceBones[i].name] = sourceBones[i];
  93372. }
  93373. if (this.bones.length !== sourceBones.length) {
  93374. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  93375. ret = false;
  93376. }
  93377. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  93378. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  93379. var boneName = this.bones[i].name;
  93380. var sourceBone = boneDict[boneName];
  93381. if (sourceBone) {
  93382. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  93383. }
  93384. else {
  93385. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  93386. ret = false;
  93387. }
  93388. }
  93389. // do not call createAnimationRange(), since it also is done to bones, which was already done
  93390. var range = source.getAnimationRange(name);
  93391. if (range) {
  93392. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  93393. }
  93394. return ret;
  93395. };
  93396. /**
  93397. * Forces the skeleton to go to rest pose
  93398. */
  93399. Skeleton.prototype.returnToRest = function () {
  93400. for (var index = 0; index < this.bones.length; index++) {
  93401. this.bones[index].returnToRest();
  93402. }
  93403. };
  93404. Skeleton.prototype._getHighestAnimationFrame = function () {
  93405. var ret = 0;
  93406. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  93407. if (this.bones[i].animations[0]) {
  93408. var highest = this.bones[i].animations[0].getHighestFrame();
  93409. if (ret < highest) {
  93410. ret = highest;
  93411. }
  93412. }
  93413. }
  93414. return ret;
  93415. };
  93416. /**
  93417. * Begin a specific animation range
  93418. * @param name defines the name of the range to start
  93419. * @param loop defines if looping must be turned on (false by default)
  93420. * @param speedRatio defines the speed ratio to apply (1 by default)
  93421. * @param onAnimationEnd defines a callback which will be called when animation will end
  93422. * @returns a new animatable
  93423. */
  93424. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  93425. var range = this.getAnimationRange(name);
  93426. if (!range) {
  93427. return null;
  93428. }
  93429. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  93430. };
  93431. /** @hidden */
  93432. Skeleton.prototype._markAsDirty = function () {
  93433. this._isDirty = true;
  93434. };
  93435. /** @hidden */
  93436. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  93437. this._meshesWithPoseMatrix.push(mesh);
  93438. };
  93439. /** @hidden */
  93440. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  93441. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  93442. if (index > -1) {
  93443. this._meshesWithPoseMatrix.splice(index, 1);
  93444. }
  93445. };
  93446. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  93447. this.onBeforeComputeObservable.notifyObservers(this);
  93448. for (var index = 0; index < this.bones.length; index++) {
  93449. var bone = this.bones[index];
  93450. var parentBone = bone.getParent();
  93451. if (parentBone) {
  93452. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  93453. }
  93454. else {
  93455. if (initialSkinMatrix) {
  93456. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  93457. }
  93458. else {
  93459. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  93460. }
  93461. }
  93462. if (bone._index !== -1) {
  93463. var mappedIndex = bone._index === null ? index : bone._index;
  93464. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  93465. }
  93466. }
  93467. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  93468. };
  93469. /**
  93470. * Build all resources required to render a skeleton
  93471. */
  93472. Skeleton.prototype.prepare = function () {
  93473. if (!this._isDirty) {
  93474. return;
  93475. }
  93476. if (this.needInitialSkinMatrix) {
  93477. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  93478. var mesh = this._meshesWithPoseMatrix[index];
  93479. var poseMatrix = mesh.getPoseMatrix();
  93480. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  93481. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  93482. }
  93483. if (this._synchronizedWithMesh !== mesh) {
  93484. this._synchronizedWithMesh = mesh;
  93485. // Prepare bones
  93486. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  93487. var bone = this.bones[boneIndex];
  93488. if (!bone.getParent()) {
  93489. var matrix = bone.getBaseMatrix();
  93490. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  93491. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  93492. }
  93493. }
  93494. }
  93495. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  93496. }
  93497. }
  93498. else {
  93499. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  93500. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  93501. if (this.isUsingTextureForMatrices) {
  93502. if (this._transformMatrixTexture) {
  93503. this._transformMatrixTexture.dispose();
  93504. }
  93505. this._transformMatrixTexture = BABYLON.RawTexture.CreateRGBATexture(this._transformMatrices, (this.bones.length + 1) * 4, 1, this._scene, false, false, BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  93506. }
  93507. }
  93508. this._computeTransformMatrices(this._transformMatrices, null);
  93509. if (this.isUsingTextureForMatrices && this._transformMatrixTexture) {
  93510. this._transformMatrixTexture.update(this._transformMatrices);
  93511. }
  93512. }
  93513. this._isDirty = false;
  93514. this._scene._activeBones.addCount(this.bones.length, false);
  93515. };
  93516. /**
  93517. * Gets the list of animatables currently running for this skeleton
  93518. * @returns an array of animatables
  93519. */
  93520. Skeleton.prototype.getAnimatables = function () {
  93521. if (!this._animatables || this._animatables.length !== this.bones.length) {
  93522. this._animatables = [];
  93523. for (var index = 0; index < this.bones.length; index++) {
  93524. this._animatables.push(this.bones[index]);
  93525. }
  93526. }
  93527. return this._animatables;
  93528. };
  93529. /**
  93530. * Clone the current skeleton
  93531. * @param name defines the name of the new skeleton
  93532. * @param id defines the id of the enw skeleton
  93533. * @returns the new skeleton
  93534. */
  93535. Skeleton.prototype.clone = function (name, id) {
  93536. var result = new Skeleton(name, id || name, this._scene);
  93537. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  93538. for (var index = 0; index < this.bones.length; index++) {
  93539. var source = this.bones[index];
  93540. var parentBone = null;
  93541. var parent_1 = source.getParent();
  93542. if (parent_1) {
  93543. var parentIndex = this.bones.indexOf(parent_1);
  93544. parentBone = result.bones[parentIndex];
  93545. }
  93546. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  93547. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  93548. }
  93549. if (this._ranges) {
  93550. result._ranges = {};
  93551. for (var rangeName in this._ranges) {
  93552. var range = this._ranges[rangeName];
  93553. if (range) {
  93554. result._ranges[rangeName] = range.clone();
  93555. }
  93556. }
  93557. }
  93558. this._isDirty = true;
  93559. return result;
  93560. };
  93561. /**
  93562. * Enable animation blending for this skeleton
  93563. * @param blendingSpeed defines the blending speed to apply
  93564. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  93565. */
  93566. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  93567. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  93568. this.bones.forEach(function (bone) {
  93569. bone.animations.forEach(function (animation) {
  93570. animation.enableBlending = true;
  93571. animation.blendingSpeed = blendingSpeed;
  93572. });
  93573. });
  93574. };
  93575. /**
  93576. * Releases all resources associated with the current skeleton
  93577. */
  93578. Skeleton.prototype.dispose = function () {
  93579. this._meshesWithPoseMatrix = [];
  93580. // Animations
  93581. this.getScene().stopAnimation(this);
  93582. // Remove from scene
  93583. this.getScene().removeSkeleton(this);
  93584. if (this._transformMatrixTexture) {
  93585. this._transformMatrixTexture.dispose();
  93586. this._transformMatrixTexture = null;
  93587. }
  93588. };
  93589. /**
  93590. * Serialize the skeleton in a JSON object
  93591. * @returns a JSON object
  93592. */
  93593. Skeleton.prototype.serialize = function () {
  93594. var serializationObject = {};
  93595. serializationObject.name = this.name;
  93596. serializationObject.id = this.id;
  93597. if (this.dimensionsAtRest) {
  93598. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  93599. }
  93600. serializationObject.bones = [];
  93601. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  93602. for (var index = 0; index < this.bones.length; index++) {
  93603. var bone = this.bones[index];
  93604. var parent_2 = bone.getParent();
  93605. var serializedBone = {
  93606. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  93607. name: bone.name,
  93608. matrix: bone.getBaseMatrix().toArray(),
  93609. rest: bone.getRestPose().toArray()
  93610. };
  93611. serializationObject.bones.push(serializedBone);
  93612. if (bone.length) {
  93613. serializedBone.length = bone.length;
  93614. }
  93615. if (bone.metadata) {
  93616. serializedBone.metadata = bone.metadata;
  93617. }
  93618. if (bone.animations && bone.animations.length > 0) {
  93619. serializedBone.animation = bone.animations[0].serialize();
  93620. }
  93621. serializationObject.ranges = [];
  93622. for (var name in this._ranges) {
  93623. var source = this._ranges[name];
  93624. if (!source) {
  93625. continue;
  93626. }
  93627. var range = {};
  93628. range.name = name;
  93629. range.from = source.from;
  93630. range.to = source.to;
  93631. serializationObject.ranges.push(range);
  93632. }
  93633. }
  93634. return serializationObject;
  93635. };
  93636. /**
  93637. * Creates a new skeleton from serialized data
  93638. * @param parsedSkeleton defines the serialized data
  93639. * @param scene defines the hosting scene
  93640. * @returns a new skeleton
  93641. */
  93642. Skeleton.Parse = function (parsedSkeleton, scene) {
  93643. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  93644. if (parsedSkeleton.dimensionsAtRest) {
  93645. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  93646. }
  93647. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  93648. var index;
  93649. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  93650. var parsedBone = parsedSkeleton.bones[index];
  93651. var parentBone = null;
  93652. if (parsedBone.parentBoneIndex > -1) {
  93653. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  93654. }
  93655. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  93656. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  93657. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  93658. bone.id = parsedBone.id;
  93659. }
  93660. if (parsedBone.length) {
  93661. bone.length = parsedBone.length;
  93662. }
  93663. if (parsedBone.metadata) {
  93664. bone.metadata = parsedBone.metadata;
  93665. }
  93666. if (parsedBone.animation) {
  93667. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  93668. }
  93669. }
  93670. // placed after bones, so createAnimationRange can cascade down
  93671. if (parsedSkeleton.ranges) {
  93672. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  93673. var data = parsedSkeleton.ranges[index];
  93674. skeleton.createAnimationRange(data.name, data.from, data.to);
  93675. }
  93676. }
  93677. return skeleton;
  93678. };
  93679. /**
  93680. * Compute all node absolute transforms
  93681. * @param forceUpdate defines if computation must be done even if cache is up to date
  93682. */
  93683. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  93684. if (forceUpdate === void 0) { forceUpdate = false; }
  93685. var renderId = this._scene.getRenderId();
  93686. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  93687. this.bones[0].computeAbsoluteTransforms();
  93688. this._lastAbsoluteTransformsUpdateId = renderId;
  93689. }
  93690. };
  93691. /**
  93692. * Gets the root pose matrix
  93693. * @returns a matrix
  93694. */
  93695. Skeleton.prototype.getPoseMatrix = function () {
  93696. var poseMatrix = null;
  93697. if (this._meshesWithPoseMatrix.length > 0) {
  93698. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  93699. }
  93700. return poseMatrix;
  93701. };
  93702. /**
  93703. * Sorts bones per internal index
  93704. */
  93705. Skeleton.prototype.sortBones = function () {
  93706. var bones = new Array();
  93707. var visited = new Array(this.bones.length);
  93708. for (var index = 0; index < this.bones.length; index++) {
  93709. this._sortBones(index, bones, visited);
  93710. }
  93711. this.bones = bones;
  93712. };
  93713. Skeleton.prototype._sortBones = function (index, bones, visited) {
  93714. if (visited[index]) {
  93715. return;
  93716. }
  93717. visited[index] = true;
  93718. var bone = this.bones[index];
  93719. if (bone._index === undefined) {
  93720. bone._index = index;
  93721. }
  93722. var parentBone = bone.getParent();
  93723. if (parentBone) {
  93724. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  93725. }
  93726. bones.push(bone);
  93727. };
  93728. return Skeleton;
  93729. }());
  93730. BABYLON.Skeleton = Skeleton;
  93731. })(BABYLON || (BABYLON = {}));
  93732. //# sourceMappingURL=skeleton.js.map
  93733. var BABYLON;
  93734. (function (BABYLON) {
  93735. /**
  93736. * This groups tools to convert HDR texture to native colors array.
  93737. */
  93738. var HDRTools = /** @class */ (function () {
  93739. function HDRTools() {
  93740. }
  93741. HDRTools.Ldexp = function (mantissa, exponent) {
  93742. if (exponent > 1023) {
  93743. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  93744. }
  93745. if (exponent < -1074) {
  93746. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  93747. }
  93748. return mantissa * Math.pow(2, exponent);
  93749. };
  93750. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  93751. if (exponent > 0) { /*nonzero pixel*/
  93752. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  93753. float32array[index + 0] = red * exponent;
  93754. float32array[index + 1] = green * exponent;
  93755. float32array[index + 2] = blue * exponent;
  93756. }
  93757. else {
  93758. float32array[index + 0] = 0;
  93759. float32array[index + 1] = 0;
  93760. float32array[index + 2] = 0;
  93761. }
  93762. };
  93763. HDRTools.readStringLine = function (uint8array, startIndex) {
  93764. var line = "";
  93765. var character = "";
  93766. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  93767. character = String.fromCharCode(uint8array[i]);
  93768. if (character == "\n") {
  93769. break;
  93770. }
  93771. line += character;
  93772. }
  93773. return line;
  93774. };
  93775. /**
  93776. * Reads header information from an RGBE texture stored in a native array.
  93777. * More information on this format are available here:
  93778. * https://en.wikipedia.org/wiki/RGBE_image_format
  93779. *
  93780. * @param uint8array The binary file stored in native array.
  93781. * @return The header information.
  93782. */
  93783. HDRTools.RGBE_ReadHeader = function (uint8array) {
  93784. var height = 0;
  93785. var width = 0;
  93786. var line = this.readStringLine(uint8array, 0);
  93787. if (line[0] != '#' || line[1] != '?') {
  93788. throw "Bad HDR Format.";
  93789. }
  93790. var endOfHeader = false;
  93791. var findFormat = false;
  93792. var lineIndex = 0;
  93793. do {
  93794. lineIndex += (line.length + 1);
  93795. line = this.readStringLine(uint8array, lineIndex);
  93796. if (line == "FORMAT=32-bit_rle_rgbe") {
  93797. findFormat = true;
  93798. }
  93799. else if (line.length == 0) {
  93800. endOfHeader = true;
  93801. }
  93802. } while (!endOfHeader);
  93803. if (!findFormat) {
  93804. throw "HDR Bad header format, unsupported FORMAT";
  93805. }
  93806. lineIndex += (line.length + 1);
  93807. line = this.readStringLine(uint8array, lineIndex);
  93808. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  93809. var match = sizeRegexp.exec(line);
  93810. // TODO. Support +Y and -X if needed.
  93811. if (!match || match.length < 3) {
  93812. throw "HDR Bad header format, no size";
  93813. }
  93814. width = parseInt(match[2]);
  93815. height = parseInt(match[1]);
  93816. if (width < 8 || width > 0x7fff) {
  93817. throw "HDR Bad header format, unsupported size";
  93818. }
  93819. lineIndex += (line.length + 1);
  93820. return {
  93821. height: height,
  93822. width: width,
  93823. dataPosition: lineIndex
  93824. };
  93825. };
  93826. /**
  93827. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  93828. * This RGBE texture needs to store the information as a panorama.
  93829. *
  93830. * More information on this format are available here:
  93831. * https://en.wikipedia.org/wiki/RGBE_image_format
  93832. *
  93833. * @param buffer The binary file stored in an array buffer.
  93834. * @param size The expected size of the extracted cubemap.
  93835. * @return The Cube Map information.
  93836. */
  93837. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  93838. var uint8array = new Uint8Array(buffer);
  93839. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  93840. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  93841. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  93842. return cubeMapData;
  93843. };
  93844. /**
  93845. * Returns the pixels data extracted from an RGBE texture.
  93846. * This pixels will be stored left to right up to down in the R G B order in one array.
  93847. *
  93848. * More information on this format are available here:
  93849. * https://en.wikipedia.org/wiki/RGBE_image_format
  93850. *
  93851. * @param uint8array The binary file stored in an array buffer.
  93852. * @param hdrInfo The header information of the file.
  93853. * @return The pixels data in RGB right to left up to down order.
  93854. */
  93855. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  93856. // Keep for multi format supports.
  93857. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  93858. };
  93859. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  93860. var num_scanlines = hdrInfo.height;
  93861. var scanline_width = hdrInfo.width;
  93862. var a, b, c, d, count;
  93863. var dataIndex = hdrInfo.dataPosition;
  93864. var index = 0, endIndex = 0, i = 0;
  93865. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  93866. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  93867. // 3 channels of 4 bytes per pixel in float.
  93868. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  93869. var resultArray = new Float32Array(resultBuffer);
  93870. // read in each successive scanline
  93871. while (num_scanlines > 0) {
  93872. a = uint8array[dataIndex++];
  93873. b = uint8array[dataIndex++];
  93874. c = uint8array[dataIndex++];
  93875. d = uint8array[dataIndex++];
  93876. if (a != 2 || b != 2 || (c & 0x80)) {
  93877. // this file is not run length encoded
  93878. throw "HDR Bad header format, not RLE";
  93879. }
  93880. if (((c << 8) | d) != scanline_width) {
  93881. throw "HDR Bad header format, wrong scan line width";
  93882. }
  93883. index = 0;
  93884. // read each of the four channels for the scanline into the buffer
  93885. for (i = 0; i < 4; i++) {
  93886. endIndex = (i + 1) * scanline_width;
  93887. while (index < endIndex) {
  93888. a = uint8array[dataIndex++];
  93889. b = uint8array[dataIndex++];
  93890. if (a > 128) {
  93891. // a run of the same value
  93892. count = a - 128;
  93893. if ((count == 0) || (count > endIndex - index)) {
  93894. throw "HDR Bad Format, bad scanline data (run)";
  93895. }
  93896. while (count-- > 0) {
  93897. scanLineArray[index++] = b;
  93898. }
  93899. }
  93900. else {
  93901. // a non-run
  93902. count = a;
  93903. if ((count == 0) || (count > endIndex - index)) {
  93904. throw "HDR Bad Format, bad scanline data (non-run)";
  93905. }
  93906. scanLineArray[index++] = b;
  93907. if (--count > 0) {
  93908. for (var j = 0; j < count; j++) {
  93909. scanLineArray[index++] = uint8array[dataIndex++];
  93910. }
  93911. }
  93912. }
  93913. }
  93914. }
  93915. // now convert data from buffer into floats
  93916. for (i = 0; i < scanline_width; i++) {
  93917. a = scanLineArray[i];
  93918. b = scanLineArray[i + scanline_width];
  93919. c = scanLineArray[i + 2 * scanline_width];
  93920. d = scanLineArray[i + 3 * scanline_width];
  93921. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  93922. }
  93923. num_scanlines--;
  93924. }
  93925. return resultArray;
  93926. };
  93927. return HDRTools;
  93928. }());
  93929. BABYLON.HDRTools = HDRTools;
  93930. })(BABYLON || (BABYLON = {}));
  93931. //# sourceMappingURL=hdr.js.map
  93932. var BABYLON;
  93933. (function (BABYLON) {
  93934. /**
  93935. * This represents a texture coming from an HDR input.
  93936. *
  93937. * The only supported format is currently panorama picture stored in RGBE format.
  93938. * Example of such files can be found on HDRLib: http://hdrlib.com/
  93939. */
  93940. var HDRCubeTexture = /** @class */ (function (_super) {
  93941. __extends(HDRCubeTexture, _super);
  93942. /**
  93943. * Instantiates an HDRTexture from the following parameters.
  93944. *
  93945. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  93946. * @param scene The scene the texture will be used in
  93947. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  93948. * @param noMipmap Forces to not generate the mipmap if true
  93949. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  93950. * @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)
  93951. * @param reserved Reserved flag for internal use.
  93952. */
  93953. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  93954. if (noMipmap === void 0) { noMipmap = false; }
  93955. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93956. if (gammaSpace === void 0) { gammaSpace = false; }
  93957. if (reserved === void 0) { reserved = false; }
  93958. if (onLoad === void 0) { onLoad = null; }
  93959. if (onError === void 0) { onError = null; }
  93960. var _this = _super.call(this, scene) || this;
  93961. _this._generateHarmonics = true;
  93962. _this._onLoad = null;
  93963. _this._onError = null;
  93964. /**
  93965. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  93966. */
  93967. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  93968. _this._isBlocking = true;
  93969. _this._rotationY = 0;
  93970. /**
  93971. * Gets or sets the center of the bounding box associated with the cube texture
  93972. * It must define where the camera used to render the texture was set
  93973. */
  93974. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  93975. if (!url) {
  93976. return _this;
  93977. }
  93978. _this.name = url;
  93979. _this.url = url;
  93980. _this.hasAlpha = false;
  93981. _this.isCube = true;
  93982. _this._textureMatrix = BABYLON.Matrix.Identity();
  93983. _this._onLoad = onLoad;
  93984. _this._onError = onError;
  93985. _this.gammaSpace = gammaSpace;
  93986. _this._noMipmap = noMipmap;
  93987. _this._size = size;
  93988. _this._texture = _this._getFromCache(url, _this._noMipmap);
  93989. if (!_this._texture) {
  93990. if (!scene.useDelayedTextureLoading) {
  93991. _this.loadTexture();
  93992. }
  93993. else {
  93994. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  93995. }
  93996. }
  93997. return _this;
  93998. }
  93999. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  94000. /**
  94001. * Gets wether or not the texture is blocking during loading.
  94002. */
  94003. get: function () {
  94004. return this._isBlocking;
  94005. },
  94006. /**
  94007. * Sets wether or not the texture is blocking during loading.
  94008. */
  94009. set: function (value) {
  94010. this._isBlocking = value;
  94011. },
  94012. enumerable: true,
  94013. configurable: true
  94014. });
  94015. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  94016. /**
  94017. * Gets texture matrix rotation angle around Y axis radians.
  94018. */
  94019. get: function () {
  94020. return this._rotationY;
  94021. },
  94022. /**
  94023. * Sets texture matrix rotation angle around Y axis in radians.
  94024. */
  94025. set: function (value) {
  94026. this._rotationY = value;
  94027. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  94028. },
  94029. enumerable: true,
  94030. configurable: true
  94031. });
  94032. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  94033. get: function () {
  94034. return this._boundingBoxSize;
  94035. },
  94036. /**
  94037. * Gets or sets the size of the bounding box associated with the cube texture
  94038. * When defined, the cubemap will switch to local mode
  94039. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  94040. * @example https://www.babylonjs-playground.com/#RNASML
  94041. */
  94042. set: function (value) {
  94043. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  94044. return;
  94045. }
  94046. this._boundingBoxSize = value;
  94047. var scene = this.getScene();
  94048. if (scene) {
  94049. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  94050. }
  94051. },
  94052. enumerable: true,
  94053. configurable: true
  94054. });
  94055. /**
  94056. * Occurs when the file is raw .hdr file.
  94057. */
  94058. HDRCubeTexture.prototype.loadTexture = function () {
  94059. var _this = this;
  94060. var callback = function (buffer) {
  94061. _this.lodGenerationOffset = 0.0;
  94062. _this.lodGenerationScale = 0.8;
  94063. var scene = _this.getScene();
  94064. if (!scene) {
  94065. return null;
  94066. }
  94067. // Extract the raw linear data.
  94068. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  94069. // Generate harmonics if needed.
  94070. if (_this._generateHarmonics) {
  94071. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  94072. _this.sphericalPolynomial = sphericalPolynomial;
  94073. }
  94074. var results = [];
  94075. var byteArray = null;
  94076. // Push each faces.
  94077. for (var j = 0; j < 6; j++) {
  94078. // Create uintarray fallback.
  94079. if (!scene.getEngine().getCaps().textureFloat) {
  94080. // 3 channels of 1 bytes per pixel in bytes.
  94081. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  94082. byteArray = new Uint8Array(byteBuffer);
  94083. }
  94084. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  94085. // If special cases.
  94086. if (_this.gammaSpace || byteArray) {
  94087. for (var i = 0; i < _this._size * _this._size; i++) {
  94088. // Put in gamma space if requested.
  94089. if (_this.gammaSpace) {
  94090. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  94091. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  94092. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  94093. }
  94094. // Convert to int texture for fallback.
  94095. if (byteArray) {
  94096. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  94097. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  94098. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  94099. // May use luminance instead if the result is not accurate.
  94100. var max = Math.max(Math.max(r, g), b);
  94101. if (max > 255) {
  94102. var scale = 255 / max;
  94103. r *= scale;
  94104. g *= scale;
  94105. b *= scale;
  94106. }
  94107. byteArray[(i * 3) + 0] = r;
  94108. byteArray[(i * 3) + 1] = g;
  94109. byteArray[(i * 3) + 2] = b;
  94110. }
  94111. }
  94112. }
  94113. if (byteArray) {
  94114. results.push(byteArray);
  94115. }
  94116. else {
  94117. results.push(dataFace);
  94118. }
  94119. }
  94120. return results;
  94121. };
  94122. var scene = this.getScene();
  94123. if (scene) {
  94124. 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);
  94125. }
  94126. };
  94127. HDRCubeTexture.prototype.clone = function () {
  94128. var scene = this.getScene();
  94129. if (!scene) {
  94130. return this;
  94131. }
  94132. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  94133. // Base texture
  94134. newTexture.level = this.level;
  94135. newTexture.wrapU = this.wrapU;
  94136. newTexture.wrapV = this.wrapV;
  94137. newTexture.coordinatesIndex = this.coordinatesIndex;
  94138. newTexture.coordinatesMode = this.coordinatesMode;
  94139. return newTexture;
  94140. };
  94141. // Methods
  94142. HDRCubeTexture.prototype.delayLoad = function () {
  94143. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  94144. return;
  94145. }
  94146. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  94147. this._texture = this._getFromCache(this.url, this._noMipmap);
  94148. if (!this._texture) {
  94149. this.loadTexture();
  94150. }
  94151. };
  94152. /**
  94153. * Get the texture reflection matrix used to rotate/transform the reflection.
  94154. * @returns the reflection matrix
  94155. */
  94156. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  94157. return this._textureMatrix;
  94158. };
  94159. /**
  94160. * Set the texture reflection matrix used to rotate/transform the reflection.
  94161. * @param value Define the reflection matrix to set
  94162. */
  94163. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  94164. this._textureMatrix = value;
  94165. };
  94166. /**
  94167. * Parses a JSON representation of an HDR Texture in order to create the texture
  94168. * @param parsedTexture Define the JSON representation
  94169. * @param scene Define the scene the texture should be created in
  94170. * @param rootUrl Define the root url in case we need to load relative dependencies
  94171. * @returns the newly created texture after parsing
  94172. */
  94173. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  94174. var texture = null;
  94175. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  94176. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  94177. texture.name = parsedTexture.name;
  94178. texture.hasAlpha = parsedTexture.hasAlpha;
  94179. texture.level = parsedTexture.level;
  94180. texture.coordinatesMode = parsedTexture.coordinatesMode;
  94181. texture.isBlocking = parsedTexture.isBlocking;
  94182. }
  94183. if (texture) {
  94184. if (parsedTexture.boundingBoxPosition) {
  94185. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  94186. }
  94187. if (parsedTexture.boundingBoxSize) {
  94188. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  94189. }
  94190. if (parsedTexture.rotationY) {
  94191. texture.rotationY = parsedTexture.rotationY;
  94192. }
  94193. }
  94194. return texture;
  94195. };
  94196. HDRCubeTexture.prototype.serialize = function () {
  94197. if (!this.name) {
  94198. return null;
  94199. }
  94200. var serializationObject = {};
  94201. serializationObject.name = this.name;
  94202. serializationObject.hasAlpha = this.hasAlpha;
  94203. serializationObject.isCube = true;
  94204. serializationObject.level = this.level;
  94205. serializationObject.size = this._size;
  94206. serializationObject.coordinatesMode = this.coordinatesMode;
  94207. serializationObject.useInGammaSpace = this.gammaSpace;
  94208. serializationObject.generateHarmonics = this._generateHarmonics;
  94209. serializationObject.customType = "BABYLON.HDRCubeTexture";
  94210. serializationObject.noMipmap = this._noMipmap;
  94211. serializationObject.isBlocking = this._isBlocking;
  94212. serializationObject.rotationY = this._rotationY;
  94213. return serializationObject;
  94214. };
  94215. HDRCubeTexture._facesMapping = [
  94216. "right",
  94217. "left",
  94218. "up",
  94219. "down",
  94220. "front",
  94221. "back"
  94222. ];
  94223. return HDRCubeTexture;
  94224. }(BABYLON.BaseTexture));
  94225. BABYLON.HDRCubeTexture = HDRCubeTexture;
  94226. })(BABYLON || (BABYLON = {}));
  94227. //# sourceMappingURL=hdrCubeTexture.js.map
  94228. var BABYLON;
  94229. (function (BABYLON) {
  94230. /**
  94231. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  94232. */
  94233. var PanoramaToCubeMapTools = /** @class */ (function () {
  94234. function PanoramaToCubeMapTools() {
  94235. }
  94236. /**
  94237. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  94238. *
  94239. * @param float32Array The source data.
  94240. * @param inputWidth The width of the input panorama.
  94241. * @param inputHeight The height of the input panorama.
  94242. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  94243. * @return The cubemap data
  94244. */
  94245. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  94246. if (!float32Array) {
  94247. throw "ConvertPanoramaToCubemap: input cannot be null";
  94248. }
  94249. if (float32Array.length != inputWidth * inputHeight * 3) {
  94250. throw "ConvertPanoramaToCubemap: input size is wrong";
  94251. }
  94252. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  94253. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  94254. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  94255. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  94256. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  94257. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  94258. return {
  94259. front: textureFront,
  94260. back: textureBack,
  94261. left: textureLeft,
  94262. right: textureRight,
  94263. up: textureUp,
  94264. down: textureDown,
  94265. size: size,
  94266. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  94267. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  94268. gammaSpace: false,
  94269. };
  94270. };
  94271. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  94272. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  94273. var textureArray = new Float32Array(buffer);
  94274. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  94275. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  94276. var dy = 1 / texSize;
  94277. var fy = 0;
  94278. for (var y = 0; y < texSize; y++) {
  94279. var xv1 = faceData[0];
  94280. var xv2 = faceData[2];
  94281. for (var x = 0; x < texSize; x++) {
  94282. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  94283. v.normalize();
  94284. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  94285. // 3 channels per pixels
  94286. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  94287. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  94288. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  94289. xv1 = xv1.add(rotDX1);
  94290. xv2 = xv2.add(rotDX2);
  94291. }
  94292. fy += dy;
  94293. }
  94294. return textureArray;
  94295. };
  94296. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  94297. var theta = Math.atan2(vDir.z, vDir.x);
  94298. var phi = Math.acos(vDir.y);
  94299. while (theta < -Math.PI) {
  94300. theta += 2 * Math.PI;
  94301. }
  94302. while (theta > Math.PI) {
  94303. theta -= 2 * Math.PI;
  94304. }
  94305. var dx = theta / Math.PI;
  94306. var dy = phi / Math.PI;
  94307. // recenter.
  94308. dx = dx * 0.5 + 0.5;
  94309. var px = Math.round(dx * inputWidth);
  94310. if (px < 0) {
  94311. px = 0;
  94312. }
  94313. else if (px >= inputWidth) {
  94314. px = inputWidth - 1;
  94315. }
  94316. var py = Math.round(dy * inputHeight);
  94317. if (py < 0) {
  94318. py = 0;
  94319. }
  94320. else if (py >= inputHeight) {
  94321. py = inputHeight - 1;
  94322. }
  94323. var inputY = (inputHeight - py - 1);
  94324. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  94325. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  94326. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  94327. return {
  94328. r: r,
  94329. g: g,
  94330. b: b
  94331. };
  94332. };
  94333. PanoramaToCubeMapTools.FACE_FRONT = [
  94334. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  94335. new BABYLON.Vector3(1.0, -1.0, -1.0),
  94336. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  94337. new BABYLON.Vector3(1.0, 1.0, -1.0)
  94338. ];
  94339. PanoramaToCubeMapTools.FACE_BACK = [
  94340. new BABYLON.Vector3(1.0, -1.0, 1.0),
  94341. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  94342. new BABYLON.Vector3(1.0, 1.0, 1.0),
  94343. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  94344. ];
  94345. PanoramaToCubeMapTools.FACE_RIGHT = [
  94346. new BABYLON.Vector3(1.0, -1.0, -1.0),
  94347. new BABYLON.Vector3(1.0, -1.0, 1.0),
  94348. new BABYLON.Vector3(1.0, 1.0, -1.0),
  94349. new BABYLON.Vector3(1.0, 1.0, 1.0)
  94350. ];
  94351. PanoramaToCubeMapTools.FACE_LEFT = [
  94352. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  94353. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  94354. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  94355. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  94356. ];
  94357. PanoramaToCubeMapTools.FACE_DOWN = [
  94358. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  94359. new BABYLON.Vector3(1.0, 1.0, -1.0),
  94360. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  94361. new BABYLON.Vector3(1.0, 1.0, 1.0)
  94362. ];
  94363. PanoramaToCubeMapTools.FACE_UP = [
  94364. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  94365. new BABYLON.Vector3(1.0, -1.0, 1.0),
  94366. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  94367. new BABYLON.Vector3(1.0, -1.0, -1.0)
  94368. ];
  94369. return PanoramaToCubeMapTools;
  94370. }());
  94371. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  94372. })(BABYLON || (BABYLON = {}));
  94373. //# sourceMappingURL=panoramaToCubemap.js.map
  94374. var BABYLON;
  94375. (function (BABYLON) {
  94376. /**
  94377. * Vector2 wth index property
  94378. */
  94379. var IndexedVector2 = /** @class */ (function (_super) {
  94380. __extends(IndexedVector2, _super);
  94381. function IndexedVector2(original,
  94382. /** Index of the vector2 */
  94383. index) {
  94384. var _this = _super.call(this, original.x, original.y) || this;
  94385. _this.index = index;
  94386. return _this;
  94387. }
  94388. return IndexedVector2;
  94389. }(BABYLON.Vector2));
  94390. /**
  94391. * Defines points to create a polygon
  94392. */
  94393. var PolygonPoints = /** @class */ (function () {
  94394. function PolygonPoints() {
  94395. this.elements = new Array();
  94396. }
  94397. PolygonPoints.prototype.add = function (originalPoints) {
  94398. var _this = this;
  94399. var result = new Array();
  94400. originalPoints.forEach(function (point) {
  94401. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  94402. var newPoint = new IndexedVector2(point, _this.elements.length);
  94403. result.push(newPoint);
  94404. _this.elements.push(newPoint);
  94405. }
  94406. });
  94407. return result;
  94408. };
  94409. PolygonPoints.prototype.computeBounds = function () {
  94410. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  94411. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  94412. this.elements.forEach(function (point) {
  94413. // x
  94414. if (point.x < lmin.x) {
  94415. lmin.x = point.x;
  94416. }
  94417. else if (point.x > lmax.x) {
  94418. lmax.x = point.x;
  94419. }
  94420. // y
  94421. if (point.y < lmin.y) {
  94422. lmin.y = point.y;
  94423. }
  94424. else if (point.y > lmax.y) {
  94425. lmax.y = point.y;
  94426. }
  94427. });
  94428. return {
  94429. min: lmin,
  94430. max: lmax,
  94431. width: lmax.x - lmin.x,
  94432. height: lmax.y - lmin.y
  94433. };
  94434. };
  94435. return PolygonPoints;
  94436. }());
  94437. /**
  94438. * Polygon
  94439. * @see https://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  94440. */
  94441. var Polygon = /** @class */ (function () {
  94442. function Polygon() {
  94443. }
  94444. /**
  94445. * Creates a rectangle
  94446. * @param xmin bottom X coord
  94447. * @param ymin bottom Y coord
  94448. * @param xmax top X coord
  94449. * @param ymax top Y coord
  94450. * @returns points that make the resulting rectation
  94451. */
  94452. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  94453. return [
  94454. new BABYLON.Vector2(xmin, ymin),
  94455. new BABYLON.Vector2(xmax, ymin),
  94456. new BABYLON.Vector2(xmax, ymax),
  94457. new BABYLON.Vector2(xmin, ymax)
  94458. ];
  94459. };
  94460. /**
  94461. * Creates a circle
  94462. * @param radius radius of circle
  94463. * @param cx scale in x
  94464. * @param cy scale in y
  94465. * @param numberOfSides number of sides that make up the circle
  94466. * @returns points that make the resulting circle
  94467. */
  94468. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  94469. if (cx === void 0) { cx = 0; }
  94470. if (cy === void 0) { cy = 0; }
  94471. if (numberOfSides === void 0) { numberOfSides = 32; }
  94472. var result = new Array();
  94473. var angle = 0;
  94474. var increment = (Math.PI * 2) / numberOfSides;
  94475. for (var i = 0; i < numberOfSides; i++) {
  94476. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  94477. angle -= increment;
  94478. }
  94479. return result;
  94480. };
  94481. /**
  94482. * Creates a polygon from input string
  94483. * @param input Input polygon data
  94484. * @returns the parsed points
  94485. */
  94486. Polygon.Parse = function (input) {
  94487. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  94488. var i, result = [];
  94489. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  94490. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  94491. }
  94492. return result;
  94493. };
  94494. /**
  94495. * Starts building a polygon from x and y coordinates
  94496. * @param x x coordinate
  94497. * @param y y coordinate
  94498. * @returns the started path2
  94499. */
  94500. Polygon.StartingAt = function (x, y) {
  94501. return BABYLON.Path2.StartingAt(x, y);
  94502. };
  94503. return Polygon;
  94504. }());
  94505. BABYLON.Polygon = Polygon;
  94506. /**
  94507. * Builds a polygon
  94508. * @see https://doc.babylonjs.com/how_to/polygonmeshbuilder
  94509. */
  94510. var PolygonMeshBuilder = /** @class */ (function () {
  94511. /**
  94512. * Creates a PolygonMeshBuilder
  94513. * @param name name of the builder
  94514. * @param contours Path of the polygon
  94515. * @param scene scene to add to
  94516. */
  94517. function PolygonMeshBuilder(name, contours, scene) {
  94518. this._points = new PolygonPoints();
  94519. this._outlinepoints = new PolygonPoints();
  94520. this._holes = new Array();
  94521. this._epoints = new Array();
  94522. this._eholes = new Array();
  94523. this._name = name;
  94524. this._scene = scene;
  94525. var points;
  94526. if (contours instanceof BABYLON.Path2) {
  94527. points = contours.getPoints();
  94528. }
  94529. else {
  94530. points = contours;
  94531. }
  94532. this._addToepoint(points);
  94533. this._points.add(points);
  94534. this._outlinepoints.add(points);
  94535. if (typeof earcut === 'undefined') {
  94536. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  94537. }
  94538. }
  94539. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  94540. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  94541. var p = points_1[_i];
  94542. this._epoints.push(p.x, p.y);
  94543. }
  94544. };
  94545. /**
  94546. * Adds a whole within the polygon
  94547. * @param hole Array of points defining the hole
  94548. * @returns this
  94549. */
  94550. PolygonMeshBuilder.prototype.addHole = function (hole) {
  94551. this._points.add(hole);
  94552. var holepoints = new PolygonPoints();
  94553. holepoints.add(hole);
  94554. this._holes.push(holepoints);
  94555. this._eholes.push(this._epoints.length / 2);
  94556. this._addToepoint(hole);
  94557. return this;
  94558. };
  94559. /**
  94560. * Creates the polygon
  94561. * @param updatable If the mesh should be updatable
  94562. * @param depth The depth of the mesh created
  94563. * @returns the created mesh
  94564. */
  94565. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  94566. var _this = this;
  94567. if (updatable === void 0) { updatable = false; }
  94568. if (depth === void 0) { depth = 0; }
  94569. var result = new BABYLON.Mesh(this._name, this._scene);
  94570. var normals = new Array();
  94571. var positions = new Array();
  94572. var uvs = new Array();
  94573. var bounds = this._points.computeBounds();
  94574. this._points.elements.forEach(function (p) {
  94575. normals.push(0, 1.0, 0);
  94576. positions.push(p.x, 0, p.y);
  94577. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  94578. });
  94579. var indices = new Array();
  94580. var res = earcut(this._epoints, this._eholes, 2);
  94581. for (var i = 0; i < res.length; i++) {
  94582. indices.push(res[i]);
  94583. }
  94584. if (depth > 0) {
  94585. var positionscount = (positions.length / 3); //get the current pointcount
  94586. this._points.elements.forEach(function (p) {
  94587. normals.push(0, -1.0, 0);
  94588. positions.push(p.x, -depth, p.y);
  94589. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  94590. });
  94591. var totalCount = indices.length;
  94592. for (var i = 0; i < totalCount; i += 3) {
  94593. var i0 = indices[i + 0];
  94594. var i1 = indices[i + 1];
  94595. var i2 = indices[i + 2];
  94596. indices.push(i2 + positionscount);
  94597. indices.push(i1 + positionscount);
  94598. indices.push(i0 + positionscount);
  94599. }
  94600. //Add the sides
  94601. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  94602. this._holes.forEach(function (hole) {
  94603. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  94604. });
  94605. }
  94606. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  94607. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  94608. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  94609. result.setIndices(indices);
  94610. return result;
  94611. };
  94612. /**
  94613. * Adds a side to the polygon
  94614. * @param positions points that make the polygon
  94615. * @param normals normals of the polygon
  94616. * @param uvs uvs of the polygon
  94617. * @param indices indices of the polygon
  94618. * @param bounds bounds of the polygon
  94619. * @param points points of the polygon
  94620. * @param depth depth of the polygon
  94621. * @param flip flip of the polygon
  94622. */
  94623. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  94624. var StartIndex = positions.length / 3;
  94625. var ulength = 0;
  94626. for (var i = 0; i < points.elements.length; i++) {
  94627. var p = points.elements[i];
  94628. var p1;
  94629. if ((i + 1) > points.elements.length - 1) {
  94630. p1 = points.elements[0];
  94631. }
  94632. else {
  94633. p1 = points.elements[i + 1];
  94634. }
  94635. positions.push(p.x, 0, p.y);
  94636. positions.push(p.x, -depth, p.y);
  94637. positions.push(p1.x, 0, p1.y);
  94638. positions.push(p1.x, -depth, p1.y);
  94639. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  94640. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  94641. var v3 = v2.subtract(v1);
  94642. var v4 = new BABYLON.Vector3(0, 1, 0);
  94643. var vn = BABYLON.Vector3.Cross(v3, v4);
  94644. vn = vn.normalize();
  94645. uvs.push(ulength / bounds.width, 0);
  94646. uvs.push(ulength / bounds.width, 1);
  94647. ulength += v3.length();
  94648. uvs.push((ulength / bounds.width), 0);
  94649. uvs.push((ulength / bounds.width), 1);
  94650. if (!flip) {
  94651. normals.push(-vn.x, -vn.y, -vn.z);
  94652. normals.push(-vn.x, -vn.y, -vn.z);
  94653. normals.push(-vn.x, -vn.y, -vn.z);
  94654. normals.push(-vn.x, -vn.y, -vn.z);
  94655. indices.push(StartIndex);
  94656. indices.push(StartIndex + 1);
  94657. indices.push(StartIndex + 2);
  94658. indices.push(StartIndex + 1);
  94659. indices.push(StartIndex + 3);
  94660. indices.push(StartIndex + 2);
  94661. }
  94662. else {
  94663. normals.push(vn.x, vn.y, vn.z);
  94664. normals.push(vn.x, vn.y, vn.z);
  94665. normals.push(vn.x, vn.y, vn.z);
  94666. normals.push(vn.x, vn.y, vn.z);
  94667. indices.push(StartIndex);
  94668. indices.push(StartIndex + 2);
  94669. indices.push(StartIndex + 1);
  94670. indices.push(StartIndex + 1);
  94671. indices.push(StartIndex + 2);
  94672. indices.push(StartIndex + 3);
  94673. }
  94674. StartIndex += 4;
  94675. }
  94676. };
  94677. return PolygonMeshBuilder;
  94678. }());
  94679. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  94680. })(BABYLON || (BABYLON = {}));
  94681. //# sourceMappingURL=polygonMesh.js.map
  94682. var BABYLON;
  94683. (function (BABYLON) {
  94684. /**
  94685. * Unique ID when we import meshes from Babylon to CSG
  94686. */
  94687. var currentCSGMeshId = 0;
  94688. /**
  94689. * Represents a vertex of a polygon. Use your own vertex class instead of this
  94690. * one to provide additional features like texture coordinates and vertex
  94691. * colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  94692. * `flip()`, and `interpolate()` methods that behave analogous to the ones
  94693. * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  94694. * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  94695. * is not used anywhere else.
  94696. * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  94697. */
  94698. var Vertex = /** @class */ (function () {
  94699. /**
  94700. * Initializes the vertex
  94701. * @param pos The position of the vertex
  94702. * @param normal The normal of the vertex
  94703. * @param uv The texture coordinate of the vertex
  94704. */
  94705. function Vertex(
  94706. /**
  94707. * The position of the vertex
  94708. */
  94709. pos,
  94710. /**
  94711. * The normal of the vertex
  94712. */
  94713. normal,
  94714. /**
  94715. * The texture coordinate of the vertex
  94716. */
  94717. uv) {
  94718. this.pos = pos;
  94719. this.normal = normal;
  94720. this.uv = uv;
  94721. }
  94722. /**
  94723. * Make a clone, or deep copy, of the vertex
  94724. * @returns A new Vertex
  94725. */
  94726. Vertex.prototype.clone = function () {
  94727. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  94728. };
  94729. /**
  94730. * Invert all orientation-specific data (e.g. vertex normal). Called when the
  94731. * orientation of a polygon is flipped.
  94732. */
  94733. Vertex.prototype.flip = function () {
  94734. this.normal = this.normal.scale(-1);
  94735. };
  94736. /**
  94737. * Create a new vertex between this vertex and `other` by linearly
  94738. * interpolating all properties using a parameter of `t`. Subclasses should
  94739. * override this to interpolate additional properties.
  94740. * @param other the vertex to interpolate against
  94741. * @param t The factor used to linearly interpolate between the vertices
  94742. */
  94743. Vertex.prototype.interpolate = function (other, t) {
  94744. 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));
  94745. };
  94746. return Vertex;
  94747. }());
  94748. /**
  94749. * Represents a plane in 3D space.
  94750. */
  94751. var Plane = /** @class */ (function () {
  94752. /**
  94753. * Initializes the plane
  94754. * @param normal The normal for the plane
  94755. * @param w
  94756. */
  94757. function Plane(normal, w) {
  94758. this.normal = normal;
  94759. this.w = w;
  94760. }
  94761. /**
  94762. * Construct a plane from three points
  94763. * @param a Point a
  94764. * @param b Point b
  94765. * @param c Point c
  94766. */
  94767. Plane.FromPoints = function (a, b, c) {
  94768. var v0 = c.subtract(a);
  94769. var v1 = b.subtract(a);
  94770. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  94771. return null;
  94772. }
  94773. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  94774. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  94775. };
  94776. /**
  94777. * Clone, or make a deep copy of the plane
  94778. * @returns a new Plane
  94779. */
  94780. Plane.prototype.clone = function () {
  94781. return new Plane(this.normal.clone(), this.w);
  94782. };
  94783. /**
  94784. * Flip the face of the plane
  94785. */
  94786. Plane.prototype.flip = function () {
  94787. this.normal.scaleInPlace(-1);
  94788. this.w = -this.w;
  94789. };
  94790. /**
  94791. * Split `polygon` by this plane if needed, then put the polygon or polygon
  94792. * fragments in the appropriate lists. Coplanar polygons go into either
  94793. `* coplanarFront` or `coplanarBack` depending on their orientation with
  94794. * respect to this plane. Polygons in front or in back of this plane go into
  94795. * either `front` or `back`
  94796. * @param polygon The polygon to be split
  94797. * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane
  94798. * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane
  94799. * @param front Will contain the polygons in front of the plane
  94800. * @param back Will contain the polygons begind the plane
  94801. */
  94802. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  94803. var COPLANAR = 0;
  94804. var FRONT = 1;
  94805. var BACK = 2;
  94806. var SPANNING = 3;
  94807. // Classify each point as well as the entire polygon into one of the above
  94808. // four classes.
  94809. var polygonType = 0;
  94810. var types = [];
  94811. var i;
  94812. var t;
  94813. for (i = 0; i < polygon.vertices.length; i++) {
  94814. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  94815. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  94816. polygonType |= type;
  94817. types.push(type);
  94818. }
  94819. // Put the polygon in the correct list, splitting it when necessary
  94820. switch (polygonType) {
  94821. case COPLANAR:
  94822. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  94823. break;
  94824. case FRONT:
  94825. front.push(polygon);
  94826. break;
  94827. case BACK:
  94828. back.push(polygon);
  94829. break;
  94830. case SPANNING:
  94831. var f = [], b = [];
  94832. for (i = 0; i < polygon.vertices.length; i++) {
  94833. var j = (i + 1) % polygon.vertices.length;
  94834. var ti = types[i], tj = types[j];
  94835. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  94836. if (ti !== BACK) {
  94837. f.push(vi);
  94838. }
  94839. if (ti !== FRONT) {
  94840. b.push(ti !== BACK ? vi.clone() : vi);
  94841. }
  94842. if ((ti | tj) === SPANNING) {
  94843. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  94844. var v = vi.interpolate(vj, t);
  94845. f.push(v);
  94846. b.push(v.clone());
  94847. }
  94848. }
  94849. var poly;
  94850. if (f.length >= 3) {
  94851. poly = new Polygon(f, polygon.shared);
  94852. if (poly.plane) {
  94853. front.push(poly);
  94854. }
  94855. }
  94856. if (b.length >= 3) {
  94857. poly = new Polygon(b, polygon.shared);
  94858. if (poly.plane) {
  94859. back.push(poly);
  94860. }
  94861. }
  94862. break;
  94863. }
  94864. };
  94865. /**
  94866. * `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  94867. * point is on the plane
  94868. */
  94869. Plane.EPSILON = 1e-5;
  94870. return Plane;
  94871. }());
  94872. /**
  94873. * Represents a convex polygon. The vertices used to initialize a polygon must
  94874. * be coplanar and form a convex loop.
  94875. *
  94876. * Each convex polygon has a `shared` property, which is shared between all
  94877. * polygons that are clones of each other or were split from the same polygon.
  94878. * This can be used to define per-polygon properties (such as surface color)
  94879. */
  94880. var Polygon = /** @class */ (function () {
  94881. /**
  94882. * Initializes the polygon
  94883. * @param vertices The vertices of the polygon
  94884. * @param shared The properties shared across all polygons
  94885. */
  94886. function Polygon(vertices, shared) {
  94887. this.vertices = vertices;
  94888. this.shared = shared;
  94889. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  94890. }
  94891. /**
  94892. * Clones, or makes a deep copy, or the polygon
  94893. */
  94894. Polygon.prototype.clone = function () {
  94895. var vertices = this.vertices.map(function (v) { return v.clone(); });
  94896. return new Polygon(vertices, this.shared);
  94897. };
  94898. /**
  94899. * Flips the faces of the polygon
  94900. */
  94901. Polygon.prototype.flip = function () {
  94902. this.vertices.reverse().map(function (v) { v.flip(); });
  94903. this.plane.flip();
  94904. };
  94905. return Polygon;
  94906. }());
  94907. /**
  94908. * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  94909. * by picking a polygon to split along. That polygon (and all other coplanar
  94910. * polygons) are added directly to that node and the other polygons are added to
  94911. * the front and/or back subtrees. This is not a leafy BSP tree since there is
  94912. * no distinction between internal and leaf nodes
  94913. */
  94914. var Node = /** @class */ (function () {
  94915. /**
  94916. * Initializes the node
  94917. * @param polygons A collection of polygons held in the node
  94918. */
  94919. function Node(polygons) {
  94920. this.plane = null;
  94921. this.front = null;
  94922. this.back = null;
  94923. this.polygons = new Array();
  94924. if (polygons) {
  94925. this.build(polygons);
  94926. }
  94927. }
  94928. /**
  94929. * Clones, or makes a deep copy, of the node
  94930. * @returns The cloned node
  94931. */
  94932. Node.prototype.clone = function () {
  94933. var node = new Node();
  94934. node.plane = this.plane && this.plane.clone();
  94935. node.front = this.front && this.front.clone();
  94936. node.back = this.back && this.back.clone();
  94937. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  94938. return node;
  94939. };
  94940. /**
  94941. * Convert solid space to empty space and empty space to solid space
  94942. */
  94943. Node.prototype.invert = function () {
  94944. for (var i = 0; i < this.polygons.length; i++) {
  94945. this.polygons[i].flip();
  94946. }
  94947. if (this.plane) {
  94948. this.plane.flip();
  94949. }
  94950. if (this.front) {
  94951. this.front.invert();
  94952. }
  94953. if (this.back) {
  94954. this.back.invert();
  94955. }
  94956. var temp = this.front;
  94957. this.front = this.back;
  94958. this.back = temp;
  94959. };
  94960. /**
  94961. * Recursively remove all polygons in `polygons` that are inside this BSP
  94962. * tree.
  94963. * @param polygons Polygons to remove from the BSP
  94964. * @returns Polygons clipped from the BSP
  94965. */
  94966. Node.prototype.clipPolygons = function (polygons) {
  94967. if (!this.plane) {
  94968. return polygons.slice();
  94969. }
  94970. var front = new Array(), back = new Array();
  94971. for (var i = 0; i < polygons.length; i++) {
  94972. this.plane.splitPolygon(polygons[i], front, back, front, back);
  94973. }
  94974. if (this.front) {
  94975. front = this.front.clipPolygons(front);
  94976. }
  94977. if (this.back) {
  94978. back = this.back.clipPolygons(back);
  94979. }
  94980. else {
  94981. back = [];
  94982. }
  94983. return front.concat(back);
  94984. };
  94985. /**
  94986. * Remove all polygons in this BSP tree that are inside the other BSP tree
  94987. * `bsp`.
  94988. * @param bsp BSP containing polygons to remove from this BSP
  94989. */
  94990. Node.prototype.clipTo = function (bsp) {
  94991. this.polygons = bsp.clipPolygons(this.polygons);
  94992. if (this.front) {
  94993. this.front.clipTo(bsp);
  94994. }
  94995. if (this.back) {
  94996. this.back.clipTo(bsp);
  94997. }
  94998. };
  94999. /**
  95000. * Return a list of all polygons in this BSP tree
  95001. * @returns List of all polygons in this BSP tree
  95002. */
  95003. Node.prototype.allPolygons = function () {
  95004. var polygons = this.polygons.slice();
  95005. if (this.front) {
  95006. polygons = polygons.concat(this.front.allPolygons());
  95007. }
  95008. if (this.back) {
  95009. polygons = polygons.concat(this.back.allPolygons());
  95010. }
  95011. return polygons;
  95012. };
  95013. /**
  95014. * Build a BSP tree out of `polygons`. When called on an existing tree, the
  95015. * new polygons are filtered down to the bottom of the tree and become new
  95016. * nodes there. Each set of polygons is partitioned using the first polygon
  95017. * (no heuristic is used to pick a good split)
  95018. * @param polygons Polygons used to construct the BSP tree
  95019. */
  95020. Node.prototype.build = function (polygons) {
  95021. if (!polygons.length) {
  95022. return;
  95023. }
  95024. if (!this.plane) {
  95025. this.plane = polygons[0].plane.clone();
  95026. }
  95027. var front = new Array(), back = new Array();
  95028. for (var i = 0; i < polygons.length; i++) {
  95029. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  95030. }
  95031. if (front.length) {
  95032. if (!this.front) {
  95033. this.front = new Node();
  95034. }
  95035. this.front.build(front);
  95036. }
  95037. if (back.length) {
  95038. if (!this.back) {
  95039. this.back = new Node();
  95040. }
  95041. this.back.build(back);
  95042. }
  95043. };
  95044. return Node;
  95045. }());
  95046. /**
  95047. * Class for building Constructive Solid Geometry
  95048. */
  95049. var CSG = /** @class */ (function () {
  95050. function CSG() {
  95051. this.polygons = new Array();
  95052. }
  95053. /**
  95054. * Convert the BABYLON.Mesh to BABYLON.CSG
  95055. * @param mesh The BABYLON.Mesh to convert to BABYLON.CSG
  95056. * @returns A new BABYLON.CSG from the BABYLON.Mesh
  95057. */
  95058. CSG.FromMesh = function (mesh) {
  95059. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  95060. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  95061. if (mesh instanceof BABYLON.Mesh) {
  95062. mesh.computeWorldMatrix(true);
  95063. matrix = mesh.getWorldMatrix();
  95064. meshPosition = mesh.position.clone();
  95065. meshRotation = mesh.rotation.clone();
  95066. if (mesh.rotationQuaternion) {
  95067. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  95068. }
  95069. meshScaling = mesh.scaling.clone();
  95070. }
  95071. else {
  95072. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  95073. }
  95074. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  95075. var subMeshes = mesh.subMeshes;
  95076. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  95077. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  95078. vertices = [];
  95079. for (var j = 0; j < 3; j++) {
  95080. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  95081. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  95082. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  95083. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  95084. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  95085. vertex = new Vertex(position, normal, uv);
  95086. vertices.push(vertex);
  95087. }
  95088. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  95089. // To handle the case of degenerated triangle
  95090. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  95091. if (polygon.plane) {
  95092. polygons.push(polygon);
  95093. }
  95094. }
  95095. }
  95096. var csg = CSG.FromPolygons(polygons);
  95097. csg.matrix = matrix;
  95098. csg.position = meshPosition;
  95099. csg.rotation = meshRotation;
  95100. csg.scaling = meshScaling;
  95101. csg.rotationQuaternion = meshRotationQuaternion;
  95102. currentCSGMeshId++;
  95103. return csg;
  95104. };
  95105. /**
  95106. * Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  95107. * @param polygons Polygons used to construct a BABYLON.CSG solid
  95108. */
  95109. CSG.FromPolygons = function (polygons) {
  95110. var csg = new CSG();
  95111. csg.polygons = polygons;
  95112. return csg;
  95113. };
  95114. /**
  95115. * Clones, or makes a deep copy, of the BABYLON.CSG
  95116. * @returns A new BABYLON.CSG
  95117. */
  95118. CSG.prototype.clone = function () {
  95119. var csg = new CSG();
  95120. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  95121. csg.copyTransformAttributes(this);
  95122. return csg;
  95123. };
  95124. /**
  95125. * Unions this CSG with another CSG
  95126. * @param csg The CSG to union against this CSG
  95127. * @returns The unioned CSG
  95128. */
  95129. CSG.prototype.union = function (csg) {
  95130. var a = new Node(this.clone().polygons);
  95131. var b = new Node(csg.clone().polygons);
  95132. a.clipTo(b);
  95133. b.clipTo(a);
  95134. b.invert();
  95135. b.clipTo(a);
  95136. b.invert();
  95137. a.build(b.allPolygons());
  95138. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  95139. };
  95140. /**
  95141. * Unions this CSG with another CSG in place
  95142. * @param csg The CSG to union against this CSG
  95143. */
  95144. CSG.prototype.unionInPlace = function (csg) {
  95145. var a = new Node(this.polygons);
  95146. var b = new Node(csg.polygons);
  95147. a.clipTo(b);
  95148. b.clipTo(a);
  95149. b.invert();
  95150. b.clipTo(a);
  95151. b.invert();
  95152. a.build(b.allPolygons());
  95153. this.polygons = a.allPolygons();
  95154. };
  95155. /**
  95156. * Subtracts this CSG with another CSG
  95157. * @param csg The CSG to subtract against this CSG
  95158. * @returns A new BABYLON.CSG
  95159. */
  95160. CSG.prototype.subtract = function (csg) {
  95161. var a = new Node(this.clone().polygons);
  95162. var b = new Node(csg.clone().polygons);
  95163. a.invert();
  95164. a.clipTo(b);
  95165. b.clipTo(a);
  95166. b.invert();
  95167. b.clipTo(a);
  95168. b.invert();
  95169. a.build(b.allPolygons());
  95170. a.invert();
  95171. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  95172. };
  95173. /**
  95174. * Subtracts this CSG with another CSG in place
  95175. * @param csg The CSG to subtact against this CSG
  95176. */
  95177. CSG.prototype.subtractInPlace = function (csg) {
  95178. var a = new Node(this.polygons);
  95179. var b = new Node(csg.polygons);
  95180. a.invert();
  95181. a.clipTo(b);
  95182. b.clipTo(a);
  95183. b.invert();
  95184. b.clipTo(a);
  95185. b.invert();
  95186. a.build(b.allPolygons());
  95187. a.invert();
  95188. this.polygons = a.allPolygons();
  95189. };
  95190. /**
  95191. * Intersect this CSG with another CSG
  95192. * @param csg The CSG to intersect against this CSG
  95193. * @returns A new BABYLON.CSG
  95194. */
  95195. CSG.prototype.intersect = function (csg) {
  95196. var a = new Node(this.clone().polygons);
  95197. var b = new Node(csg.clone().polygons);
  95198. a.invert();
  95199. b.clipTo(a);
  95200. b.invert();
  95201. a.clipTo(b);
  95202. b.clipTo(a);
  95203. a.build(b.allPolygons());
  95204. a.invert();
  95205. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  95206. };
  95207. /**
  95208. * Intersects this CSG with another CSG in place
  95209. * @param csg The CSG to intersect against this CSG
  95210. */
  95211. CSG.prototype.intersectInPlace = function (csg) {
  95212. var a = new Node(this.polygons);
  95213. var b = new Node(csg.polygons);
  95214. a.invert();
  95215. b.clipTo(a);
  95216. b.invert();
  95217. a.clipTo(b);
  95218. b.clipTo(a);
  95219. a.build(b.allPolygons());
  95220. a.invert();
  95221. this.polygons = a.allPolygons();
  95222. };
  95223. /**
  95224. * Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  95225. * not modified.
  95226. * @returns A new BABYLON.CSG solid with solid and empty space switched
  95227. */
  95228. CSG.prototype.inverse = function () {
  95229. var csg = this.clone();
  95230. csg.inverseInPlace();
  95231. return csg;
  95232. };
  95233. /**
  95234. * Inverses the BABYLON.CSG in place
  95235. */
  95236. CSG.prototype.inverseInPlace = function () {
  95237. this.polygons.map(function (p) { p.flip(); });
  95238. };
  95239. /**
  95240. * This is used to keep meshes transformations so they can be restored
  95241. * when we build back a Babylon Mesh
  95242. * NB : All CSG operations are performed in world coordinates
  95243. * @param csg The BABYLON.CSG to copy the transform attributes from
  95244. * @returns This BABYLON.CSG
  95245. */
  95246. CSG.prototype.copyTransformAttributes = function (csg) {
  95247. this.matrix = csg.matrix;
  95248. this.position = csg.position;
  95249. this.rotation = csg.rotation;
  95250. this.scaling = csg.scaling;
  95251. this.rotationQuaternion = csg.rotationQuaternion;
  95252. return this;
  95253. };
  95254. /**
  95255. * Build Raw mesh from CSG
  95256. * Coordinates here are in world space
  95257. * @param name The name of the mesh geometry
  95258. * @param scene The BABYLON.Scene
  95259. * @param keepSubMeshes Specifies if the submeshes should be kept
  95260. * @returns A new BABYLON.Mesh
  95261. */
  95262. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  95263. var matrix = this.matrix.clone();
  95264. matrix.invert();
  95265. 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;
  95266. if (keepSubMeshes) {
  95267. // Sort Polygons, since subMeshes are indices range
  95268. polygons.sort(function (a, b) {
  95269. if (a.shared.meshId === b.shared.meshId) {
  95270. return a.shared.subMeshId - b.shared.subMeshId;
  95271. }
  95272. else {
  95273. return a.shared.meshId - b.shared.meshId;
  95274. }
  95275. });
  95276. }
  95277. for (var i = 0, il = polygons.length; i < il; i++) {
  95278. polygon = polygons[i];
  95279. // Building SubMeshes
  95280. if (!subMesh_dict[polygon.shared.meshId]) {
  95281. subMesh_dict[polygon.shared.meshId] = {};
  95282. }
  95283. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  95284. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  95285. indexStart: +Infinity,
  95286. indexEnd: -Infinity,
  95287. materialIndex: polygon.shared.materialIndex
  95288. };
  95289. }
  95290. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  95291. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  95292. polygonIndices[0] = 0;
  95293. polygonIndices[1] = j - 1;
  95294. polygonIndices[2] = j;
  95295. for (var k = 0; k < 3; k++) {
  95296. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  95297. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  95298. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  95299. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  95300. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  95301. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  95302. // Check if 2 points can be merged
  95303. if (!(typeof vertex_idx !== 'undefined' &&
  95304. normals[vertex_idx * 3] === localNormal.x &&
  95305. normals[vertex_idx * 3 + 1] === localNormal.y &&
  95306. normals[vertex_idx * 3 + 2] === localNormal.z &&
  95307. uvs[vertex_idx * 2] === uv.x &&
  95308. uvs[vertex_idx * 2 + 1] === uv.y)) {
  95309. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  95310. uvs.push(uv.x, uv.y);
  95311. normals.push(normal.x, normal.y, normal.z);
  95312. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  95313. }
  95314. indices.push(vertex_idx);
  95315. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  95316. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  95317. currentIndex++;
  95318. }
  95319. }
  95320. }
  95321. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  95322. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  95323. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  95324. mesh.setIndices(indices, null);
  95325. if (keepSubMeshes) {
  95326. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  95327. var materialIndexOffset = 0, materialMaxIndex;
  95328. mesh.subMeshes = new Array();
  95329. for (var m in subMesh_dict) {
  95330. materialMaxIndex = -1;
  95331. for (var sm in subMesh_dict[m]) {
  95332. subMesh_obj = subMesh_dict[m][sm];
  95333. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  95334. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  95335. }
  95336. materialIndexOffset += ++materialMaxIndex;
  95337. }
  95338. }
  95339. return mesh;
  95340. };
  95341. /**
  95342. * Build Mesh from CSG taking material and transforms into account
  95343. * @param name The name of the BABYLON.Mesh
  95344. * @param material The material of the BABYLON.Mesh
  95345. * @param scene The BABYLON.Scene
  95346. * @param keepSubMeshes Specifies if submeshes should be kept
  95347. * @returns The new BABYLON.Mesh
  95348. */
  95349. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  95350. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  95351. mesh.material = material;
  95352. mesh.position.copyFrom(this.position);
  95353. mesh.rotation.copyFrom(this.rotation);
  95354. if (this.rotationQuaternion) {
  95355. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  95356. }
  95357. mesh.scaling.copyFrom(this.scaling);
  95358. mesh.computeWorldMatrix(true);
  95359. return mesh;
  95360. };
  95361. return CSG;
  95362. }());
  95363. BABYLON.CSG = CSG;
  95364. })(BABYLON || (BABYLON = {}));
  95365. //# sourceMappingURL=csg.js.map
  95366. var BABYLON;
  95367. (function (BABYLON) {
  95368. /**
  95369. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  95370. * It controls one of the indiviual texture used in the effect.
  95371. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95372. */
  95373. var LensFlare = /** @class */ (function () {
  95374. /**
  95375. * Instantiates a new Lens Flare.
  95376. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  95377. * It controls one of the indiviual texture used in the effect.
  95378. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95379. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  95380. * @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.
  95381. * @param color Define the lens color
  95382. * @param imgUrl Define the lens texture url
  95383. * @param system Define the `lensFlareSystem` this flare is part of
  95384. */
  95385. function LensFlare(
  95386. /**
  95387. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  95388. */
  95389. size,
  95390. /**
  95391. * 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.
  95392. */
  95393. position, color, imgUrl, system) {
  95394. this.size = size;
  95395. this.position = position;
  95396. /**
  95397. * Define the alpha mode to render this particular lens.
  95398. */
  95399. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  95400. this.color = color || new BABYLON.Color3(1, 1, 1);
  95401. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  95402. this._system = system;
  95403. system.lensFlares.push(this);
  95404. }
  95405. /**
  95406. * Creates a new Lens Flare.
  95407. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  95408. * It controls one of the indiviual texture used in the effect.
  95409. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95410. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  95411. * @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.
  95412. * @param color Define the lens color
  95413. * @param imgUrl Define the lens texture url
  95414. * @param system Define the `lensFlareSystem` this flare is part of
  95415. * @returns The newly created Lens Flare
  95416. */
  95417. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  95418. return new LensFlare(size, position, color, imgUrl, system);
  95419. };
  95420. /**
  95421. * Dispose and release the lens flare with its associated resources.
  95422. */
  95423. LensFlare.prototype.dispose = function () {
  95424. if (this.texture) {
  95425. this.texture.dispose();
  95426. }
  95427. // Remove from scene
  95428. var index = this._system.lensFlares.indexOf(this);
  95429. this._system.lensFlares.splice(index, 1);
  95430. };
  95431. return LensFlare;
  95432. }());
  95433. BABYLON.LensFlare = LensFlare;
  95434. })(BABYLON || (BABYLON = {}));
  95435. //# sourceMappingURL=lensFlare.js.map
  95436. var BABYLON;
  95437. (function (BABYLON) {
  95438. // Adds the parser to the scene parsers.
  95439. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  95440. // Lens flares
  95441. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  95442. if (!container.lensFlareSystems) {
  95443. container.lensFlareSystems = new Array();
  95444. }
  95445. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  95446. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  95447. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  95448. container.lensFlareSystems.push(lf);
  95449. }
  95450. }
  95451. });
  95452. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  95453. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  95454. if (this.lensFlareSystems[index].name === name) {
  95455. return this.lensFlareSystems[index];
  95456. }
  95457. }
  95458. return null;
  95459. };
  95460. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  95461. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  95462. if (this.lensFlareSystems[index].id === id) {
  95463. return this.lensFlareSystems[index];
  95464. }
  95465. }
  95466. return null;
  95467. };
  95468. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  95469. var index = this.lensFlareSystems.indexOf(toRemove);
  95470. if (index !== -1) {
  95471. this.lensFlareSystems.splice(index, 1);
  95472. }
  95473. return index;
  95474. };
  95475. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  95476. this.lensFlareSystems.push(newLensFlareSystem);
  95477. };
  95478. /**
  95479. * Defines the lens flare scene component responsible to manage any lens flares
  95480. * in a given scene.
  95481. */
  95482. var LensFlareSystemSceneComponent = /** @class */ (function () {
  95483. /**
  95484. * Creates a new instance of the component for the given scene
  95485. * @param scene Defines the scene to register the component in
  95486. */
  95487. function LensFlareSystemSceneComponent(scene) {
  95488. /**
  95489. * The component name helpfull to identify the component in the list of scene components.
  95490. */
  95491. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  95492. this.scene = scene;
  95493. scene.lensFlareSystems = new Array();
  95494. }
  95495. /**
  95496. * Registers the component in a given scene
  95497. */
  95498. LensFlareSystemSceneComponent.prototype.register = function () {
  95499. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  95500. };
  95501. /**
  95502. * Rebuilds the elements related to this component in case of
  95503. * context lost for instance.
  95504. */
  95505. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  95506. // Nothing to do for lens flare
  95507. };
  95508. /**
  95509. * Adds all the element from the container to the scene
  95510. * @param container the container holding the elements
  95511. */
  95512. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  95513. var _this = this;
  95514. if (!container.lensFlareSystems) {
  95515. return;
  95516. }
  95517. container.lensFlareSystems.forEach(function (o) {
  95518. _this.scene.addLensFlareSystem(o);
  95519. });
  95520. };
  95521. /**
  95522. * Removes all the elements in the container from the scene
  95523. * @param container contains the elements to remove
  95524. */
  95525. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  95526. var _this = this;
  95527. if (!container.lensFlareSystems) {
  95528. return;
  95529. }
  95530. container.lensFlareSystems.forEach(function (o) {
  95531. _this.scene.removeLensFlareSystem(o);
  95532. });
  95533. };
  95534. /**
  95535. * Serializes the component data to the specified json object
  95536. * @param serializationObject The object to serialize to
  95537. */
  95538. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  95539. // Lens flares
  95540. serializationObject.lensFlareSystems = [];
  95541. var lensFlareSystems = this.scene.lensFlareSystems;
  95542. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  95543. var lensFlareSystem = lensFlareSystems_1[_i];
  95544. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  95545. }
  95546. };
  95547. /**
  95548. * Disposes the component and the associated ressources.
  95549. */
  95550. LensFlareSystemSceneComponent.prototype.dispose = function () {
  95551. var lensFlareSystems = this.scene.lensFlareSystems;
  95552. while (lensFlareSystems.length) {
  95553. lensFlareSystems[0].dispose();
  95554. }
  95555. };
  95556. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  95557. // Lens flares
  95558. if (this.scene.lensFlaresEnabled) {
  95559. var lensFlareSystems = this.scene.lensFlareSystems;
  95560. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  95561. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  95562. var lensFlareSystem = lensFlareSystems_2[_i];
  95563. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  95564. lensFlareSystem.render();
  95565. }
  95566. }
  95567. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  95568. }
  95569. };
  95570. return LensFlareSystemSceneComponent;
  95571. }());
  95572. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  95573. })(BABYLON || (BABYLON = {}));
  95574. //# sourceMappingURL=lensFlareSystemSceneComponent.js.map
  95575. var BABYLON;
  95576. (function (BABYLON) {
  95577. /**
  95578. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  95579. * It is usually composed of several `BABYLON.lensFlare`.
  95580. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95581. */
  95582. var LensFlareSystem = /** @class */ (function () {
  95583. /**
  95584. * Instantiates a lens flare system.
  95585. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  95586. * It is usually composed of several `BABYLON.lensFlare`.
  95587. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  95588. * @param name Define the name of the lens flare system in the scene
  95589. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  95590. * @param scene Define the scene the lens flare system belongs to
  95591. */
  95592. function LensFlareSystem(
  95593. /**
  95594. * Define the name of the lens flare system
  95595. */
  95596. name, emitter, scene) {
  95597. this.name = name;
  95598. /**
  95599. * List of lens flares used in this system.
  95600. */
  95601. this.lensFlares = new Array();
  95602. /**
  95603. * Define a limit from the border the lens flare can be visible.
  95604. */
  95605. this.borderLimit = 300;
  95606. /**
  95607. * Define a viewport border we do not want to see the lens flare in.
  95608. */
  95609. this.viewportBorder = 0;
  95610. /**
  95611. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  95612. */
  95613. this.layerMask = 0x0FFFFFFF;
  95614. this._vertexBuffers = {};
  95615. this._isEnabled = true;
  95616. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95617. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  95618. if (!component) {
  95619. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  95620. scene._addComponent(component);
  95621. }
  95622. this._emitter = emitter;
  95623. this.id = name;
  95624. scene.lensFlareSystems.push(this);
  95625. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  95626. var engine = scene.getEngine();
  95627. // VBO
  95628. var vertices = [];
  95629. vertices.push(1, 1);
  95630. vertices.push(-1, 1);
  95631. vertices.push(-1, -1);
  95632. vertices.push(1, -1);
  95633. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  95634. // Indices
  95635. var indices = [];
  95636. indices.push(0);
  95637. indices.push(1);
  95638. indices.push(2);
  95639. indices.push(0);
  95640. indices.push(2);
  95641. indices.push(3);
  95642. this._indexBuffer = engine.createIndexBuffer(indices);
  95643. // Effects
  95644. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  95645. }
  95646. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  95647. /**
  95648. * Define if the lens flare system is enabled.
  95649. */
  95650. get: function () {
  95651. return this._isEnabled;
  95652. },
  95653. set: function (value) {
  95654. this._isEnabled = value;
  95655. },
  95656. enumerable: true,
  95657. configurable: true
  95658. });
  95659. /**
  95660. * Get the scene the effects belongs to.
  95661. * @returns the scene holding the lens flare system
  95662. */
  95663. LensFlareSystem.prototype.getScene = function () {
  95664. return this._scene;
  95665. };
  95666. /**
  95667. * Get the emitter of the lens flare system.
  95668. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  95669. * @returns the emitter of the lens flare system
  95670. */
  95671. LensFlareSystem.prototype.getEmitter = function () {
  95672. return this._emitter;
  95673. };
  95674. /**
  95675. * Set the emitter of the lens flare system.
  95676. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  95677. * @param newEmitter Define the new emitter of the system
  95678. */
  95679. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  95680. this._emitter = newEmitter;
  95681. };
  95682. /**
  95683. * Get the lens flare system emitter position.
  95684. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  95685. * @returns the position
  95686. */
  95687. LensFlareSystem.prototype.getEmitterPosition = function () {
  95688. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  95689. };
  95690. /**
  95691. * @hidden
  95692. */
  95693. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  95694. var position = this.getEmitterPosition();
  95695. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  95696. this._positionX = position.x;
  95697. this._positionY = position.y;
  95698. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  95699. if (this.viewportBorder > 0) {
  95700. globalViewport.x -= this.viewportBorder;
  95701. globalViewport.y -= this.viewportBorder;
  95702. globalViewport.width += this.viewportBorder * 2;
  95703. globalViewport.height += this.viewportBorder * 2;
  95704. position.x += this.viewportBorder;
  95705. position.y += this.viewportBorder;
  95706. this._positionX += this.viewportBorder;
  95707. this._positionY += this.viewportBorder;
  95708. }
  95709. if (position.z > 0) {
  95710. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  95711. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height)) {
  95712. return true;
  95713. }
  95714. }
  95715. return true;
  95716. }
  95717. return false;
  95718. };
  95719. /** @hidden */
  95720. LensFlareSystem.prototype._isVisible = function () {
  95721. if (!this._isEnabled || !this._scene.activeCamera) {
  95722. return false;
  95723. }
  95724. var emitterPosition = this.getEmitterPosition();
  95725. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  95726. var distance = direction.length();
  95727. direction.normalize();
  95728. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  95729. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  95730. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  95731. };
  95732. /**
  95733. * @hidden
  95734. */
  95735. LensFlareSystem.prototype.render = function () {
  95736. if (!this._effect.isReady() || !this._scene.activeCamera) {
  95737. return false;
  95738. }
  95739. var engine = this._scene.getEngine();
  95740. var viewport = this._scene.activeCamera.viewport;
  95741. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  95742. // Position
  95743. if (!this.computeEffectivePosition(globalViewport)) {
  95744. return false;
  95745. }
  95746. // Visibility
  95747. if (!this._isVisible()) {
  95748. return false;
  95749. }
  95750. // Intensity
  95751. var awayX;
  95752. var awayY;
  95753. if (this._positionX < this.borderLimit + globalViewport.x) {
  95754. awayX = this.borderLimit + globalViewport.x - this._positionX;
  95755. }
  95756. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  95757. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  95758. }
  95759. else {
  95760. awayX = 0;
  95761. }
  95762. if (this._positionY < this.borderLimit + globalViewport.y) {
  95763. awayY = this.borderLimit + globalViewport.y - this._positionY;
  95764. }
  95765. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  95766. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  95767. }
  95768. else {
  95769. awayY = 0;
  95770. }
  95771. var away = (awayX > awayY) ? awayX : awayY;
  95772. away -= this.viewportBorder;
  95773. if (away > this.borderLimit) {
  95774. away = this.borderLimit;
  95775. }
  95776. var intensity = 1.0 - BABYLON.Scalar.Clamp(away / this.borderLimit, 0, 1);
  95777. if (intensity < 0) {
  95778. return false;
  95779. }
  95780. if (intensity > 1.0) {
  95781. intensity = 1.0;
  95782. }
  95783. if (this.viewportBorder > 0) {
  95784. globalViewport.x += this.viewportBorder;
  95785. globalViewport.y += this.viewportBorder;
  95786. globalViewport.width -= this.viewportBorder * 2;
  95787. globalViewport.height -= this.viewportBorder * 2;
  95788. this._positionX -= this.viewportBorder;
  95789. this._positionY -= this.viewportBorder;
  95790. }
  95791. // Position
  95792. var centerX = globalViewport.x + globalViewport.width / 2;
  95793. var centerY = globalViewport.y + globalViewport.height / 2;
  95794. var distX = centerX - this._positionX;
  95795. var distY = centerY - this._positionY;
  95796. // Effects
  95797. engine.enableEffect(this._effect);
  95798. engine.setState(false);
  95799. engine.setDepthBuffer(false);
  95800. // VBOs
  95801. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  95802. // Flares
  95803. for (var index = 0; index < this.lensFlares.length; index++) {
  95804. var flare = this.lensFlares[index];
  95805. engine.setAlphaMode(flare.alphaMode);
  95806. var x = centerX - (distX * flare.position);
  95807. var y = centerY - (distY * flare.position);
  95808. var cw = flare.size;
  95809. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  95810. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  95811. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  95812. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  95813. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  95814. // Texture
  95815. this._effect.setTexture("textureSampler", flare.texture);
  95816. // Color
  95817. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  95818. // Draw order
  95819. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95820. }
  95821. engine.setDepthBuffer(true);
  95822. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  95823. return true;
  95824. };
  95825. /**
  95826. * Dispose and release the lens flare with its associated resources.
  95827. */
  95828. LensFlareSystem.prototype.dispose = function () {
  95829. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  95830. if (vertexBuffer) {
  95831. vertexBuffer.dispose();
  95832. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  95833. }
  95834. if (this._indexBuffer) {
  95835. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  95836. this._indexBuffer = null;
  95837. }
  95838. while (this.lensFlares.length) {
  95839. this.lensFlares[0].dispose();
  95840. }
  95841. // Remove from scene
  95842. var index = this._scene.lensFlareSystems.indexOf(this);
  95843. this._scene.lensFlareSystems.splice(index, 1);
  95844. };
  95845. /**
  95846. * Parse a lens flare system from a JSON repressentation
  95847. * @param parsedLensFlareSystem Define the JSON to parse
  95848. * @param scene Define the scene the parsed system should be instantiated in
  95849. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  95850. * @returns the parsed system
  95851. */
  95852. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  95853. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  95854. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  95855. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  95856. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  95857. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  95858. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  95859. var parsedFlare = parsedLensFlareSystem.flares[index];
  95860. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  95861. }
  95862. return lensFlareSystem;
  95863. };
  95864. /**
  95865. * Serialize the current Lens Flare System into a JSON representation.
  95866. * @returns the serialized JSON
  95867. */
  95868. LensFlareSystem.prototype.serialize = function () {
  95869. var serializationObject = {};
  95870. serializationObject.id = this.id;
  95871. serializationObject.name = this.name;
  95872. serializationObject.emitterId = this.getEmitter().id;
  95873. serializationObject.borderLimit = this.borderLimit;
  95874. serializationObject.flares = [];
  95875. for (var index = 0; index < this.lensFlares.length; index++) {
  95876. var flare = this.lensFlares[index];
  95877. serializationObject.flares.push({
  95878. size: flare.size,
  95879. position: flare.position,
  95880. color: flare.color.asArray(),
  95881. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  95882. });
  95883. }
  95884. return serializationObject;
  95885. };
  95886. return LensFlareSystem;
  95887. }());
  95888. BABYLON.LensFlareSystem = LensFlareSystem;
  95889. })(BABYLON || (BABYLON = {}));
  95890. //# sourceMappingURL=lensFlareSystem.js.map
  95891. var BABYLON;
  95892. (function (BABYLON) {
  95893. /**
  95894. * This is a holder class for the physics joint created by the physics plugin
  95895. * It holds a set of functions to control the underlying joint
  95896. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95897. */
  95898. var PhysicsJoint = /** @class */ (function () {
  95899. /**
  95900. * Initializes the physics joint
  95901. * @param type The type of the physics joint
  95902. * @param jointData The data for the physics joint
  95903. */
  95904. function PhysicsJoint(
  95905. /**
  95906. * The type of the physics joint
  95907. */
  95908. type,
  95909. /**
  95910. * The data for the physics joint
  95911. */
  95912. jointData) {
  95913. this.type = type;
  95914. this.jointData = jointData;
  95915. jointData.nativeParams = jointData.nativeParams || {};
  95916. }
  95917. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  95918. /**
  95919. * Gets the physics joint
  95920. */
  95921. get: function () {
  95922. return this._physicsJoint;
  95923. },
  95924. /**
  95925. * Sets the physics joint
  95926. */
  95927. set: function (newJoint) {
  95928. if (this._physicsJoint) {
  95929. //remove from the wolrd
  95930. }
  95931. this._physicsJoint = newJoint;
  95932. },
  95933. enumerable: true,
  95934. configurable: true
  95935. });
  95936. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  95937. /**
  95938. * Sets the physics plugin
  95939. */
  95940. set: function (physicsPlugin) {
  95941. this._physicsPlugin = physicsPlugin;
  95942. },
  95943. enumerable: true,
  95944. configurable: true
  95945. });
  95946. /**
  95947. * Execute a function that is physics-plugin specific.
  95948. * @param {Function} func the function that will be executed.
  95949. * It accepts two parameters: the physics world and the physics joint
  95950. */
  95951. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  95952. func(this._physicsPlugin.world, this._physicsJoint);
  95953. };
  95954. //TODO check if the native joints are the same
  95955. //Joint Types
  95956. /**
  95957. * Distance-Joint type
  95958. */
  95959. PhysicsJoint.DistanceJoint = 0;
  95960. /**
  95961. * Hinge-Joint type
  95962. */
  95963. PhysicsJoint.HingeJoint = 1;
  95964. /**
  95965. * Ball-and-Socket joint type
  95966. */
  95967. PhysicsJoint.BallAndSocketJoint = 2;
  95968. /**
  95969. * Wheel-Joint type
  95970. */
  95971. PhysicsJoint.WheelJoint = 3;
  95972. /**
  95973. * Slider-Joint type
  95974. */
  95975. PhysicsJoint.SliderJoint = 4;
  95976. //OIMO
  95977. /**
  95978. * Prismatic-Joint type
  95979. */
  95980. PhysicsJoint.PrismaticJoint = 5;
  95981. //
  95982. /**
  95983. * Universal-Joint type
  95984. * ENERGY FTW! (compare with this - @see http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  95985. */
  95986. PhysicsJoint.UniversalJoint = 6;
  95987. /**
  95988. * Hinge-Joint 2 type
  95989. */
  95990. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  95991. //Cannon
  95992. /**
  95993. * Point to Point Joint type. Similar to a Ball-Joint. Different in parameters
  95994. */
  95995. PhysicsJoint.PointToPointJoint = 8;
  95996. //Cannon only at the moment
  95997. /**
  95998. * Spring-Joint type
  95999. */
  96000. PhysicsJoint.SpringJoint = 9;
  96001. /**
  96002. * Lock-Joint type
  96003. */
  96004. PhysicsJoint.LockJoint = 10;
  96005. return PhysicsJoint;
  96006. }());
  96007. BABYLON.PhysicsJoint = PhysicsJoint;
  96008. /**
  96009. * A class representing a physics distance joint
  96010. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96011. */
  96012. var DistanceJoint = /** @class */ (function (_super) {
  96013. __extends(DistanceJoint, _super);
  96014. /**
  96015. *
  96016. * @param jointData The data for the Distance-Joint
  96017. */
  96018. function DistanceJoint(jointData) {
  96019. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  96020. }
  96021. /**
  96022. * Update the predefined distance.
  96023. * @param maxDistance The maximum preferred distance
  96024. * @param minDistance The minimum preferred distance
  96025. */
  96026. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  96027. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  96028. };
  96029. return DistanceJoint;
  96030. }(PhysicsJoint));
  96031. BABYLON.DistanceJoint = DistanceJoint;
  96032. /**
  96033. * Represents a Motor-Enabled Joint
  96034. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96035. */
  96036. var MotorEnabledJoint = /** @class */ (function (_super) {
  96037. __extends(MotorEnabledJoint, _super);
  96038. /**
  96039. * Initializes the Motor-Enabled Joint
  96040. * @param type The type of the joint
  96041. * @param jointData The physica joint data for the joint
  96042. */
  96043. function MotorEnabledJoint(type, jointData) {
  96044. return _super.call(this, type, jointData) || this;
  96045. }
  96046. /**
  96047. * Set the motor values.
  96048. * Attention, this function is plugin specific. Engines won't react 100% the same.
  96049. * @param force the force to apply
  96050. * @param maxForce max force for this motor.
  96051. */
  96052. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  96053. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  96054. };
  96055. /**
  96056. * Set the motor's limits.
  96057. * Attention, this function is plugin specific. Engines won't react 100% the same.
  96058. * @param upperLimit The upper limit of the motor
  96059. * @param lowerLimit The lower limit of the motor
  96060. */
  96061. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  96062. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  96063. };
  96064. return MotorEnabledJoint;
  96065. }(PhysicsJoint));
  96066. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  96067. /**
  96068. * This class represents a single physics Hinge-Joint
  96069. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96070. */
  96071. var HingeJoint = /** @class */ (function (_super) {
  96072. __extends(HingeJoint, _super);
  96073. /**
  96074. * Initializes the Hinge-Joint
  96075. * @param jointData The joint data for the Hinge-Joint
  96076. */
  96077. function HingeJoint(jointData) {
  96078. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  96079. }
  96080. /**
  96081. * Set the motor values.
  96082. * Attention, this function is plugin specific. Engines won't react 100% the same.
  96083. * @param {number} force the force to apply
  96084. * @param {number} maxForce max force for this motor.
  96085. */
  96086. HingeJoint.prototype.setMotor = function (force, maxForce) {
  96087. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  96088. };
  96089. /**
  96090. * Set the motor's limits.
  96091. * Attention, this function is plugin specific. Engines won't react 100% the same.
  96092. * @param upperLimit The upper limit of the motor
  96093. * @param lowerLimit The lower limit of the motor
  96094. */
  96095. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  96096. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  96097. };
  96098. return HingeJoint;
  96099. }(MotorEnabledJoint));
  96100. BABYLON.HingeJoint = HingeJoint;
  96101. /**
  96102. * This class represents a dual hinge physics joint (same as wheel joint)
  96103. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96104. */
  96105. var Hinge2Joint = /** @class */ (function (_super) {
  96106. __extends(Hinge2Joint, _super);
  96107. /**
  96108. * Initializes the Hinge2-Joint
  96109. * @param jointData The joint data for the Hinge2-Joint
  96110. */
  96111. function Hinge2Joint(jointData) {
  96112. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  96113. }
  96114. /**
  96115. * Set the motor values.
  96116. * Attention, this function is plugin specific. Engines won't react 100% the same.
  96117. * @param {number} force the force to apply
  96118. * @param {number} maxForce max force for this motor.
  96119. * @param {motorIndex} the motor's index, 0 or 1.
  96120. */
  96121. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  96122. if (motorIndex === void 0) { motorIndex = 0; }
  96123. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  96124. };
  96125. /**
  96126. * Set the motor limits.
  96127. * Attention, this function is plugin specific. Engines won't react 100% the same.
  96128. * @param {number} upperLimit the upper limit
  96129. * @param {number} lowerLimit lower limit
  96130. * @param {motorIndex} the motor's index, 0 or 1.
  96131. */
  96132. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  96133. if (motorIndex === void 0) { motorIndex = 0; }
  96134. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  96135. };
  96136. return Hinge2Joint;
  96137. }(MotorEnabledJoint));
  96138. BABYLON.Hinge2Joint = Hinge2Joint;
  96139. })(BABYLON || (BABYLON = {}));
  96140. //# sourceMappingURL=physicsJoint.js.map
  96141. var BABYLON;
  96142. (function (BABYLON) {
  96143. /**
  96144. * Represents a physics imposter
  96145. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96146. */
  96147. var PhysicsImpostor = /** @class */ (function () {
  96148. /**
  96149. * Initializes the physics imposter
  96150. * @param object The physics-enabled object used as the physics imposter
  96151. * @param type The type of the physics imposter
  96152. * @param _options The options for the physics imposter
  96153. * @param _scene The Babylon scene
  96154. */
  96155. function PhysicsImpostor(
  96156. /**
  96157. * The physics-enabled object used as the physics imposter
  96158. */
  96159. object,
  96160. /**
  96161. * The type of the physics imposter
  96162. */
  96163. type, _options, _scene) {
  96164. if (_options === void 0) { _options = { mass: 0 }; }
  96165. var _this = this;
  96166. this.object = object;
  96167. this.type = type;
  96168. this._options = _options;
  96169. this._scene = _scene;
  96170. this._bodyUpdateRequired = false;
  96171. this._onBeforePhysicsStepCallbacks = new Array();
  96172. this._onAfterPhysicsStepCallbacks = new Array();
  96173. this._onPhysicsCollideCallbacks = [];
  96174. this._deltaPosition = BABYLON.Vector3.Zero();
  96175. this._isDisposed = false;
  96176. //temp variables for parent rotation calculations
  96177. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  96178. this._tmpQuat = new BABYLON.Quaternion();
  96179. this._tmpQuat2 = new BABYLON.Quaternion();
  96180. /**
  96181. * this function is executed by the physics engine.
  96182. */
  96183. this.beforeStep = function () {
  96184. if (!_this._physicsEngine) {
  96185. return;
  96186. }
  96187. _this.object.translate(_this._deltaPosition, -1);
  96188. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  96189. _this.object.computeWorldMatrix(false);
  96190. if (_this.object.parent && _this.object.rotationQuaternion) {
  96191. _this.getParentsRotation();
  96192. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  96193. }
  96194. else {
  96195. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  96196. }
  96197. if (!_this._options.disableBidirectionalTransformation) {
  96198. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  96199. }
  96200. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  96201. func(_this);
  96202. });
  96203. };
  96204. /**
  96205. * this function is executed by the physics engine
  96206. */
  96207. this.afterStep = function () {
  96208. if (!_this._physicsEngine) {
  96209. return;
  96210. }
  96211. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  96212. func(_this);
  96213. });
  96214. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  96215. // object has now its world rotation. needs to be converted to local.
  96216. if (_this.object.parent && _this.object.rotationQuaternion) {
  96217. _this.getParentsRotation();
  96218. _this._tmpQuat.conjugateInPlace();
  96219. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  96220. }
  96221. // take the position set and make it the absolute position of this object.
  96222. _this.object.setAbsolutePosition(_this.object.position);
  96223. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  96224. _this.object.translate(_this._deltaPosition, 1);
  96225. };
  96226. /**
  96227. * Legacy collision detection event support
  96228. */
  96229. this.onCollideEvent = null;
  96230. /**
  96231. * event and body object due to cannon's event-based architecture.
  96232. */
  96233. this.onCollide = function (e) {
  96234. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  96235. return;
  96236. }
  96237. if (!_this._physicsEngine) {
  96238. return;
  96239. }
  96240. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  96241. if (otherImpostor) {
  96242. // Legacy collision detection event support
  96243. if (_this.onCollideEvent) {
  96244. _this.onCollideEvent(_this, otherImpostor);
  96245. }
  96246. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  96247. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  96248. }).forEach(function (obj) {
  96249. obj.callback(_this, otherImpostor);
  96250. });
  96251. }
  96252. };
  96253. //sanity check!
  96254. if (!this.object) {
  96255. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  96256. return;
  96257. }
  96258. //legacy support for old syntax.
  96259. if (!this._scene && object.getScene) {
  96260. this._scene = object.getScene();
  96261. }
  96262. if (!this._scene) {
  96263. return;
  96264. }
  96265. this._physicsEngine = this._scene.getPhysicsEngine();
  96266. if (!this._physicsEngine) {
  96267. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  96268. }
  96269. else {
  96270. //set the object's quaternion, if not set
  96271. if (!this.object.rotationQuaternion) {
  96272. if (this.object.rotation) {
  96273. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  96274. }
  96275. else {
  96276. this.object.rotationQuaternion = new BABYLON.Quaternion();
  96277. }
  96278. }
  96279. //default options params
  96280. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  96281. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  96282. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  96283. this._joints = [];
  96284. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  96285. if (!this.object.parent || this._options.ignoreParent) {
  96286. this._init();
  96287. }
  96288. else if (this.object.parent.physicsImpostor) {
  96289. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  96290. }
  96291. }
  96292. }
  96293. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  96294. /**
  96295. * Specifies if the physics imposter is disposed
  96296. */
  96297. get: function () {
  96298. return this._isDisposed;
  96299. },
  96300. enumerable: true,
  96301. configurable: true
  96302. });
  96303. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  96304. /**
  96305. * Gets the mass of the physics imposter
  96306. */
  96307. get: function () {
  96308. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  96309. },
  96310. set: function (value) {
  96311. this.setMass(value);
  96312. },
  96313. enumerable: true,
  96314. configurable: true
  96315. });
  96316. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  96317. /**
  96318. * Gets the coefficient of friction
  96319. */
  96320. get: function () {
  96321. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  96322. },
  96323. /**
  96324. * Sets the coefficient of friction
  96325. */
  96326. set: function (value) {
  96327. if (!this._physicsEngine) {
  96328. return;
  96329. }
  96330. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  96331. },
  96332. enumerable: true,
  96333. configurable: true
  96334. });
  96335. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  96336. /**
  96337. * Gets the coefficient of restitution
  96338. */
  96339. get: function () {
  96340. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  96341. },
  96342. /**
  96343. * Sets the coefficient of restitution
  96344. */
  96345. set: function (value) {
  96346. if (!this._physicsEngine) {
  96347. return;
  96348. }
  96349. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  96350. },
  96351. enumerable: true,
  96352. configurable: true
  96353. });
  96354. /**
  96355. * This function will completly initialize this impostor.
  96356. * It will create a new body - but only if this mesh has no parent.
  96357. * If it has, this impostor will not be used other than to define the impostor
  96358. * of the child mesh.
  96359. * @hidden
  96360. */
  96361. PhysicsImpostor.prototype._init = function () {
  96362. if (!this._physicsEngine) {
  96363. return;
  96364. }
  96365. this._physicsEngine.removeImpostor(this);
  96366. this.physicsBody = null;
  96367. this._parent = this._parent || this._getPhysicsParent();
  96368. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  96369. this._physicsEngine.addImpostor(this);
  96370. }
  96371. };
  96372. PhysicsImpostor.prototype._getPhysicsParent = function () {
  96373. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  96374. var parentMesh = this.object.parent;
  96375. return parentMesh.physicsImpostor;
  96376. }
  96377. return null;
  96378. };
  96379. /**
  96380. * Should a new body be generated.
  96381. * @returns boolean specifying if body initialization is required
  96382. */
  96383. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  96384. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  96385. };
  96386. /**
  96387. * Sets the updated scaling
  96388. * @param updated Specifies if the scaling is updated
  96389. */
  96390. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  96391. this.forceUpdate();
  96392. };
  96393. /**
  96394. * Force a regeneration of this or the parent's impostor's body.
  96395. * Use under cautious - This will remove all joints already implemented.
  96396. */
  96397. PhysicsImpostor.prototype.forceUpdate = function () {
  96398. this._init();
  96399. if (this.parent && !this._options.ignoreParent) {
  96400. this.parent.forceUpdate();
  96401. }
  96402. };
  96403. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  96404. /*public get mesh(): AbstractMesh {
  96405. return this._mesh;
  96406. }*/
  96407. /**
  96408. * Gets the body that holds this impostor. Either its own, or its parent.
  96409. */
  96410. get: function () {
  96411. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  96412. },
  96413. /**
  96414. * Set the physics body. Used mainly by the physics engine/plugin
  96415. */
  96416. set: function (physicsBody) {
  96417. if (this._physicsBody && this._physicsEngine) {
  96418. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  96419. }
  96420. this._physicsBody = physicsBody;
  96421. this.resetUpdateFlags();
  96422. },
  96423. enumerable: true,
  96424. configurable: true
  96425. });
  96426. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  96427. /**
  96428. * Get the parent of the physics imposter
  96429. * @returns Physics imposter or null
  96430. */
  96431. get: function () {
  96432. return !this._options.ignoreParent && this._parent ? this._parent : null;
  96433. },
  96434. /**
  96435. * Sets the parent of the physics imposter
  96436. */
  96437. set: function (value) {
  96438. this._parent = value;
  96439. },
  96440. enumerable: true,
  96441. configurable: true
  96442. });
  96443. /**
  96444. * Resets the update flags
  96445. */
  96446. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  96447. this._bodyUpdateRequired = false;
  96448. };
  96449. /**
  96450. * Gets the object extend size
  96451. * @returns the object extend size
  96452. */
  96453. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  96454. if (this.object.getBoundingInfo) {
  96455. var q = this.object.rotationQuaternion;
  96456. //reset rotation
  96457. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  96458. //calculate the world matrix with no rotation
  96459. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  96460. var boundingInfo = this.object.getBoundingInfo();
  96461. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  96462. //bring back the rotation
  96463. this.object.rotationQuaternion = q;
  96464. //calculate the world matrix with the new rotation
  96465. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  96466. return size;
  96467. }
  96468. else {
  96469. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  96470. }
  96471. };
  96472. /**
  96473. * Gets the object center
  96474. * @returns The object center
  96475. */
  96476. PhysicsImpostor.prototype.getObjectCenter = function () {
  96477. if (this.object.getBoundingInfo) {
  96478. var boundingInfo = this.object.getBoundingInfo();
  96479. return boundingInfo.boundingBox.centerWorld;
  96480. }
  96481. else {
  96482. return this.object.position;
  96483. }
  96484. };
  96485. /**
  96486. * Get a specific parametes from the options parameter
  96487. * @param paramName The object parameter name
  96488. * @returns The object parameter
  96489. */
  96490. PhysicsImpostor.prototype.getParam = function (paramName) {
  96491. return this._options[paramName];
  96492. };
  96493. /**
  96494. * Sets a specific parameter in the options given to the physics plugin
  96495. * @param paramName The parameter name
  96496. * @param value The value of the parameter
  96497. */
  96498. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  96499. this._options[paramName] = value;
  96500. this._bodyUpdateRequired = true;
  96501. };
  96502. /**
  96503. * Specifically change the body's mass option. Won't recreate the physics body object
  96504. * @param mass The mass of the physics imposter
  96505. */
  96506. PhysicsImpostor.prototype.setMass = function (mass) {
  96507. if (this.getParam("mass") !== mass) {
  96508. this.setParam("mass", mass);
  96509. }
  96510. if (this._physicsEngine) {
  96511. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  96512. }
  96513. };
  96514. /**
  96515. * Gets the linear velocity
  96516. * @returns linear velocity or null
  96517. */
  96518. PhysicsImpostor.prototype.getLinearVelocity = function () {
  96519. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  96520. };
  96521. /**
  96522. * Sets the linear velocity
  96523. * @param velocity linear velocity or null
  96524. */
  96525. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  96526. if (this._physicsEngine) {
  96527. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  96528. }
  96529. };
  96530. /**
  96531. * Gets the angular velocity
  96532. * @returns angular velocity or null
  96533. */
  96534. PhysicsImpostor.prototype.getAngularVelocity = function () {
  96535. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  96536. };
  96537. /**
  96538. * Sets the angular velocity
  96539. * @param velocity The velocity or null
  96540. */
  96541. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  96542. if (this._physicsEngine) {
  96543. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  96544. }
  96545. };
  96546. /**
  96547. * Execute a function with the physics plugin native code
  96548. * Provide a function the will have two variables - the world object and the physics body object
  96549. * @param func The function to execute with the physics plugin native code
  96550. */
  96551. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  96552. if (this._physicsEngine) {
  96553. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  96554. }
  96555. };
  96556. /**
  96557. * Register a function that will be executed before the physics world is stepping forward
  96558. * @param func The function to execute before the physics world is stepped forward
  96559. */
  96560. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  96561. this._onBeforePhysicsStepCallbacks.push(func);
  96562. };
  96563. /**
  96564. * Unregister a function that will be executed before the physics world is stepping forward
  96565. * @param func The function to execute before the physics world is stepped forward
  96566. */
  96567. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  96568. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  96569. if (index > -1) {
  96570. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  96571. }
  96572. else {
  96573. BABYLON.Tools.Warn("Function to remove was not found");
  96574. }
  96575. };
  96576. /**
  96577. * Register a function that will be executed after the physics step
  96578. * @param func The function to execute after physics step
  96579. */
  96580. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  96581. this._onAfterPhysicsStepCallbacks.push(func);
  96582. };
  96583. /**
  96584. * Unregisters a function that will be executed after the physics step
  96585. * @param func The function to execute after physics step
  96586. */
  96587. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  96588. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  96589. if (index > -1) {
  96590. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  96591. }
  96592. else {
  96593. BABYLON.Tools.Warn("Function to remove was not found");
  96594. }
  96595. };
  96596. /**
  96597. * register a function that will be executed when this impostor collides against a different body
  96598. * @param collideAgainst Physics imposter, or array of physics imposters to collide against
  96599. * @param func Callback that is executed on collision
  96600. */
  96601. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  96602. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  96603. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  96604. };
  96605. /**
  96606. * Unregisters the physics imposter on contact
  96607. * @param collideAgainst The physics object to collide against
  96608. * @param func Callback to execute on collision
  96609. */
  96610. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  96611. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  96612. var index = -1;
  96613. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  96614. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  96615. // chcek the arrays match
  96616. var sameList = cbDef.otherImpostors.every(function (impostor) {
  96617. return collidedAgainstList.indexOf(impostor) > -1;
  96618. });
  96619. if (sameList) {
  96620. index = idx;
  96621. }
  96622. return sameList;
  96623. }
  96624. return false;
  96625. });
  96626. if (found) {
  96627. this._onPhysicsCollideCallbacks.splice(index, 1);
  96628. }
  96629. else {
  96630. BABYLON.Tools.Warn("Function to remove was not found");
  96631. }
  96632. };
  96633. /**
  96634. * Get the parent rotation
  96635. * @returns The parent rotation
  96636. */
  96637. PhysicsImpostor.prototype.getParentsRotation = function () {
  96638. var parent = this.object.parent;
  96639. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  96640. while (parent) {
  96641. if (parent.rotationQuaternion) {
  96642. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  96643. }
  96644. else {
  96645. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  96646. }
  96647. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  96648. parent = parent.parent;
  96649. }
  96650. return this._tmpQuat;
  96651. };
  96652. /**
  96653. * Apply a force
  96654. * @param force The force to apply
  96655. * @param contactPoint The contact point for the force
  96656. * @returns The physics imposter
  96657. */
  96658. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  96659. if (this._physicsEngine) {
  96660. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  96661. }
  96662. return this;
  96663. };
  96664. /**
  96665. * Apply an impulse
  96666. * @param force The impulse force
  96667. * @param contactPoint The contact point for the impulse force
  96668. * @returns The physics imposter
  96669. */
  96670. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  96671. if (this._physicsEngine) {
  96672. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  96673. }
  96674. return this;
  96675. };
  96676. /**
  96677. * A help function to create a joint
  96678. * @param otherImpostor A physics imposter used to create a joint
  96679. * @param jointType The type of joint
  96680. * @param jointData The data for the joint
  96681. * @returns The physics imposter
  96682. */
  96683. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  96684. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  96685. this.addJoint(otherImpostor, joint);
  96686. return this;
  96687. };
  96688. /**
  96689. * Add a joint to this impostor with a different impostor
  96690. * @param otherImpostor A physics imposter used to add a joint
  96691. * @param joint The joint to add
  96692. * @returns The physics imposter
  96693. */
  96694. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  96695. this._joints.push({
  96696. otherImpostor: otherImpostor,
  96697. joint: joint
  96698. });
  96699. if (this._physicsEngine) {
  96700. this._physicsEngine.addJoint(this, otherImpostor, joint);
  96701. }
  96702. return this;
  96703. };
  96704. /**
  96705. * Will keep this body still, in a sleep mode.
  96706. * @returns the physics imposter
  96707. */
  96708. PhysicsImpostor.prototype.sleep = function () {
  96709. if (this._physicsEngine) {
  96710. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  96711. }
  96712. return this;
  96713. };
  96714. /**
  96715. * Wake the body up.
  96716. * @returns The physics imposter
  96717. */
  96718. PhysicsImpostor.prototype.wakeUp = function () {
  96719. if (this._physicsEngine) {
  96720. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  96721. }
  96722. return this;
  96723. };
  96724. /**
  96725. * Clones the physics imposter
  96726. * @param newObject The physics imposter clones to this physics-enabled object
  96727. * @returns A nullable physics imposter
  96728. */
  96729. PhysicsImpostor.prototype.clone = function (newObject) {
  96730. if (!newObject) {
  96731. return null;
  96732. }
  96733. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  96734. };
  96735. /**
  96736. * Disposes the physics imposter
  96737. */
  96738. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  96739. var _this = this;
  96740. //no dispose if no physics engine is available.
  96741. if (!this._physicsEngine) {
  96742. return;
  96743. }
  96744. this._joints.forEach(function (j) {
  96745. if (_this._physicsEngine) {
  96746. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  96747. }
  96748. });
  96749. //dispose the physics body
  96750. this._physicsEngine.removeImpostor(this);
  96751. if (this.parent) {
  96752. this.parent.forceUpdate();
  96753. }
  96754. else {
  96755. /*this._object.getChildMeshes().forEach(function(mesh) {
  96756. if (mesh.physicsImpostor) {
  96757. if (disposeChildren) {
  96758. mesh.physicsImpostor.dispose();
  96759. mesh.physicsImpostor = null;
  96760. }
  96761. }
  96762. })*/
  96763. }
  96764. this._isDisposed = true;
  96765. };
  96766. /**
  96767. * Sets the delta position
  96768. * @param position The delta position amount
  96769. */
  96770. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  96771. this._deltaPosition.copyFrom(position);
  96772. };
  96773. /**
  96774. * Sets the delta rotation
  96775. * @param rotation The delta rotation amount
  96776. */
  96777. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  96778. if (!this._deltaRotation) {
  96779. this._deltaRotation = new BABYLON.Quaternion();
  96780. }
  96781. this._deltaRotation.copyFrom(rotation);
  96782. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  96783. };
  96784. /**
  96785. * Gets the box size of the physics imposter and stores the result in the input parameter
  96786. * @param result Stores the box size
  96787. * @returns The physics imposter
  96788. */
  96789. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  96790. if (this._physicsEngine) {
  96791. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  96792. }
  96793. return this;
  96794. };
  96795. /**
  96796. * Gets the radius of the physics imposter
  96797. * @returns Radius of the physics imposter
  96798. */
  96799. PhysicsImpostor.prototype.getRadius = function () {
  96800. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  96801. };
  96802. /**
  96803. * Sync a bone with this impostor
  96804. * @param bone The bone to sync to the impostor.
  96805. * @param boneMesh The mesh that the bone is influencing.
  96806. * @param jointPivot The pivot of the joint / bone in local space.
  96807. * @param distToJoint Optional distance from the impostor to the joint.
  96808. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  96809. */
  96810. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  96811. var tempVec = PhysicsImpostor._tmpVecs[0];
  96812. var mesh = this.object;
  96813. if (mesh.rotationQuaternion) {
  96814. if (adjustRotation) {
  96815. var tempQuat = PhysicsImpostor._tmpQuat;
  96816. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  96817. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  96818. }
  96819. else {
  96820. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  96821. }
  96822. }
  96823. tempVec.x = 0;
  96824. tempVec.y = 0;
  96825. tempVec.z = 0;
  96826. if (jointPivot) {
  96827. tempVec.x = jointPivot.x;
  96828. tempVec.y = jointPivot.y;
  96829. tempVec.z = jointPivot.z;
  96830. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  96831. if (distToJoint === undefined || distToJoint === null) {
  96832. distToJoint = jointPivot.length();
  96833. }
  96834. tempVec.x *= distToJoint;
  96835. tempVec.y *= distToJoint;
  96836. tempVec.z *= distToJoint;
  96837. }
  96838. if (bone.getParent()) {
  96839. tempVec.addInPlace(mesh.getAbsolutePosition());
  96840. bone.setAbsolutePosition(tempVec, boneMesh);
  96841. }
  96842. else {
  96843. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  96844. boneMesh.position.x -= tempVec.x;
  96845. boneMesh.position.y -= tempVec.y;
  96846. boneMesh.position.z -= tempVec.z;
  96847. }
  96848. };
  96849. /**
  96850. * Sync impostor to a bone
  96851. * @param bone The bone that the impostor will be synced to.
  96852. * @param boneMesh The mesh that the bone is influencing.
  96853. * @param jointPivot The pivot of the joint / bone in local space.
  96854. * @param distToJoint Optional distance from the impostor to the joint.
  96855. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  96856. * @param boneAxis Optional vector3 axis the bone is aligned with
  96857. */
  96858. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  96859. var mesh = this.object;
  96860. if (mesh.rotationQuaternion) {
  96861. if (adjustRotation) {
  96862. var tempQuat = PhysicsImpostor._tmpQuat;
  96863. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  96864. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  96865. }
  96866. else {
  96867. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  96868. }
  96869. }
  96870. var pos = PhysicsImpostor._tmpVecs[0];
  96871. var boneDir = PhysicsImpostor._tmpVecs[1];
  96872. if (!boneAxis) {
  96873. boneAxis = PhysicsImpostor._tmpVecs[2];
  96874. boneAxis.x = 0;
  96875. boneAxis.y = 1;
  96876. boneAxis.z = 0;
  96877. }
  96878. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  96879. bone.getAbsolutePositionToRef(boneMesh, pos);
  96880. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  96881. distToJoint = jointPivot.length();
  96882. }
  96883. if (distToJoint !== undefined && distToJoint !== null) {
  96884. pos.x += boneDir.x * distToJoint;
  96885. pos.y += boneDir.y * distToJoint;
  96886. pos.z += boneDir.z * distToJoint;
  96887. }
  96888. mesh.setAbsolutePosition(pos);
  96889. };
  96890. /**
  96891. * The default object size of the imposter
  96892. */
  96893. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  96894. /**
  96895. * The identity quaternion of the imposter
  96896. */
  96897. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  96898. PhysicsImpostor._tmpVecs = BABYLON.Tools.BuildArray(3, BABYLON.Vector3.Zero);
  96899. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  96900. //Impostor types
  96901. /**
  96902. * No-Imposter type
  96903. */
  96904. PhysicsImpostor.NoImpostor = 0;
  96905. /**
  96906. * Sphere-Imposter type
  96907. */
  96908. PhysicsImpostor.SphereImpostor = 1;
  96909. /**
  96910. * Box-Imposter type
  96911. */
  96912. PhysicsImpostor.BoxImpostor = 2;
  96913. /**
  96914. * Plane-Imposter type
  96915. */
  96916. PhysicsImpostor.PlaneImpostor = 3;
  96917. /**
  96918. * Mesh-imposter type
  96919. */
  96920. PhysicsImpostor.MeshImpostor = 4;
  96921. /**
  96922. * Cylinder-Imposter type
  96923. */
  96924. PhysicsImpostor.CylinderImpostor = 7;
  96925. /**
  96926. * Particle-Imposter type
  96927. */
  96928. PhysicsImpostor.ParticleImpostor = 8;
  96929. /**
  96930. * Heightmap-Imposter type
  96931. */
  96932. PhysicsImpostor.HeightmapImpostor = 9;
  96933. return PhysicsImpostor;
  96934. }());
  96935. BABYLON.PhysicsImpostor = PhysicsImpostor;
  96936. })(BABYLON || (BABYLON = {}));
  96937. //# sourceMappingURL=physicsImpostor.js.map
  96938. var BABYLON;
  96939. (function (BABYLON) {
  96940. /**
  96941. * Class used to control physics engine
  96942. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  96943. */
  96944. var PhysicsEngine = /** @class */ (function () {
  96945. /**
  96946. * Creates a new Physics Engine
  96947. * @param gravity defines the gravity vector used by the simulation
  96948. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  96949. */
  96950. function PhysicsEngine(gravity, _physicsPlugin) {
  96951. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  96952. this._physicsPlugin = _physicsPlugin;
  96953. this._impostors = [];
  96954. this._joints = [];
  96955. if (!this._physicsPlugin.isSupported()) {
  96956. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  96957. + "Please make sure it is included.");
  96958. }
  96959. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  96960. this.setGravity(gravity);
  96961. this.setTimeStep();
  96962. }
  96963. /**
  96964. * Sets the gravity vector used by the simulation
  96965. * @param gravity defines the gravity vector to use
  96966. */
  96967. PhysicsEngine.prototype.setGravity = function (gravity) {
  96968. this.gravity = gravity;
  96969. this._physicsPlugin.setGravity(this.gravity);
  96970. };
  96971. /**
  96972. * Set the time step of the physics engine.
  96973. * Default is 1/60.
  96974. * To slow it down, enter 1/600 for example.
  96975. * To speed it up, 1/30
  96976. * @param newTimeStep defines the new timestep to apply to this world.
  96977. */
  96978. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  96979. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  96980. this._physicsPlugin.setTimeStep(newTimeStep);
  96981. };
  96982. /**
  96983. * Get the time step of the physics engine.
  96984. * @returns the current time step
  96985. */
  96986. PhysicsEngine.prototype.getTimeStep = function () {
  96987. return this._physicsPlugin.getTimeStep();
  96988. };
  96989. /**
  96990. * Release all resources
  96991. */
  96992. PhysicsEngine.prototype.dispose = function () {
  96993. this._impostors.forEach(function (impostor) {
  96994. impostor.dispose();
  96995. });
  96996. this._physicsPlugin.dispose();
  96997. };
  96998. /**
  96999. * Gets the name of the current physics plugin
  97000. * @returns the name of the plugin
  97001. */
  97002. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  97003. return this._physicsPlugin.name;
  97004. };
  97005. /**
  97006. * Adding a new impostor for the impostor tracking.
  97007. * This will be done by the impostor itself.
  97008. * @param impostor the impostor to add
  97009. */
  97010. PhysicsEngine.prototype.addImpostor = function (impostor) {
  97011. impostor.uniqueId = this._impostors.push(impostor);
  97012. //if no parent, generate the body
  97013. if (!impostor.parent) {
  97014. this._physicsPlugin.generatePhysicsBody(impostor);
  97015. }
  97016. };
  97017. /**
  97018. * Remove an impostor from the engine.
  97019. * This impostor and its mesh will not longer be updated by the physics engine.
  97020. * @param impostor the impostor to remove
  97021. */
  97022. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  97023. var index = this._impostors.indexOf(impostor);
  97024. if (index > -1) {
  97025. var removed = this._impostors.splice(index, 1);
  97026. //Is it needed?
  97027. if (removed.length) {
  97028. //this will also remove it from the world.
  97029. removed[0].physicsBody = null;
  97030. }
  97031. }
  97032. };
  97033. /**
  97034. * Add a joint to the physics engine
  97035. * @param mainImpostor defines the main impostor to which the joint is added.
  97036. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  97037. * @param joint defines the joint that will connect both impostors.
  97038. */
  97039. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  97040. var impostorJoint = {
  97041. mainImpostor: mainImpostor,
  97042. connectedImpostor: connectedImpostor,
  97043. joint: joint
  97044. };
  97045. joint.physicsPlugin = this._physicsPlugin;
  97046. this._joints.push(impostorJoint);
  97047. this._physicsPlugin.generateJoint(impostorJoint);
  97048. };
  97049. /**
  97050. * Removes a joint from the simulation
  97051. * @param mainImpostor defines the impostor used with the joint
  97052. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  97053. * @param joint defines the joint to remove
  97054. */
  97055. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  97056. var matchingJoints = this._joints.filter(function (impostorJoint) {
  97057. return (impostorJoint.connectedImpostor === connectedImpostor
  97058. && impostorJoint.joint === joint
  97059. && impostorJoint.mainImpostor === mainImpostor);
  97060. });
  97061. if (matchingJoints.length) {
  97062. this._physicsPlugin.removeJoint(matchingJoints[0]);
  97063. //TODO remove it from the list as well
  97064. }
  97065. };
  97066. /**
  97067. * Called by the scene. No need to call it.
  97068. * @param delta defines the timespam between frames
  97069. */
  97070. PhysicsEngine.prototype._step = function (delta) {
  97071. var _this = this;
  97072. //check if any mesh has no body / requires an update
  97073. this._impostors.forEach(function (impostor) {
  97074. if (impostor.isBodyInitRequired()) {
  97075. _this._physicsPlugin.generatePhysicsBody(impostor);
  97076. }
  97077. });
  97078. if (delta > 0.1) {
  97079. delta = 0.1;
  97080. }
  97081. else if (delta <= 0) {
  97082. delta = 1.0 / 60.0;
  97083. }
  97084. this._physicsPlugin.executeStep(delta, this._impostors);
  97085. };
  97086. /**
  97087. * Gets the current plugin used to run the simulation
  97088. * @returns current plugin
  97089. */
  97090. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  97091. return this._physicsPlugin;
  97092. };
  97093. /**
  97094. * Gets the list of physic impostors
  97095. * @returns an array of PhysicsImpostor
  97096. */
  97097. PhysicsEngine.prototype.getImpostors = function () {
  97098. return this._impostors;
  97099. };
  97100. /**
  97101. * Gets the impostor for a physics enabled object
  97102. * @param object defines the object impersonated by the impostor
  97103. * @returns the PhysicsImpostor or null if not found
  97104. */
  97105. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  97106. for (var i = 0; i < this._impostors.length; ++i) {
  97107. if (this._impostors[i].object === object) {
  97108. return this._impostors[i];
  97109. }
  97110. }
  97111. return null;
  97112. };
  97113. /**
  97114. * Gets the impostor for a physics body object
  97115. * @param body defines physics body used by the impostor
  97116. * @returns the PhysicsImpostor or null if not found
  97117. */
  97118. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  97119. for (var i = 0; i < this._impostors.length; ++i) {
  97120. if (this._impostors[i].physicsBody === body) {
  97121. return this._impostors[i];
  97122. }
  97123. }
  97124. return null;
  97125. };
  97126. /**
  97127. * Global value used to control the smallest number supported by the simulation
  97128. */
  97129. PhysicsEngine.Epsilon = 0.001;
  97130. return PhysicsEngine;
  97131. }());
  97132. BABYLON.PhysicsEngine = PhysicsEngine;
  97133. })(BABYLON || (BABYLON = {}));
  97134. //# sourceMappingURL=physicsEngine.js.map
  97135. var BABYLON;
  97136. (function (BABYLON) {
  97137. /**
  97138. * A helper for physics simulations
  97139. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97140. */
  97141. var PhysicsHelper = /** @class */ (function () {
  97142. /**
  97143. * Initializes the Physics helper
  97144. * @param scene Babylon.js scene
  97145. */
  97146. function PhysicsHelper(scene) {
  97147. this._scene = scene;
  97148. this._physicsEngine = this._scene.getPhysicsEngine();
  97149. if (!this._physicsEngine) {
  97150. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  97151. }
  97152. }
  97153. /**
  97154. * Applies a radial explosion impulse
  97155. * @param origin the origin of the explosion
  97156. * @param radius the explosion radius
  97157. * @param strength the explosion strength
  97158. * @param falloff possible options: Constant & Linear. Defaults to Constant
  97159. * @returns A physics radial explosion event, or null
  97160. */
  97161. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  97162. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  97163. if (!this._physicsEngine) {
  97164. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  97165. return null;
  97166. }
  97167. var impostors = this._physicsEngine.getImpostors();
  97168. if (impostors.length === 0) {
  97169. return null;
  97170. }
  97171. var event = new PhysicsRadialExplosionEvent(this._scene);
  97172. impostors.forEach(function (impostor) {
  97173. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  97174. if (!impostorForceAndContactPoint) {
  97175. return;
  97176. }
  97177. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  97178. });
  97179. event.dispose(false);
  97180. return event;
  97181. };
  97182. /**
  97183. * Applies a radial explosion force
  97184. * @param origin the origin of the explosion
  97185. * @param radius the explosion radius
  97186. * @param strength the explosion strength
  97187. * @param falloff possible options: Constant & Linear. Defaults to Constant
  97188. * @returns A physics radial explosion event, or null
  97189. */
  97190. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  97191. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  97192. if (!this._physicsEngine) {
  97193. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  97194. return null;
  97195. }
  97196. var impostors = this._physicsEngine.getImpostors();
  97197. if (impostors.length === 0) {
  97198. return null;
  97199. }
  97200. var event = new PhysicsRadialExplosionEvent(this._scene);
  97201. impostors.forEach(function (impostor) {
  97202. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  97203. if (!impostorForceAndContactPoint) {
  97204. return;
  97205. }
  97206. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  97207. });
  97208. event.dispose(false);
  97209. return event;
  97210. };
  97211. /**
  97212. * Creates a gravitational field
  97213. * @param origin the origin of the explosion
  97214. * @param radius the explosion radius
  97215. * @param strength the explosion strength
  97216. * @param falloff possible options: Constant & Linear. Defaults to Constant
  97217. * @returns A physics gravitational field event, or null
  97218. */
  97219. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  97220. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  97221. if (!this._physicsEngine) {
  97222. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  97223. return null;
  97224. }
  97225. var impostors = this._physicsEngine.getImpostors();
  97226. if (impostors.length === 0) {
  97227. return null;
  97228. }
  97229. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  97230. event.dispose(false);
  97231. return event;
  97232. };
  97233. /**
  97234. * Creates a physics updraft event
  97235. * @param origin the origin of the updraft
  97236. * @param radius the radius of the updraft
  97237. * @param strength the strength of the updraft
  97238. * @param height the height of the updraft
  97239. * @param updraftMode possible options: Center & Perpendicular. Defaults to Center
  97240. * @returns A physics updraft event, or null
  97241. */
  97242. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  97243. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  97244. if (!this._physicsEngine) {
  97245. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  97246. return null;
  97247. }
  97248. if (this._physicsEngine.getImpostors().length === 0) {
  97249. return null;
  97250. }
  97251. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  97252. event.dispose(false);
  97253. return event;
  97254. };
  97255. /**
  97256. * Creates a physics vortex event
  97257. * @param origin the of the vortex
  97258. * @param radius the radius of the vortex
  97259. * @param strength the strength of the vortex
  97260. * @param height the height of the vortex
  97261. * @returns a Physics vortex event, or null
  97262. * A physics vortex event or null
  97263. */
  97264. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  97265. if (!this._physicsEngine) {
  97266. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  97267. return null;
  97268. }
  97269. if (this._physicsEngine.getImpostors().length === 0) {
  97270. return null;
  97271. }
  97272. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  97273. event.dispose(false);
  97274. return event;
  97275. };
  97276. return PhysicsHelper;
  97277. }());
  97278. BABYLON.PhysicsHelper = PhysicsHelper;
  97279. /**
  97280. * Represents a physics radial explosion event
  97281. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97282. */
  97283. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  97284. /**
  97285. * Initializes a radial explosioin event
  97286. * @param scene BabylonJS scene
  97287. */
  97288. function PhysicsRadialExplosionEvent(scene) {
  97289. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  97290. this._rays = [];
  97291. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  97292. this._scene = scene;
  97293. }
  97294. /**
  97295. * Returns the data related to the radial explosion event (sphere & rays).
  97296. * @returns The radial explosion event data
  97297. */
  97298. PhysicsRadialExplosionEvent.prototype.getData = function () {
  97299. this._dataFetched = true;
  97300. return {
  97301. sphere: this._sphere,
  97302. rays: this._rays,
  97303. };
  97304. };
  97305. /**
  97306. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  97307. * @param impostor A physics imposter
  97308. * @param origin the origin of the explosion
  97309. * @param radius the explosion radius
  97310. * @param strength the explosion strength
  97311. * @param falloff possible options: Constant & Linear
  97312. * @returns {Nullable<PhysicsForceAndContactPoint>} A physics force and contact point, or null
  97313. */
  97314. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  97315. if (impostor.mass === 0) {
  97316. return null;
  97317. }
  97318. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  97319. return null;
  97320. }
  97321. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  97322. return null;
  97323. }
  97324. var impostorObjectCenter = impostor.getObjectCenter();
  97325. var direction = impostorObjectCenter.subtract(origin);
  97326. var ray = new BABYLON.Ray(origin, direction, radius);
  97327. this._rays.push(ray);
  97328. var hit = ray.intersectsMesh(impostor.object);
  97329. var contactPoint = hit.pickedPoint;
  97330. if (!contactPoint) {
  97331. return null;
  97332. }
  97333. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  97334. if (distanceFromOrigin > radius) {
  97335. return null;
  97336. }
  97337. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  97338. ? strength
  97339. : strength * (1 - (distanceFromOrigin / radius));
  97340. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  97341. return { force: force, contactPoint: contactPoint };
  97342. };
  97343. /**
  97344. * Disposes the sphere.
  97345. * @param force Specifies if the sphere should be disposed by force
  97346. */
  97347. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  97348. var _this = this;
  97349. if (force === void 0) { force = true; }
  97350. if (force) {
  97351. this._sphere.dispose();
  97352. }
  97353. else {
  97354. setTimeout(function () {
  97355. if (!_this._dataFetched) {
  97356. _this._sphere.dispose();
  97357. }
  97358. }, 0);
  97359. }
  97360. };
  97361. /*** Helpers ***/
  97362. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  97363. if (!this._sphere) {
  97364. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  97365. this._sphere.isVisible = false;
  97366. }
  97367. };
  97368. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  97369. var impostorObject = impostor.object;
  97370. this._prepareSphere();
  97371. this._sphere.position = origin;
  97372. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  97373. this._sphere._updateBoundingInfo();
  97374. this._sphere.computeWorldMatrix(true);
  97375. return this._sphere.intersectsMesh(impostorObject, true);
  97376. };
  97377. return PhysicsRadialExplosionEvent;
  97378. }());
  97379. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  97380. /**
  97381. * Represents a gravitational field event
  97382. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97383. */
  97384. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  97385. /**
  97386. * Initializes the physics gravitational field event
  97387. * @param physicsHelper A physics helper
  97388. * @param scene BabylonJS scene
  97389. * @param origin The origin position of the gravitational field event
  97390. * @param radius The radius of the gravitational field event
  97391. * @param strength The strength of the gravitational field event
  97392. * @param falloff The falloff for the gravitational field event
  97393. */
  97394. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  97395. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  97396. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  97397. this._physicsHelper = physicsHelper;
  97398. this._scene = scene;
  97399. this._origin = origin;
  97400. this._radius = radius;
  97401. this._strength = strength;
  97402. this._falloff = falloff;
  97403. this._tickCallback = this._tick.bind(this);
  97404. }
  97405. /**
  97406. * Returns the data related to the gravitational field event (sphere).
  97407. * @returns A gravitational field event
  97408. */
  97409. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  97410. this._dataFetched = true;
  97411. return {
  97412. sphere: this._sphere,
  97413. };
  97414. };
  97415. /**
  97416. * Enables the gravitational field.
  97417. */
  97418. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  97419. this._tickCallback.call(this);
  97420. this._scene.registerBeforeRender(this._tickCallback);
  97421. };
  97422. /**
  97423. * Disables the gravitational field.
  97424. */
  97425. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  97426. this._scene.unregisterBeforeRender(this._tickCallback);
  97427. };
  97428. /**
  97429. * Disposes the sphere.
  97430. * @param force The force to dispose from the gravitational field event
  97431. */
  97432. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  97433. var _this = this;
  97434. if (force === void 0) { force = true; }
  97435. if (force) {
  97436. this._sphere.dispose();
  97437. }
  97438. else {
  97439. setTimeout(function () {
  97440. if (!_this._dataFetched) {
  97441. _this._sphere.dispose();
  97442. }
  97443. }, 0);
  97444. }
  97445. };
  97446. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  97447. // Since the params won't change, we fetch the event only once
  97448. if (this._sphere) {
  97449. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  97450. }
  97451. else {
  97452. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  97453. if (radialExplosionEvent) {
  97454. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  97455. }
  97456. }
  97457. };
  97458. return PhysicsGravitationalFieldEvent;
  97459. }());
  97460. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  97461. /**
  97462. * Represents a physics updraft event
  97463. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97464. */
  97465. var PhysicsUpdraftEvent = /** @class */ (function () {
  97466. /**
  97467. * Initializes the physics updraft event
  97468. * @param _scene BabylonJS scene
  97469. * @param _origin The origin position of the updraft
  97470. * @param _radius The radius of the updraft
  97471. * @param _strength The strength of the updraft
  97472. * @param _height The height of the updraft
  97473. * @param _updraftMode The mode of the updraft
  97474. */
  97475. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  97476. this._scene = _scene;
  97477. this._origin = _origin;
  97478. this._radius = _radius;
  97479. this._strength = _strength;
  97480. this._height = _height;
  97481. this._updraftMode = _updraftMode;
  97482. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  97483. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  97484. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  97485. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  97486. this._physicsEngine = this._scene.getPhysicsEngine();
  97487. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  97488. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  97489. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  97490. this._originDirection = this._origin.subtract(this._originTop).normalize();
  97491. }
  97492. this._tickCallback = this._tick.bind(this);
  97493. }
  97494. /**
  97495. * Returns the data related to the updraft event (cylinder).
  97496. * @returns A physics updraft event
  97497. */
  97498. PhysicsUpdraftEvent.prototype.getData = function () {
  97499. this._dataFetched = true;
  97500. return {
  97501. cylinder: this._cylinder,
  97502. };
  97503. };
  97504. /**
  97505. * Enables the updraft.
  97506. */
  97507. PhysicsUpdraftEvent.prototype.enable = function () {
  97508. this._tickCallback.call(this);
  97509. this._scene.registerBeforeRender(this._tickCallback);
  97510. };
  97511. /**
  97512. * Disables the cortex.
  97513. */
  97514. PhysicsUpdraftEvent.prototype.disable = function () {
  97515. this._scene.unregisterBeforeRender(this._tickCallback);
  97516. };
  97517. /**
  97518. * Disposes the sphere.
  97519. * @param force Specifies if the updraft should be disposed by force
  97520. */
  97521. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  97522. var _this = this;
  97523. if (force === void 0) { force = true; }
  97524. if (force) {
  97525. this._cylinder.dispose();
  97526. }
  97527. else {
  97528. setTimeout(function () {
  97529. if (!_this._dataFetched) {
  97530. _this._cylinder.dispose();
  97531. }
  97532. }, 0);
  97533. }
  97534. };
  97535. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  97536. if (impostor.mass === 0) {
  97537. return null;
  97538. }
  97539. if (!this._intersectsWithCylinder(impostor)) {
  97540. return null;
  97541. }
  97542. var impostorObjectCenter = impostor.getObjectCenter();
  97543. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  97544. var direction = this._originDirection;
  97545. }
  97546. else {
  97547. var direction = impostorObjectCenter.subtract(this._originTop);
  97548. }
  97549. var multiplier = this._strength * -1;
  97550. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  97551. return { force: force, contactPoint: impostorObjectCenter };
  97552. };
  97553. PhysicsUpdraftEvent.prototype._tick = function () {
  97554. var _this = this;
  97555. this._physicsEngine.getImpostors().forEach(function (impostor) {
  97556. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  97557. if (!impostorForceAndContactPoint) {
  97558. return;
  97559. }
  97560. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  97561. });
  97562. };
  97563. /*** Helpers ***/
  97564. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  97565. if (!this._cylinder) {
  97566. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  97567. height: this._height,
  97568. diameter: this._radius * 2,
  97569. }, this._scene);
  97570. this._cylinder.isVisible = false;
  97571. }
  97572. };
  97573. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  97574. var impostorObject = impostor.object;
  97575. this._prepareCylinder();
  97576. this._cylinder.position = this._cylinderPosition;
  97577. return this._cylinder.intersectsMesh(impostorObject, true);
  97578. };
  97579. return PhysicsUpdraftEvent;
  97580. }());
  97581. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  97582. /**
  97583. * Represents a physics vortex event
  97584. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97585. */
  97586. var PhysicsVortexEvent = /** @class */ (function () {
  97587. /**
  97588. * Initializes the physics vortex event
  97589. * @param _scene The BabylonJS scene
  97590. * @param _origin The origin position of the vortex
  97591. * @param _radius The radius of the vortex
  97592. * @param _strength The strength of the vortex
  97593. * @param _height The height of the vortex
  97594. */
  97595. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  97596. this._scene = _scene;
  97597. this._origin = _origin;
  97598. this._radius = _radius;
  97599. this._strength = _strength;
  97600. this._height = _height;
  97601. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  97602. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  97603. this._updraftMultiplier = 0.02;
  97604. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  97605. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  97606. this._physicsEngine = this._scene.getPhysicsEngine();
  97607. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  97608. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  97609. this._tickCallback = this._tick.bind(this);
  97610. }
  97611. /**
  97612. * Returns the data related to the vortex event (cylinder).
  97613. * @returns The physics vortex event data
  97614. */
  97615. PhysicsVortexEvent.prototype.getData = function () {
  97616. this._dataFetched = true;
  97617. return {
  97618. cylinder: this._cylinder,
  97619. };
  97620. };
  97621. /**
  97622. * Enables the vortex.
  97623. */
  97624. PhysicsVortexEvent.prototype.enable = function () {
  97625. this._tickCallback.call(this);
  97626. this._scene.registerBeforeRender(this._tickCallback);
  97627. };
  97628. /**
  97629. * Disables the cortex.
  97630. */
  97631. PhysicsVortexEvent.prototype.disable = function () {
  97632. this._scene.unregisterBeforeRender(this._tickCallback);
  97633. };
  97634. /**
  97635. * Disposes the sphere.
  97636. * @param force
  97637. */
  97638. PhysicsVortexEvent.prototype.dispose = function (force) {
  97639. var _this = this;
  97640. if (force === void 0) { force = true; }
  97641. if (force) {
  97642. this._cylinder.dispose();
  97643. }
  97644. else {
  97645. setTimeout(function () {
  97646. if (!_this._dataFetched) {
  97647. _this._cylinder.dispose();
  97648. }
  97649. }, 0);
  97650. }
  97651. };
  97652. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  97653. if (impostor.mass === 0) {
  97654. return null;
  97655. }
  97656. if (!this._intersectsWithCylinder(impostor)) {
  97657. return null;
  97658. }
  97659. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  97660. return null;
  97661. }
  97662. var impostorObjectCenter = impostor.getObjectCenter();
  97663. 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)
  97664. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  97665. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  97666. var hit = ray.intersectsMesh(impostor.object);
  97667. var contactPoint = hit.pickedPoint;
  97668. if (!contactPoint) {
  97669. return null;
  97670. }
  97671. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  97672. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  97673. var directionToOrigin = contactPoint.normalize();
  97674. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  97675. directionToOrigin = directionToOrigin.negate();
  97676. }
  97677. // TODO: find a more physically based solution
  97678. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  97679. var forceX = directionToOrigin.x * this._strength / 8;
  97680. var forceY = directionToOrigin.y * this._updraftMultiplier;
  97681. var forceZ = directionToOrigin.z * this._strength / 8;
  97682. }
  97683. else {
  97684. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  97685. var forceY = this._originTop.y * this._updraftMultiplier;
  97686. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  97687. }
  97688. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  97689. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  97690. return { force: force, contactPoint: impostorObjectCenter };
  97691. };
  97692. PhysicsVortexEvent.prototype._tick = function () {
  97693. var _this = this;
  97694. this._physicsEngine.getImpostors().forEach(function (impostor) {
  97695. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  97696. if (!impostorForceAndContactPoint) {
  97697. return;
  97698. }
  97699. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  97700. });
  97701. };
  97702. /*** Helpers ***/
  97703. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  97704. if (!this._cylinder) {
  97705. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  97706. height: this._height,
  97707. diameter: this._radius * 2,
  97708. }, this._scene);
  97709. this._cylinder.isVisible = false;
  97710. }
  97711. };
  97712. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  97713. var impostorObject = impostor.object;
  97714. this._prepareCylinder();
  97715. this._cylinder.position = this._cylinderPosition;
  97716. return this._cylinder.intersectsMesh(impostorObject, true);
  97717. };
  97718. return PhysicsVortexEvent;
  97719. }());
  97720. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  97721. /**
  97722. * The strenght of the force in correspondence to the distance of the affected object
  97723. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97724. */
  97725. var PhysicsRadialImpulseFalloff;
  97726. (function (PhysicsRadialImpulseFalloff) {
  97727. /** Defines that impulse is constant in strength across it's whole radius */
  97728. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  97729. /** DEfines that impulse gets weaker if it's further from the origin */
  97730. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  97731. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  97732. /**
  97733. * The strength of the force in correspondence to the distance of the affected object
  97734. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  97735. */
  97736. var PhysicsUpdraftMode;
  97737. (function (PhysicsUpdraftMode) {
  97738. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  97739. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  97740. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  97741. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  97742. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  97743. })(BABYLON || (BABYLON = {}));
  97744. //# sourceMappingURL=physicsHelper.js.map
  97745. var BABYLON;
  97746. (function (BABYLON) {
  97747. /** @hidden */
  97748. var CannonJSPlugin = /** @class */ (function () {
  97749. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  97750. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  97751. if (iterations === void 0) { iterations = 10; }
  97752. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  97753. this.name = "CannonJSPlugin";
  97754. this._physicsMaterials = new Array();
  97755. this._fixedTimeStep = 1 / 60;
  97756. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  97757. this.BJSCANNON = CANNON;
  97758. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  97759. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  97760. this._tmpPosition = BABYLON.Vector3.Zero();
  97761. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  97762. this._tmpUnityRotation = new BABYLON.Quaternion();
  97763. if (!this.isSupported()) {
  97764. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  97765. return;
  97766. }
  97767. this._extendNamespace();
  97768. this.world = new this.BJSCANNON.World();
  97769. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  97770. this.world.solver.iterations = iterations;
  97771. }
  97772. CannonJSPlugin.prototype.setGravity = function (gravity) {
  97773. this.world.gravity.copy(gravity);
  97774. };
  97775. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  97776. this._fixedTimeStep = timeStep;
  97777. };
  97778. CannonJSPlugin.prototype.getTimeStep = function () {
  97779. return this._fixedTimeStep;
  97780. };
  97781. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  97782. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  97783. };
  97784. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  97785. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  97786. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  97787. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  97788. };
  97789. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  97790. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  97791. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  97792. impostor.physicsBody.applyForce(impulse, worldPoint);
  97793. };
  97794. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  97795. //parent-child relationship. Does this impostor has a parent impostor?
  97796. if (impostor.parent) {
  97797. if (impostor.physicsBody) {
  97798. this.removePhysicsBody(impostor);
  97799. //TODO is that needed?
  97800. impostor.forceUpdate();
  97801. }
  97802. return;
  97803. }
  97804. //should a new body be created for this impostor?
  97805. if (impostor.isBodyInitRequired()) {
  97806. var shape = this._createShape(impostor);
  97807. //unregister events, if body is being changed
  97808. var oldBody = impostor.physicsBody;
  97809. if (oldBody) {
  97810. this.removePhysicsBody(impostor);
  97811. }
  97812. //create the body and material
  97813. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  97814. var bodyCreationObject = {
  97815. mass: impostor.getParam("mass"),
  97816. material: material
  97817. };
  97818. // A simple extend, in case native options were used.
  97819. var nativeOptions = impostor.getParam("nativeOptions");
  97820. for (var key in nativeOptions) {
  97821. if (nativeOptions.hasOwnProperty(key)) {
  97822. bodyCreationObject[key] = nativeOptions[key];
  97823. }
  97824. }
  97825. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  97826. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  97827. this.world.addEventListener("preStep", impostor.beforeStep);
  97828. this.world.addEventListener("postStep", impostor.afterStep);
  97829. impostor.physicsBody.addShape(shape);
  97830. this.world.add(impostor.physicsBody);
  97831. //try to keep the body moving in the right direction by taking old properties.
  97832. //Should be tested!
  97833. if (oldBody) {
  97834. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  97835. impostor.physicsBody[param].copy(oldBody[param]);
  97836. });
  97837. }
  97838. this._processChildMeshes(impostor);
  97839. }
  97840. //now update the body's transformation
  97841. this._updatePhysicsBodyTransformation(impostor);
  97842. };
  97843. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  97844. var _this = this;
  97845. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  97846. var currentRotation = mainImpostor.object.rotationQuaternion;
  97847. if (meshChildren.length) {
  97848. var processMesh = function (localPosition, mesh) {
  97849. if (!currentRotation || !mesh.rotationQuaternion) {
  97850. return;
  97851. }
  97852. var childImpostor = mesh.getPhysicsImpostor();
  97853. if (childImpostor) {
  97854. var parent = childImpostor.parent;
  97855. if (parent !== mainImpostor) {
  97856. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  97857. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  97858. if (childImpostor.physicsBody) {
  97859. _this.removePhysicsBody(childImpostor);
  97860. childImpostor.physicsBody = null;
  97861. }
  97862. childImpostor.parent = mainImpostor;
  97863. childImpostor.resetUpdateFlags();
  97864. 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));
  97865. //Add the mass of the children.
  97866. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  97867. }
  97868. }
  97869. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  97870. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  97871. };
  97872. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  97873. }
  97874. };
  97875. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  97876. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  97877. this.world.removeEventListener("preStep", impostor.beforeStep);
  97878. this.world.removeEventListener("postStep", impostor.afterStep);
  97879. this.world.remove(impostor.physicsBody);
  97880. };
  97881. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  97882. var mainBody = impostorJoint.mainImpostor.physicsBody;
  97883. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  97884. if (!mainBody || !connectedBody) {
  97885. return;
  97886. }
  97887. var constraint;
  97888. var jointData = impostorJoint.joint.jointData;
  97889. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  97890. var constraintData = {
  97891. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  97892. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  97893. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  97894. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  97895. maxForce: jointData.nativeParams.maxForce,
  97896. collideConnected: !!jointData.collision
  97897. };
  97898. switch (impostorJoint.joint.type) {
  97899. case BABYLON.PhysicsJoint.HingeJoint:
  97900. case BABYLON.PhysicsJoint.Hinge2Joint:
  97901. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  97902. break;
  97903. case BABYLON.PhysicsJoint.DistanceJoint:
  97904. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  97905. break;
  97906. case BABYLON.PhysicsJoint.SpringJoint:
  97907. var springData = jointData;
  97908. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  97909. restLength: springData.length,
  97910. stiffness: springData.stiffness,
  97911. damping: springData.damping,
  97912. localAnchorA: constraintData.pivotA,
  97913. localAnchorB: constraintData.pivotB
  97914. });
  97915. break;
  97916. case BABYLON.PhysicsJoint.LockJoint:
  97917. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  97918. break;
  97919. case BABYLON.PhysicsJoint.PointToPointJoint:
  97920. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  97921. default:
  97922. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  97923. break;
  97924. }
  97925. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  97926. constraint.collideConnected = !!jointData.collision;
  97927. impostorJoint.joint.physicsJoint = constraint;
  97928. //don't add spring as constraint, as it is not one.
  97929. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  97930. this.world.addConstraint(constraint);
  97931. }
  97932. else {
  97933. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  97934. constraint.applyForce();
  97935. };
  97936. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  97937. }
  97938. };
  97939. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  97940. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  97941. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  97942. }
  97943. else {
  97944. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  97945. }
  97946. };
  97947. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  97948. var index;
  97949. var mat;
  97950. for (index = 0; index < this._physicsMaterials.length; index++) {
  97951. mat = this._physicsMaterials[index];
  97952. if (mat.friction === friction && mat.restitution === restitution) {
  97953. return mat;
  97954. }
  97955. }
  97956. var currentMat = new this.BJSCANNON.Material(name);
  97957. currentMat.friction = friction;
  97958. currentMat.restitution = restitution;
  97959. this._physicsMaterials.push(currentMat);
  97960. return currentMat;
  97961. };
  97962. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  97963. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  97964. };
  97965. CannonJSPlugin.prototype._createShape = function (impostor) {
  97966. var object = impostor.object;
  97967. var returnValue;
  97968. var extendSize = impostor.getObjectExtendSize();
  97969. switch (impostor.type) {
  97970. case BABYLON.PhysicsImpostor.SphereImpostor:
  97971. var radiusX = extendSize.x;
  97972. var radiusY = extendSize.y;
  97973. var radiusZ = extendSize.z;
  97974. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  97975. break;
  97976. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  97977. case BABYLON.PhysicsImpostor.CylinderImpostor:
  97978. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  97979. break;
  97980. case BABYLON.PhysicsImpostor.BoxImpostor:
  97981. var box = extendSize.scale(0.5);
  97982. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  97983. break;
  97984. case BABYLON.PhysicsImpostor.PlaneImpostor:
  97985. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  97986. returnValue = new this.BJSCANNON.Plane();
  97987. break;
  97988. case BABYLON.PhysicsImpostor.MeshImpostor:
  97989. // should transform the vertex data to world coordinates!!
  97990. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  97991. var rawFaces = object.getIndices ? object.getIndices() : [];
  97992. if (!rawVerts) {
  97993. return;
  97994. }
  97995. // get only scale! so the object could transform correctly.
  97996. var oldPosition = object.position.clone();
  97997. var oldRotation = object.rotation && object.rotation.clone();
  97998. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  97999. object.position.copyFromFloats(0, 0, 0);
  98000. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  98001. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  98002. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  98003. var transform = object.computeWorldMatrix(true);
  98004. // convert rawVerts to object space
  98005. var temp = new Array();
  98006. var index;
  98007. for (index = 0; index < rawVerts.length; index += 3) {
  98008. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  98009. }
  98010. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  98011. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  98012. //now set back the transformation!
  98013. object.position.copyFrom(oldPosition);
  98014. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  98015. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  98016. break;
  98017. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  98018. var oldPosition2 = object.position.clone();
  98019. var oldRotation2 = object.rotation && object.rotation.clone();
  98020. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  98021. object.position.copyFromFloats(0, 0, 0);
  98022. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  98023. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  98024. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  98025. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  98026. returnValue = this._createHeightmap(object);
  98027. object.position.copyFrom(oldPosition2);
  98028. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  98029. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  98030. object.computeWorldMatrix(true);
  98031. break;
  98032. case BABYLON.PhysicsImpostor.ParticleImpostor:
  98033. returnValue = new this.BJSCANNON.Particle();
  98034. break;
  98035. }
  98036. return returnValue;
  98037. };
  98038. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  98039. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  98040. var transform = object.computeWorldMatrix(true);
  98041. // convert rawVerts to object space
  98042. var temp = new Array();
  98043. var index;
  98044. for (index = 0; index < pos.length; index += 3) {
  98045. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  98046. }
  98047. pos = temp;
  98048. var matrix = new Array();
  98049. //For now pointDepth will not be used and will be automatically calculated.
  98050. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  98051. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  98052. var boundingInfo = object.getBoundingInfo();
  98053. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  98054. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  98055. var elementSize = dim * 2 / arraySize;
  98056. for (var i = 0; i < pos.length; i = i + 3) {
  98057. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  98058. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  98059. var y = -pos[i + 2] + minY;
  98060. if (!matrix[x]) {
  98061. matrix[x] = [];
  98062. }
  98063. if (!matrix[x][z]) {
  98064. matrix[x][z] = y;
  98065. }
  98066. matrix[x][z] = Math.max(y, matrix[x][z]);
  98067. }
  98068. for (var x = 0; x <= arraySize; ++x) {
  98069. if (!matrix[x]) {
  98070. var loc = 1;
  98071. while (!matrix[(x + loc) % arraySize]) {
  98072. loc++;
  98073. }
  98074. matrix[x] = matrix[(x + loc) % arraySize].slice();
  98075. //console.log("missing x", x);
  98076. }
  98077. for (var z = 0; z <= arraySize; ++z) {
  98078. if (!matrix[x][z]) {
  98079. var loc = 1;
  98080. var newValue;
  98081. while (newValue === undefined) {
  98082. newValue = matrix[x][(z + loc++) % arraySize];
  98083. }
  98084. matrix[x][z] = newValue;
  98085. }
  98086. }
  98087. }
  98088. var shape = new this.BJSCANNON.Heightfield(matrix, {
  98089. elementSize: elementSize
  98090. });
  98091. //For future reference, needed for body transformation
  98092. shape.minY = minY;
  98093. return shape;
  98094. };
  98095. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  98096. var object = impostor.object;
  98097. //make sure it is updated...
  98098. object.computeWorldMatrix && object.computeWorldMatrix(true);
  98099. // The delta between the mesh position and the mesh bounding box center
  98100. var bInfo = object.getBoundingInfo();
  98101. if (!bInfo) {
  98102. return;
  98103. }
  98104. var center = impostor.getObjectCenter();
  98105. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  98106. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  98107. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  98108. this._tmpPosition.copyFrom(center);
  98109. var quaternion = object.rotationQuaternion;
  98110. if (!quaternion) {
  98111. return;
  98112. }
  98113. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  98114. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  98115. //-90 DEG in X, precalculated
  98116. quaternion = quaternion.multiply(this._minus90X);
  98117. //Invert! (Precalculated, 90 deg in X)
  98118. //No need to clone. this will never change.
  98119. impostor.setDeltaRotation(this._plus90X);
  98120. }
  98121. //If it is a heightfield, if should be centered.
  98122. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  98123. var mesh = object;
  98124. var boundingInfo = mesh.getBoundingInfo();
  98125. //calculate the correct body position:
  98126. var rotationQuaternion = mesh.rotationQuaternion;
  98127. mesh.rotationQuaternion = this._tmpUnityRotation;
  98128. mesh.computeWorldMatrix(true);
  98129. //get original center with no rotation
  98130. var c = center.clone();
  98131. var oldPivot = mesh.getPivotMatrix();
  98132. if (oldPivot) {
  98133. // create a copy the pivot Matrix as it is modified in place
  98134. oldPivot = oldPivot.clone();
  98135. }
  98136. else {
  98137. oldPivot = BABYLON.Matrix.Identity();
  98138. }
  98139. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  98140. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  98141. mesh.setPreTransformMatrix(p);
  98142. mesh.computeWorldMatrix(true);
  98143. //calculate the translation
  98144. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  98145. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  98146. //add it inverted to the delta
  98147. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  98148. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  98149. //rotation is back
  98150. mesh.rotationQuaternion = rotationQuaternion;
  98151. mesh.setPreTransformMatrix(oldPivot);
  98152. mesh.computeWorldMatrix(true);
  98153. }
  98154. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  98155. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  98156. //this._tmpPosition.copyFrom(object.position);
  98157. }
  98158. impostor.setDeltaPosition(this._tmpDeltaPosition);
  98159. //Now update the impostor object
  98160. impostor.physicsBody.position.copy(this._tmpPosition);
  98161. impostor.physicsBody.quaternion.copy(quaternion);
  98162. };
  98163. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  98164. impostor.object.position.copyFrom(impostor.physicsBody.position);
  98165. if (impostor.object.rotationQuaternion) {
  98166. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  98167. }
  98168. };
  98169. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  98170. impostor.physicsBody.position.copy(newPosition);
  98171. impostor.physicsBody.quaternion.copy(newRotation);
  98172. };
  98173. CannonJSPlugin.prototype.isSupported = function () {
  98174. return this.BJSCANNON !== undefined;
  98175. };
  98176. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  98177. impostor.physicsBody.velocity.copy(velocity);
  98178. };
  98179. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  98180. impostor.physicsBody.angularVelocity.copy(velocity);
  98181. };
  98182. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  98183. var v = impostor.physicsBody.velocity;
  98184. if (!v) {
  98185. return null;
  98186. }
  98187. return new BABYLON.Vector3(v.x, v.y, v.z);
  98188. };
  98189. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  98190. var v = impostor.physicsBody.angularVelocity;
  98191. if (!v) {
  98192. return null;
  98193. }
  98194. return new BABYLON.Vector3(v.x, v.y, v.z);
  98195. };
  98196. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  98197. impostor.physicsBody.mass = mass;
  98198. impostor.physicsBody.updateMassProperties();
  98199. };
  98200. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  98201. return impostor.physicsBody.mass;
  98202. };
  98203. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  98204. return impostor.physicsBody.material.friction;
  98205. };
  98206. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  98207. impostor.physicsBody.material.friction = friction;
  98208. };
  98209. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  98210. return impostor.physicsBody.material.restitution;
  98211. };
  98212. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  98213. impostor.physicsBody.material.restitution = restitution;
  98214. };
  98215. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  98216. impostor.physicsBody.sleep();
  98217. };
  98218. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  98219. impostor.physicsBody.wakeUp();
  98220. };
  98221. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  98222. joint.physicsJoint.distance = maxDistance;
  98223. };
  98224. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  98225. // if (!motorIndex) {
  98226. // joint.physicsJoint.enableMotor();
  98227. // }
  98228. // }
  98229. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  98230. // if (!motorIndex) {
  98231. // joint.physicsJoint.disableMotor();
  98232. // }
  98233. // }
  98234. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  98235. if (!motorIndex) {
  98236. joint.physicsJoint.enableMotor();
  98237. joint.physicsJoint.setMotorSpeed(speed);
  98238. if (maxForce) {
  98239. this.setLimit(joint, maxForce);
  98240. }
  98241. }
  98242. };
  98243. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  98244. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  98245. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  98246. };
  98247. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  98248. var body = impostor.physicsBody;
  98249. mesh.position.x = body.position.x;
  98250. mesh.position.y = body.position.y;
  98251. mesh.position.z = body.position.z;
  98252. if (mesh.rotationQuaternion) {
  98253. mesh.rotationQuaternion.x = body.quaternion.x;
  98254. mesh.rotationQuaternion.y = body.quaternion.y;
  98255. mesh.rotationQuaternion.z = body.quaternion.z;
  98256. mesh.rotationQuaternion.w = body.quaternion.w;
  98257. }
  98258. };
  98259. CannonJSPlugin.prototype.getRadius = function (impostor) {
  98260. var shape = impostor.physicsBody.shapes[0];
  98261. return shape.boundingSphereRadius;
  98262. };
  98263. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  98264. var shape = impostor.physicsBody.shapes[0];
  98265. result.x = shape.halfExtents.x * 2;
  98266. result.y = shape.halfExtents.y * 2;
  98267. result.z = shape.halfExtents.z * 2;
  98268. };
  98269. CannonJSPlugin.prototype.dispose = function () {
  98270. };
  98271. CannonJSPlugin.prototype._extendNamespace = function () {
  98272. //this will force cannon to execute at least one step when using interpolation
  98273. var step_tmp1 = new this.BJSCANNON.Vec3();
  98274. var Engine = this.BJSCANNON;
  98275. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  98276. maxSubSteps = maxSubSteps || 10;
  98277. timeSinceLastCalled = timeSinceLastCalled || 0;
  98278. if (timeSinceLastCalled === 0) {
  98279. this.internalStep(dt);
  98280. this.time += dt;
  98281. }
  98282. else {
  98283. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  98284. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  98285. var t0 = performance.now();
  98286. for (var i = 0; i !== internalSteps; i++) {
  98287. this.internalStep(dt);
  98288. if (performance.now() - t0 > dt * 1000) {
  98289. break;
  98290. }
  98291. }
  98292. this.time += timeSinceLastCalled;
  98293. var h = this.time % dt;
  98294. var h_div_dt = h / dt;
  98295. var interpvelo = step_tmp1;
  98296. var bodies = this.bodies;
  98297. for (var j = 0; j !== bodies.length; j++) {
  98298. var b = bodies[j];
  98299. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  98300. b.position.vsub(b.previousPosition, interpvelo);
  98301. interpvelo.scale(h_div_dt, interpvelo);
  98302. b.position.vadd(interpvelo, b.interpolatedPosition);
  98303. }
  98304. else {
  98305. b.interpolatedPosition.copy(b.position);
  98306. b.interpolatedQuaternion.copy(b.quaternion);
  98307. }
  98308. }
  98309. }
  98310. };
  98311. };
  98312. return CannonJSPlugin;
  98313. }());
  98314. BABYLON.CannonJSPlugin = CannonJSPlugin;
  98315. })(BABYLON || (BABYLON = {}));
  98316. //# sourceMappingURL=cannonJSPlugin.js.map
  98317. var BABYLON;
  98318. (function (BABYLON) {
  98319. /** @hidden */
  98320. var OimoJSPlugin = /** @class */ (function () {
  98321. function OimoJSPlugin(iterations) {
  98322. this.name = "OimoJSPlugin";
  98323. this._tmpImpostorsArray = [];
  98324. this._tmpPositionVector = BABYLON.Vector3.Zero();
  98325. this.BJSOIMO = OIMO;
  98326. this.world = new this.BJSOIMO.World({
  98327. iterations: iterations
  98328. });
  98329. this.world.clear();
  98330. }
  98331. OimoJSPlugin.prototype.setGravity = function (gravity) {
  98332. this.world.gravity.copy(gravity);
  98333. };
  98334. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  98335. this.world.timeStep = timeStep;
  98336. };
  98337. OimoJSPlugin.prototype.getTimeStep = function () {
  98338. return this.world.timeStep;
  98339. };
  98340. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  98341. var _this = this;
  98342. impostors.forEach(function (impostor) {
  98343. impostor.beforeStep();
  98344. });
  98345. this.world.step();
  98346. impostors.forEach(function (impostor) {
  98347. impostor.afterStep();
  98348. //update the ordered impostors array
  98349. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  98350. });
  98351. //check for collisions
  98352. var contact = this.world.contacts;
  98353. while (contact !== null) {
  98354. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  98355. contact = contact.next;
  98356. continue;
  98357. }
  98358. //is this body colliding with any other? get the impostor
  98359. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  98360. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  98361. if (!mainImpostor || !collidingImpostor) {
  98362. contact = contact.next;
  98363. continue;
  98364. }
  98365. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  98366. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  98367. contact = contact.next;
  98368. }
  98369. };
  98370. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  98371. var mass = impostor.physicsBody.mass;
  98372. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  98373. };
  98374. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  98375. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  98376. this.applyImpulse(impostor, force, contactPoint);
  98377. };
  98378. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  98379. var _this = this;
  98380. //parent-child relationship. Does this impostor has a parent impostor?
  98381. if (impostor.parent) {
  98382. if (impostor.physicsBody) {
  98383. this.removePhysicsBody(impostor);
  98384. //TODO is that needed?
  98385. impostor.forceUpdate();
  98386. }
  98387. return;
  98388. }
  98389. if (impostor.isBodyInitRequired()) {
  98390. var bodyConfig = {
  98391. name: impostor.uniqueId,
  98392. //Oimo must have mass, also for static objects.
  98393. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  98394. size: [],
  98395. type: [],
  98396. pos: [],
  98397. posShape: [],
  98398. rot: [],
  98399. rotShape: [],
  98400. move: impostor.getParam("mass") !== 0,
  98401. density: impostor.getParam("mass"),
  98402. friction: impostor.getParam("friction"),
  98403. restitution: impostor.getParam("restitution"),
  98404. //Supporting older versions of Oimo
  98405. world: this.world
  98406. };
  98407. var impostors = [impostor];
  98408. var addToArray = function (parent) {
  98409. if (!parent.getChildMeshes) {
  98410. return;
  98411. }
  98412. parent.getChildMeshes().forEach(function (m) {
  98413. if (m.physicsImpostor) {
  98414. impostors.push(m.physicsImpostor);
  98415. //m.physicsImpostor._init();
  98416. }
  98417. });
  98418. };
  98419. addToArray(impostor.object);
  98420. var checkWithEpsilon_1 = function (value) {
  98421. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  98422. };
  98423. var globalQuaternion_1 = new BABYLON.Quaternion();
  98424. impostors.forEach(function (i) {
  98425. if (!i.object.rotationQuaternion) {
  98426. return;
  98427. }
  98428. //get the correct bounding box
  98429. var oldQuaternion = i.object.rotationQuaternion;
  98430. globalQuaternion_1 = oldQuaternion.clone();
  98431. var rot = oldQuaternion.toEulerAngles();
  98432. var extendSize = i.getObjectExtendSize();
  98433. var radToDeg = 57.295779513082320876;
  98434. if (i === impostor) {
  98435. var center = impostor.getObjectCenter();
  98436. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  98437. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  98438. //Can also use Array.prototype.push.apply
  98439. bodyConfig.pos.push(center.x);
  98440. bodyConfig.pos.push(center.y);
  98441. bodyConfig.pos.push(center.z);
  98442. bodyConfig.posShape.push(0, 0, 0);
  98443. //tmp solution
  98444. bodyConfig.rot.push(0);
  98445. bodyConfig.rot.push(0);
  98446. bodyConfig.rot.push(0);
  98447. bodyConfig.rotShape.push(0, 0, 0);
  98448. }
  98449. else {
  98450. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  98451. bodyConfig.posShape.push(localPosition.x);
  98452. bodyConfig.posShape.push(localPosition.y);
  98453. bodyConfig.posShape.push(localPosition.z);
  98454. bodyConfig.pos.push(0, 0, 0);
  98455. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  98456. bodyConfig.rot.push(0);
  98457. bodyConfig.rot.push(0);
  98458. bodyConfig.rot.push(0);
  98459. bodyConfig.rotShape.push(rot.x * radToDeg);
  98460. bodyConfig.rotShape.push(rot.y * radToDeg);
  98461. bodyConfig.rotShape.push(rot.z * radToDeg);
  98462. }
  98463. // register mesh
  98464. switch (i.type) {
  98465. case BABYLON.PhysicsImpostor.ParticleImpostor:
  98466. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  98467. case BABYLON.PhysicsImpostor.SphereImpostor:
  98468. var radiusX = extendSize.x;
  98469. var radiusY = extendSize.y;
  98470. var radiusZ = extendSize.z;
  98471. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  98472. bodyConfig.type.push('sphere');
  98473. //due to the way oimo works with compounds, add 3 times
  98474. bodyConfig.size.push(size);
  98475. bodyConfig.size.push(size);
  98476. bodyConfig.size.push(size);
  98477. break;
  98478. case BABYLON.PhysicsImpostor.CylinderImpostor:
  98479. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  98480. var sizeY = checkWithEpsilon_1(extendSize.y);
  98481. bodyConfig.type.push('cylinder');
  98482. bodyConfig.size.push(sizeX);
  98483. bodyConfig.size.push(sizeY);
  98484. //due to the way oimo works with compounds, add one more value.
  98485. bodyConfig.size.push(sizeY);
  98486. break;
  98487. case BABYLON.PhysicsImpostor.PlaneImpostor:
  98488. case BABYLON.PhysicsImpostor.BoxImpostor:
  98489. default:
  98490. var sizeX = checkWithEpsilon_1(extendSize.x);
  98491. var sizeY = checkWithEpsilon_1(extendSize.y);
  98492. var sizeZ = checkWithEpsilon_1(extendSize.z);
  98493. bodyConfig.type.push('box');
  98494. //if (i === impostor) {
  98495. bodyConfig.size.push(sizeX);
  98496. bodyConfig.size.push(sizeY);
  98497. bodyConfig.size.push(sizeZ);
  98498. //} else {
  98499. // bodyConfig.size.push(0,0,0);
  98500. //}
  98501. break;
  98502. }
  98503. //actually not needed, but hey...
  98504. i.object.rotationQuaternion = oldQuaternion;
  98505. });
  98506. impostor.physicsBody = this.world.add(bodyConfig);
  98507. // set the quaternion, ignoring the previously defined (euler) rotation
  98508. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  98509. // update with delta 0, so the body will reveive the new rotation.
  98510. impostor.physicsBody.updatePosition(0);
  98511. }
  98512. else {
  98513. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  98514. }
  98515. impostor.setDeltaPosition(this._tmpPositionVector);
  98516. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  98517. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  98518. };
  98519. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  98520. //impostor.physicsBody.dispose();
  98521. //Same as : (older oimo versions)
  98522. this.world.removeRigidBody(impostor.physicsBody);
  98523. };
  98524. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  98525. var mainBody = impostorJoint.mainImpostor.physicsBody;
  98526. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  98527. if (!mainBody || !connectedBody) {
  98528. return;
  98529. }
  98530. var jointData = impostorJoint.joint.jointData;
  98531. var options = jointData.nativeParams || {};
  98532. var type;
  98533. var nativeJointData = {
  98534. body1: mainBody,
  98535. body2: connectedBody,
  98536. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  98537. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  98538. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  98539. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  98540. min: options.min,
  98541. max: options.max,
  98542. collision: options.collision || jointData.collision,
  98543. spring: options.spring,
  98544. //supporting older version of Oimo
  98545. world: this.world
  98546. };
  98547. switch (impostorJoint.joint.type) {
  98548. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  98549. type = "jointBall";
  98550. break;
  98551. case BABYLON.PhysicsJoint.SpringJoint:
  98552. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  98553. var springData = jointData;
  98554. nativeJointData.min = springData.length || nativeJointData.min;
  98555. //Max should also be set, just make sure it is at least min
  98556. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  98557. case BABYLON.PhysicsJoint.DistanceJoint:
  98558. type = "jointDistance";
  98559. nativeJointData.max = jointData.maxDistance;
  98560. break;
  98561. case BABYLON.PhysicsJoint.PrismaticJoint:
  98562. type = "jointPrisme";
  98563. break;
  98564. case BABYLON.PhysicsJoint.SliderJoint:
  98565. type = "jointSlide";
  98566. break;
  98567. case BABYLON.PhysicsJoint.WheelJoint:
  98568. type = "jointWheel";
  98569. break;
  98570. case BABYLON.PhysicsJoint.HingeJoint:
  98571. default:
  98572. type = "jointHinge";
  98573. break;
  98574. }
  98575. nativeJointData.type = type;
  98576. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  98577. };
  98578. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  98579. //Bug in Oimo prevents us from disposing a joint in the playground
  98580. //joint.joint.physicsJoint.dispose();
  98581. //So we will bruteforce it!
  98582. try {
  98583. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  98584. }
  98585. catch (e) {
  98586. BABYLON.Tools.Warn(e);
  98587. }
  98588. };
  98589. OimoJSPlugin.prototype.isSupported = function () {
  98590. return this.BJSOIMO !== undefined;
  98591. };
  98592. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  98593. if (!impostor.physicsBody.sleeping) {
  98594. //TODO check that
  98595. /*if (impostor.physicsBody.shapes.next) {
  98596. var parentShape = this._getLastShape(impostor.physicsBody);
  98597. impostor.object.position.copyFrom(parentShape.position);
  98598. console.log(parentShape.position);
  98599. } else {*/
  98600. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  98601. //}
  98602. if (impostor.object.rotationQuaternion) {
  98603. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  98604. }
  98605. }
  98606. };
  98607. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  98608. var body = impostor.physicsBody;
  98609. body.position.copy(newPosition);
  98610. body.orientation.copy(newRotation);
  98611. body.syncShapes();
  98612. body.awake();
  98613. };
  98614. /*private _getLastShape(body: any): any {
  98615. var lastShape = body.shapes;
  98616. while (lastShape.next) {
  98617. lastShape = lastShape.next;
  98618. }
  98619. return lastShape;
  98620. }*/
  98621. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  98622. impostor.physicsBody.linearVelocity.copy(velocity);
  98623. };
  98624. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  98625. impostor.physicsBody.angularVelocity.copy(velocity);
  98626. };
  98627. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  98628. var v = impostor.physicsBody.linearVelocity;
  98629. if (!v) {
  98630. return null;
  98631. }
  98632. return new BABYLON.Vector3(v.x, v.y, v.z);
  98633. };
  98634. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  98635. var v = impostor.physicsBody.angularVelocity;
  98636. if (!v) {
  98637. return null;
  98638. }
  98639. return new BABYLON.Vector3(v.x, v.y, v.z);
  98640. };
  98641. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  98642. var staticBody = mass === 0;
  98643. //this will actually set the body's density and not its mass.
  98644. //But this is how oimo treats the mass variable.
  98645. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  98646. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  98647. };
  98648. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  98649. return impostor.physicsBody.shapes.density;
  98650. };
  98651. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  98652. return impostor.physicsBody.shapes.friction;
  98653. };
  98654. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  98655. impostor.physicsBody.shapes.friction = friction;
  98656. };
  98657. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  98658. return impostor.physicsBody.shapes.restitution;
  98659. };
  98660. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  98661. impostor.physicsBody.shapes.restitution = restitution;
  98662. };
  98663. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  98664. impostor.physicsBody.sleep();
  98665. };
  98666. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  98667. impostor.physicsBody.awake();
  98668. };
  98669. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  98670. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  98671. if (minDistance !== void 0) {
  98672. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  98673. }
  98674. };
  98675. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  98676. //TODO separate rotational and transational motors.
  98677. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  98678. if (motor) {
  98679. motor.setMotor(speed, maxForce);
  98680. }
  98681. };
  98682. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  98683. //TODO separate rotational and transational motors.
  98684. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  98685. if (motor) {
  98686. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  98687. }
  98688. };
  98689. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  98690. var body = impostor.physicsBody;
  98691. mesh.position.x = body.position.x;
  98692. mesh.position.y = body.position.y;
  98693. mesh.position.z = body.position.z;
  98694. if (mesh.rotationQuaternion) {
  98695. mesh.rotationQuaternion.x = body.orientation.x;
  98696. mesh.rotationQuaternion.y = body.orientation.y;
  98697. mesh.rotationQuaternion.z = body.orientation.z;
  98698. mesh.rotationQuaternion.w = body.orientation.s;
  98699. }
  98700. };
  98701. OimoJSPlugin.prototype.getRadius = function (impostor) {
  98702. return impostor.physicsBody.shapes.radius;
  98703. };
  98704. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  98705. var shape = impostor.physicsBody.shapes;
  98706. result.x = shape.halfWidth * 2;
  98707. result.y = shape.halfHeight * 2;
  98708. result.z = shape.halfDepth * 2;
  98709. };
  98710. OimoJSPlugin.prototype.dispose = function () {
  98711. this.world.clear();
  98712. };
  98713. return OimoJSPlugin;
  98714. }());
  98715. BABYLON.OimoJSPlugin = OimoJSPlugin;
  98716. })(BABYLON || (BABYLON = {}));
  98717. //# sourceMappingURL=oimoJSPlugin.js.map
  98718. var BABYLON;
  98719. (function (BABYLON) {
  98720. /**
  98721. * Gets the current physics engine
  98722. * @returns a IPhysicsEngine or null if none attached
  98723. */
  98724. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  98725. return this._physicsEngine;
  98726. };
  98727. /**
  98728. * Enables physics to the current scene
  98729. * @param gravity defines the scene's gravity for the physics engine
  98730. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  98731. * @return a boolean indicating if the physics engine was initialized
  98732. */
  98733. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  98734. if (gravity === void 0) { gravity = null; }
  98735. if (this._physicsEngine) {
  98736. return true;
  98737. }
  98738. // Register the component to the scene
  98739. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  98740. if (!component) {
  98741. component = new PhysicsEngineSceneComponent(this);
  98742. this._addComponent(component);
  98743. }
  98744. try {
  98745. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  98746. return true;
  98747. }
  98748. catch (e) {
  98749. BABYLON.Tools.Error(e.message);
  98750. return false;
  98751. }
  98752. };
  98753. /**
  98754. * Disables and disposes the physics engine associated with the scene
  98755. */
  98756. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  98757. if (!this._physicsEngine) {
  98758. return;
  98759. }
  98760. this._physicsEngine.dispose();
  98761. this._physicsEngine = null;
  98762. };
  98763. /**
  98764. * Gets a boolean indicating if there is an active physics engine
  98765. * @returns a boolean indicating if there is an active physics engine
  98766. */
  98767. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  98768. return this._physicsEngine !== undefined;
  98769. };
  98770. /**
  98771. * Deletes a physics compound impostor
  98772. * @param compound defines the compound to delete
  98773. */
  98774. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  98775. var mesh = compound.parts[0].mesh;
  98776. if (mesh.physicsImpostor) {
  98777. mesh.physicsImpostor.dispose( /*true*/);
  98778. mesh.physicsImpostor = null;
  98779. }
  98780. };
  98781. /** @hidden */
  98782. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  98783. if (this._physicsEngine) {
  98784. this.onBeforePhysicsObservable.notifyObservers(this);
  98785. this._physicsEngine._step(step / 1000);
  98786. this.onAfterPhysicsObservable.notifyObservers(this);
  98787. }
  98788. };
  98789. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  98790. get: function () {
  98791. return this._physicsImpostor;
  98792. },
  98793. set: function (value) {
  98794. var _this = this;
  98795. if (this._physicsImpostor === value) {
  98796. return;
  98797. }
  98798. if (this._disposePhysicsObserver) {
  98799. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  98800. }
  98801. this._physicsImpostor = value;
  98802. if (value) {
  98803. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  98804. // Physics
  98805. if (_this.physicsImpostor) {
  98806. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  98807. _this.physicsImpostor = null;
  98808. }
  98809. });
  98810. }
  98811. },
  98812. enumerable: true,
  98813. configurable: true
  98814. });
  98815. /**
  98816. * Gets the current physics impostor
  98817. * @see http://doc.babylonjs.com/features/physics_engine
  98818. * @returns a physics impostor or null
  98819. */
  98820. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  98821. return this.physicsImpostor;
  98822. };
  98823. /**
  98824. * Apply a physic impulse to the mesh
  98825. * @param force defines the force to apply
  98826. * @param contactPoint defines where to apply the force
  98827. * @returns the current mesh
  98828. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  98829. */
  98830. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  98831. if (!this.physicsImpostor) {
  98832. return this;
  98833. }
  98834. this.physicsImpostor.applyImpulse(force, contactPoint);
  98835. return this;
  98836. };
  98837. /**
  98838. * Creates a physic joint between two meshes
  98839. * @param otherMesh defines the other mesh to use
  98840. * @param pivot1 defines the pivot to use on this mesh
  98841. * @param pivot2 defines the pivot to use on the other mesh
  98842. * @param options defines additional options (can be plugin dependent)
  98843. * @returns the current mesh
  98844. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  98845. */
  98846. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  98847. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  98848. return this;
  98849. }
  98850. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  98851. mainPivot: pivot1,
  98852. connectedPivot: pivot2,
  98853. nativeParams: options
  98854. });
  98855. return this;
  98856. };
  98857. /**
  98858. * Defines the physics engine scene component responsible to manage a physics engine
  98859. */
  98860. var PhysicsEngineSceneComponent = /** @class */ (function () {
  98861. /**
  98862. * Creates a new instance of the component for the given scene
  98863. * @param scene Defines the scene to register the component in
  98864. */
  98865. function PhysicsEngineSceneComponent(scene) {
  98866. var _this = this;
  98867. /**
  98868. * The component name helpful to identify the component in the list of scene components.
  98869. */
  98870. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  98871. this.scene = scene;
  98872. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  98873. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  98874. // Replace the function used to get the deterministic frame time
  98875. this.scene.getDeterministicFrameTime = function () {
  98876. if (_this.scene._physicsEngine) {
  98877. return _this.scene._physicsEngine.getTimeStep() * 1000;
  98878. }
  98879. return 1000.0 / 60.0;
  98880. };
  98881. }
  98882. /**
  98883. * Registers the component in a given scene
  98884. */
  98885. PhysicsEngineSceneComponent.prototype.register = function () {
  98886. };
  98887. /**
  98888. * Rebuilds the elements related to this component in case of
  98889. * context lost for instance.
  98890. */
  98891. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  98892. // Nothing to do for this component
  98893. };
  98894. /**
  98895. * Disposes the component and the associated ressources
  98896. */
  98897. PhysicsEngineSceneComponent.prototype.dispose = function () {
  98898. this.scene.onBeforePhysicsObservable.clear();
  98899. this.scene.onAfterPhysicsObservable.clear();
  98900. if (this.scene._physicsEngine) {
  98901. this.scene.disablePhysicsEngine();
  98902. }
  98903. };
  98904. return PhysicsEngineSceneComponent;
  98905. }());
  98906. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  98907. })(BABYLON || (BABYLON = {}));
  98908. //# sourceMappingURL=physicsEngineComponent.js.map
  98909. var BABYLON;
  98910. (function (BABYLON) {
  98911. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  98912. // All values and structures referenced from:
  98913. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  98914. var DDS_MAGIC = 0x20534444;
  98915. var
  98916. //DDSD_CAPS = 0x1,
  98917. //DDSD_HEIGHT = 0x2,
  98918. //DDSD_WIDTH = 0x4,
  98919. //DDSD_PITCH = 0x8,
  98920. //DDSD_PIXELFORMAT = 0x1000,
  98921. DDSD_MIPMAPCOUNT = 0x20000;
  98922. //DDSD_LINEARSIZE = 0x80000,
  98923. //DDSD_DEPTH = 0x800000;
  98924. // var DDSCAPS_COMPLEX = 0x8,
  98925. // DDSCAPS_MIPMAP = 0x400000,
  98926. // DDSCAPS_TEXTURE = 0x1000;
  98927. var DDSCAPS2_CUBEMAP = 0x200;
  98928. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  98929. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  98930. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  98931. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  98932. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  98933. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  98934. // DDSCAPS2_VOLUME = 0x200000;
  98935. var
  98936. //DDPF_ALPHAPIXELS = 0x1,
  98937. //DDPF_ALPHA = 0x2,
  98938. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  98939. //DDPF_YUV = 0x200,
  98940. DDPF_LUMINANCE = 0x20000;
  98941. function FourCCToInt32(value) {
  98942. return value.charCodeAt(0) +
  98943. (value.charCodeAt(1) << 8) +
  98944. (value.charCodeAt(2) << 16) +
  98945. (value.charCodeAt(3) << 24);
  98946. }
  98947. function Int32ToFourCC(value) {
  98948. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  98949. }
  98950. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  98951. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  98952. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  98953. var FOURCC_DX10 = FourCCToInt32("DX10");
  98954. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  98955. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  98956. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  98957. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  98958. var headerLengthInt = 31; // The header length in 32 bit ints
  98959. // Offsets into the header array
  98960. var off_magic = 0;
  98961. var off_size = 1;
  98962. var off_flags = 2;
  98963. var off_height = 3;
  98964. var off_width = 4;
  98965. var off_mipmapCount = 7;
  98966. var off_pfFlags = 20;
  98967. var off_pfFourCC = 21;
  98968. var off_RGBbpp = 22;
  98969. var off_RMask = 23;
  98970. var off_GMask = 24;
  98971. var off_BMask = 25;
  98972. var off_AMask = 26;
  98973. // var off_caps1 = 27;
  98974. var off_caps2 = 28;
  98975. // var off_caps3 = 29;
  98976. // var off_caps4 = 30;
  98977. var off_dxgiFormat = 32;
  98978. /**
  98979. * Class used to provide DDS decompression tools
  98980. */
  98981. var DDSTools = /** @class */ (function () {
  98982. function DDSTools() {
  98983. }
  98984. /**
  98985. * Gets DDS information from an array buffer
  98986. * @param arrayBuffer defines the array buffer to read data from
  98987. * @returns the DDS information
  98988. */
  98989. DDSTools.GetDDSInfo = function (arrayBuffer) {
  98990. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  98991. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  98992. var mipmapCount = 1;
  98993. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  98994. mipmapCount = Math.max(1, header[off_mipmapCount]);
  98995. }
  98996. var fourCC = header[off_pfFourCC];
  98997. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  98998. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98999. switch (fourCC) {
  99000. case FOURCC_D3DFMT_R16G16B16A16F:
  99001. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  99002. break;
  99003. case FOURCC_D3DFMT_R32G32B32A32F:
  99004. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  99005. break;
  99006. case FOURCC_DX10:
  99007. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  99008. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  99009. break;
  99010. }
  99011. }
  99012. return {
  99013. width: header[off_width],
  99014. height: header[off_height],
  99015. mipmapCount: mipmapCount,
  99016. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  99017. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  99018. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  99019. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  99020. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  99021. dxgiFormat: dxgiFormat,
  99022. textureType: textureType
  99023. };
  99024. };
  99025. DDSTools._ToHalfFloat = function (value) {
  99026. if (!DDSTools._FloatView) {
  99027. DDSTools._FloatView = new Float32Array(1);
  99028. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  99029. }
  99030. DDSTools._FloatView[0] = value;
  99031. var x = DDSTools._Int32View[0];
  99032. var bits = (x >> 16) & 0x8000; /* Get the sign */
  99033. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  99034. var e = (x >> 23) & 0xff; /* Using int is faster here */
  99035. /* If zero, or denormal, or exponent underflows too much for a denormal
  99036. * half, return signed zero. */
  99037. if (e < 103) {
  99038. return bits;
  99039. }
  99040. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  99041. if (e > 142) {
  99042. bits |= 0x7c00;
  99043. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  99044. * not Inf, so make sure we set one mantissa bit too. */
  99045. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  99046. return bits;
  99047. }
  99048. /* If exponent underflows but not too much, return a denormal */
  99049. if (e < 113) {
  99050. m |= 0x0800;
  99051. /* Extra rounding may overflow and set mantissa to 0 and exponent
  99052. * to 1, which is OK. */
  99053. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  99054. return bits;
  99055. }
  99056. bits |= ((e - 112) << 10) | (m >> 1);
  99057. bits += m & 1;
  99058. return bits;
  99059. };
  99060. DDSTools._FromHalfFloat = function (value) {
  99061. var s = (value & 0x8000) >> 15;
  99062. var e = (value & 0x7C00) >> 10;
  99063. var f = value & 0x03FF;
  99064. if (e === 0) {
  99065. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  99066. }
  99067. else if (e == 0x1F) {
  99068. return f ? NaN : ((s ? -1 : 1) * Infinity);
  99069. }
  99070. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  99071. };
  99072. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  99073. var destArray = new Float32Array(dataLength);
  99074. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  99075. var index = 0;
  99076. for (var y = 0; y < height; y++) {
  99077. for (var x = 0; x < width; x++) {
  99078. var srcPos = (x + y * width) * 4;
  99079. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  99080. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  99081. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  99082. if (DDSTools.StoreLODInAlphaChannel) {
  99083. destArray[index + 3] = lod;
  99084. }
  99085. else {
  99086. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  99087. }
  99088. index += 4;
  99089. }
  99090. }
  99091. return destArray;
  99092. };
  99093. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  99094. if (DDSTools.StoreLODInAlphaChannel) {
  99095. var destArray = new Uint16Array(dataLength);
  99096. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  99097. var index = 0;
  99098. for (var y = 0; y < height; y++) {
  99099. for (var x = 0; x < width; x++) {
  99100. var srcPos = (x + y * width) * 4;
  99101. destArray[index] = srcData[srcPos];
  99102. destArray[index + 1] = srcData[srcPos + 1];
  99103. destArray[index + 2] = srcData[srcPos + 2];
  99104. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  99105. index += 4;
  99106. }
  99107. }
  99108. return destArray;
  99109. }
  99110. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  99111. };
  99112. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  99113. if (DDSTools.StoreLODInAlphaChannel) {
  99114. var destArray = new Float32Array(dataLength);
  99115. var srcData = new Float32Array(arrayBuffer, dataOffset);
  99116. var index = 0;
  99117. for (var y = 0; y < height; y++) {
  99118. for (var x = 0; x < width; x++) {
  99119. var srcPos = (x + y * width) * 4;
  99120. destArray[index] = srcData[srcPos];
  99121. destArray[index + 1] = srcData[srcPos + 1];
  99122. destArray[index + 2] = srcData[srcPos + 2];
  99123. destArray[index + 3] = lod;
  99124. index += 4;
  99125. }
  99126. }
  99127. return destArray;
  99128. }
  99129. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  99130. };
  99131. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  99132. var destArray = new Uint8Array(dataLength);
  99133. var srcData = new Float32Array(arrayBuffer, dataOffset);
  99134. var index = 0;
  99135. for (var y = 0; y < height; y++) {
  99136. for (var x = 0; x < width; x++) {
  99137. var srcPos = (x + y * width) * 4;
  99138. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  99139. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  99140. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  99141. if (DDSTools.StoreLODInAlphaChannel) {
  99142. destArray[index + 3] = lod;
  99143. }
  99144. else {
  99145. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  99146. }
  99147. index += 4;
  99148. }
  99149. }
  99150. return destArray;
  99151. };
  99152. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  99153. var destArray = new Uint8Array(dataLength);
  99154. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  99155. var index = 0;
  99156. for (var y = 0; y < height; y++) {
  99157. for (var x = 0; x < width; x++) {
  99158. var srcPos = (x + y * width) * 4;
  99159. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  99160. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  99161. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  99162. if (DDSTools.StoreLODInAlphaChannel) {
  99163. destArray[index + 3] = lod;
  99164. }
  99165. else {
  99166. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  99167. }
  99168. index += 4;
  99169. }
  99170. }
  99171. return destArray;
  99172. };
  99173. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  99174. var byteArray = new Uint8Array(dataLength);
  99175. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  99176. var index = 0;
  99177. for (var y = 0; y < height; y++) {
  99178. for (var x = 0; x < width; x++) {
  99179. var srcPos = (x + y * width) * 4;
  99180. byteArray[index] = srcData[srcPos + rOffset];
  99181. byteArray[index + 1] = srcData[srcPos + gOffset];
  99182. byteArray[index + 2] = srcData[srcPos + bOffset];
  99183. byteArray[index + 3] = srcData[srcPos + aOffset];
  99184. index += 4;
  99185. }
  99186. }
  99187. return byteArray;
  99188. };
  99189. DDSTools._ExtractLongWordOrder = function (value) {
  99190. if (value === 0 || value === 255 || value === -16777216) {
  99191. return 0;
  99192. }
  99193. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  99194. };
  99195. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  99196. var byteArray = new Uint8Array(dataLength);
  99197. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  99198. var index = 0;
  99199. for (var y = 0; y < height; y++) {
  99200. for (var x = 0; x < width; x++) {
  99201. var srcPos = (x + y * width) * 3;
  99202. byteArray[index] = srcData[srcPos + rOffset];
  99203. byteArray[index + 1] = srcData[srcPos + gOffset];
  99204. byteArray[index + 2] = srcData[srcPos + bOffset];
  99205. index += 3;
  99206. }
  99207. }
  99208. return byteArray;
  99209. };
  99210. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  99211. var byteArray = new Uint8Array(dataLength);
  99212. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  99213. var index = 0;
  99214. for (var y = 0; y < height; y++) {
  99215. for (var x = 0; x < width; x++) {
  99216. var srcPos = (x + y * width);
  99217. byteArray[index] = srcData[srcPos];
  99218. index++;
  99219. }
  99220. }
  99221. return byteArray;
  99222. };
  99223. /**
  99224. * Uploads DDS Levels to a Babylon Texture
  99225. * @hidden
  99226. */
  99227. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  99228. if (lodIndex === void 0) { lodIndex = -1; }
  99229. var sphericalPolynomialFaces = null;
  99230. if (info.sphericalPolynomial) {
  99231. sphericalPolynomialFaces = new Array();
  99232. }
  99233. var ext = engine.getCaps().s3tc;
  99234. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  99235. var fourCC, width, height, dataLength = 0, dataOffset;
  99236. var byteArray, mipmapCount, mip;
  99237. var internalCompressedFormat = 0;
  99238. var blockBytes = 1;
  99239. if (header[off_magic] !== DDS_MAGIC) {
  99240. BABYLON.Tools.Error("Invalid magic number in DDS header");
  99241. return;
  99242. }
  99243. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  99244. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  99245. return;
  99246. }
  99247. if (info.isCompressed && !ext) {
  99248. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  99249. return;
  99250. }
  99251. var bpp = header[off_RGBbpp];
  99252. dataOffset = header[off_size] + 4;
  99253. var computeFormats = false;
  99254. if (info.isFourCC) {
  99255. fourCC = header[off_pfFourCC];
  99256. switch (fourCC) {
  99257. case FOURCC_DXT1:
  99258. blockBytes = 8;
  99259. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  99260. break;
  99261. case FOURCC_DXT3:
  99262. blockBytes = 16;
  99263. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  99264. break;
  99265. case FOURCC_DXT5:
  99266. blockBytes = 16;
  99267. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  99268. break;
  99269. case FOURCC_D3DFMT_R16G16B16A16F:
  99270. computeFormats = true;
  99271. break;
  99272. case FOURCC_D3DFMT_R32G32B32A32F:
  99273. computeFormats = true;
  99274. break;
  99275. case FOURCC_DX10:
  99276. // There is an additionnal header so dataOffset need to be changed
  99277. dataOffset += 5 * 4; // 5 uints
  99278. var supported = false;
  99279. switch (info.dxgiFormat) {
  99280. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  99281. computeFormats = true;
  99282. supported = true;
  99283. break;
  99284. case DXGI_FORMAT_B8G8R8X8_UNORM:
  99285. info.isRGB = true;
  99286. info.isFourCC = false;
  99287. bpp = 32;
  99288. supported = true;
  99289. break;
  99290. }
  99291. if (supported) {
  99292. break;
  99293. }
  99294. default:
  99295. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  99296. return;
  99297. }
  99298. }
  99299. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  99300. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  99301. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  99302. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  99303. if (computeFormats) {
  99304. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  99305. }
  99306. mipmapCount = 1;
  99307. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  99308. mipmapCount = Math.max(1, header[off_mipmapCount]);
  99309. }
  99310. for (var face = 0; face < faces; face++) {
  99311. width = header[off_width];
  99312. height = header[off_height];
  99313. for (mip = 0; mip < mipmapCount; ++mip) {
  99314. if (lodIndex === -1 || lodIndex === mip) {
  99315. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  99316. var i = (lodIndex === -1) ? mip : 0;
  99317. if (!info.isCompressed && info.isFourCC) {
  99318. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  99319. dataLength = width * height * 4;
  99320. var floatArray = null;
  99321. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  99322. if (bpp === 128) {
  99323. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99324. if (sphericalPolynomialFaces && i == 0) {
  99325. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  99326. }
  99327. }
  99328. else if (bpp === 64) {
  99329. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99330. if (sphericalPolynomialFaces && i == 0) {
  99331. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  99332. }
  99333. }
  99334. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99335. }
  99336. else {
  99337. if (bpp === 128) {
  99338. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  99339. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99340. if (sphericalPolynomialFaces && i == 0) {
  99341. sphericalPolynomialFaces.push(floatArray);
  99342. }
  99343. }
  99344. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  99345. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  99346. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99347. if (sphericalPolynomialFaces && i == 0) {
  99348. sphericalPolynomialFaces.push(floatArray);
  99349. }
  99350. }
  99351. else { // 64
  99352. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  99353. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  99354. if (sphericalPolynomialFaces && i == 0) {
  99355. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  99356. }
  99357. }
  99358. }
  99359. if (floatArray) {
  99360. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  99361. }
  99362. }
  99363. else if (info.isRGB) {
  99364. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99365. if (bpp === 24) {
  99366. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  99367. dataLength = width * height * 3;
  99368. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  99369. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  99370. }
  99371. else { // 32
  99372. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  99373. dataLength = width * height * 4;
  99374. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  99375. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  99376. }
  99377. }
  99378. else if (info.isLuminance) {
  99379. var unpackAlignment = engine._getUnpackAlignement();
  99380. var unpaddedRowSize = width;
  99381. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  99382. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  99383. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  99384. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  99385. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99386. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  99387. }
  99388. else {
  99389. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  99390. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  99391. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99392. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  99393. }
  99394. }
  99395. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  99396. width *= 0.5;
  99397. height *= 0.5;
  99398. width = Math.max(1.0, width);
  99399. height = Math.max(1.0, height);
  99400. }
  99401. if (currentFace !== undefined) {
  99402. // Loading a single face
  99403. break;
  99404. }
  99405. }
  99406. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  99407. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  99408. size: header[off_width],
  99409. right: sphericalPolynomialFaces[0],
  99410. left: sphericalPolynomialFaces[1],
  99411. up: sphericalPolynomialFaces[2],
  99412. down: sphericalPolynomialFaces[3],
  99413. front: sphericalPolynomialFaces[4],
  99414. back: sphericalPolynomialFaces[5],
  99415. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  99416. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  99417. gammaSpace: false,
  99418. });
  99419. }
  99420. else {
  99421. info.sphericalPolynomial = undefined;
  99422. }
  99423. };
  99424. /**
  99425. * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)
  99426. */
  99427. DDSTools.StoreLODInAlphaChannel = false;
  99428. return DDSTools;
  99429. }());
  99430. BABYLON.DDSTools = DDSTools;
  99431. })(BABYLON || (BABYLON = {}));
  99432. //# sourceMappingURL=dds.js.map
  99433. var BABYLON;
  99434. (function (BABYLON) {
  99435. /**
  99436. * Implementation of the DDS Texture Loader.
  99437. */
  99438. var DDSTextureLoader = /** @class */ (function () {
  99439. function DDSTextureLoader() {
  99440. /**
  99441. * Defines wether the loader supports cascade loading the different faces.
  99442. */
  99443. this.supportCascades = true;
  99444. }
  99445. /**
  99446. * This returns if the loader support the current file information.
  99447. * @param extension defines the file extension of the file being loaded
  99448. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99449. * @param fallback defines the fallback internal texture if any
  99450. * @param isBase64 defines whether the texture is encoded as a base64
  99451. * @param isBuffer defines whether the texture data are stored as a buffer
  99452. * @returns true if the loader can load the specified file
  99453. */
  99454. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  99455. return extension.indexOf(".dds") === 0;
  99456. };
  99457. /**
  99458. * Transform the url before loading if required.
  99459. * @param rootUrl the url of the texture
  99460. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99461. * @returns the transformed texture
  99462. */
  99463. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  99464. return rootUrl;
  99465. };
  99466. /**
  99467. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  99468. * @param rootUrl the url of the texture
  99469. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99470. * @returns the fallback texture
  99471. */
  99472. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  99473. return null;
  99474. };
  99475. /**
  99476. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  99477. * @param data contains the texture data
  99478. * @param texture defines the BabylonJS internal texture
  99479. * @param createPolynomials will be true if polynomials have been requested
  99480. * @param onLoad defines the callback to trigger once the texture is ready
  99481. * @param onError defines the callback to trigger in case of error
  99482. */
  99483. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  99484. var engine = texture.getEngine();
  99485. var info;
  99486. var loadMipmap = false;
  99487. if (Array.isArray(imgs)) {
  99488. for (var index = 0; index < imgs.length; index++) {
  99489. var data_1 = imgs[index];
  99490. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  99491. texture.width = info.width;
  99492. texture.height = info.height;
  99493. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  99494. engine._unpackFlipY(info.isCompressed);
  99495. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  99496. if (!info.isFourCC && info.mipmapCount === 1) {
  99497. engine.generateMipMapsForCubemap(texture);
  99498. }
  99499. }
  99500. }
  99501. else {
  99502. var data = imgs;
  99503. info = BABYLON.DDSTools.GetDDSInfo(data);
  99504. texture.width = info.width;
  99505. texture.height = info.height;
  99506. if (createPolynomials) {
  99507. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  99508. }
  99509. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  99510. engine._unpackFlipY(info.isCompressed);
  99511. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  99512. if (!info.isFourCC && info.mipmapCount === 1) {
  99513. engine.generateMipMapsForCubemap(texture);
  99514. }
  99515. }
  99516. engine._setCubeMapTextureParams(loadMipmap);
  99517. texture.isReady = true;
  99518. if (onLoad) {
  99519. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  99520. }
  99521. };
  99522. /**
  99523. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  99524. * @param data contains the texture data
  99525. * @param texture defines the BabylonJS internal texture
  99526. * @param callback defines the method to call once ready to upload
  99527. */
  99528. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  99529. var info = BABYLON.DDSTools.GetDDSInfo(data);
  99530. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  99531. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  99532. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  99533. });
  99534. };
  99535. return DDSTextureLoader;
  99536. }());
  99537. // Register the loader.
  99538. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  99539. })(BABYLON || (BABYLON = {}));
  99540. //# sourceMappingURL=ddsTextureLoader.js.map
  99541. var BABYLON;
  99542. (function (BABYLON) {
  99543. /**
  99544. * Based on jsTGALoader - Javascript loader for TGA file
  99545. * By Vincent Thibault
  99546. * @see http://blog.robrowser.com/javascript-tga-loader.html
  99547. */
  99548. var TGATools = /** @class */ (function () {
  99549. function TGATools() {
  99550. }
  99551. /**
  99552. * Gets the header of a TGA file
  99553. * @param data defines the TGA data
  99554. * @returns the header
  99555. */
  99556. TGATools.GetTGAHeader = function (data) {
  99557. var offset = 0;
  99558. var header = {
  99559. id_length: data[offset++],
  99560. colormap_type: data[offset++],
  99561. image_type: data[offset++],
  99562. colormap_index: data[offset++] | data[offset++] << 8,
  99563. colormap_length: data[offset++] | data[offset++] << 8,
  99564. colormap_size: data[offset++],
  99565. origin: [
  99566. data[offset++] | data[offset++] << 8,
  99567. data[offset++] | data[offset++] << 8
  99568. ],
  99569. width: data[offset++] | data[offset++] << 8,
  99570. height: data[offset++] | data[offset++] << 8,
  99571. pixel_size: data[offset++],
  99572. flags: data[offset++]
  99573. };
  99574. return header;
  99575. };
  99576. /**
  99577. * Uploads TGA content to a Babylon Texture
  99578. * @hidden
  99579. */
  99580. TGATools.UploadContent = function (texture, data) {
  99581. // Not enough data to contain header ?
  99582. if (data.length < 19) {
  99583. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  99584. return;
  99585. }
  99586. // Read Header
  99587. var offset = 18;
  99588. var header = TGATools.GetTGAHeader(data);
  99589. // Assume it's a valid Targa file.
  99590. if (header.id_length + offset > data.length) {
  99591. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  99592. return;
  99593. }
  99594. // Skip not needed data
  99595. offset += header.id_length;
  99596. var use_rle = false;
  99597. var use_pal = false;
  99598. var use_grey = false;
  99599. // Get some informations.
  99600. switch (header.image_type) {
  99601. case TGATools._TYPE_RLE_INDEXED:
  99602. use_rle = true;
  99603. case TGATools._TYPE_INDEXED:
  99604. use_pal = true;
  99605. break;
  99606. case TGATools._TYPE_RLE_RGB:
  99607. use_rle = true;
  99608. case TGATools._TYPE_RGB:
  99609. // use_rgb = true;
  99610. break;
  99611. case TGATools._TYPE_RLE_GREY:
  99612. use_rle = true;
  99613. case TGATools._TYPE_GREY:
  99614. use_grey = true;
  99615. break;
  99616. }
  99617. var pixel_data;
  99618. // var numAlphaBits = header.flags & 0xf;
  99619. var pixel_size = header.pixel_size >> 3;
  99620. var pixel_total = header.width * header.height * pixel_size;
  99621. // Read palettes
  99622. var palettes;
  99623. if (use_pal) {
  99624. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  99625. }
  99626. // Read LRE
  99627. if (use_rle) {
  99628. pixel_data = new Uint8Array(pixel_total);
  99629. var c, count, i;
  99630. var localOffset = 0;
  99631. var pixels = new Uint8Array(pixel_size);
  99632. while (offset < pixel_total && localOffset < pixel_total) {
  99633. c = data[offset++];
  99634. count = (c & 0x7f) + 1;
  99635. // RLE pixels
  99636. if (c & 0x80) {
  99637. // Bind pixel tmp array
  99638. for (i = 0; i < pixel_size; ++i) {
  99639. pixels[i] = data[offset++];
  99640. }
  99641. // Copy pixel array
  99642. for (i = 0; i < count; ++i) {
  99643. pixel_data.set(pixels, localOffset + i * pixel_size);
  99644. }
  99645. localOffset += pixel_size * count;
  99646. }
  99647. // Raw pixels
  99648. else {
  99649. count *= pixel_size;
  99650. for (i = 0; i < count; ++i) {
  99651. pixel_data[localOffset + i] = data[offset++];
  99652. }
  99653. localOffset += count;
  99654. }
  99655. }
  99656. }
  99657. // RAW Pixels
  99658. else {
  99659. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  99660. }
  99661. // Load to texture
  99662. var x_start, y_start, x_step, y_step, y_end, x_end;
  99663. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  99664. default:
  99665. case TGATools._ORIGIN_UL:
  99666. x_start = 0;
  99667. x_step = 1;
  99668. x_end = header.width;
  99669. y_start = 0;
  99670. y_step = 1;
  99671. y_end = header.height;
  99672. break;
  99673. case TGATools._ORIGIN_BL:
  99674. x_start = 0;
  99675. x_step = 1;
  99676. x_end = header.width;
  99677. y_start = header.height - 1;
  99678. y_step = -1;
  99679. y_end = -1;
  99680. break;
  99681. case TGATools._ORIGIN_UR:
  99682. x_start = header.width - 1;
  99683. x_step = -1;
  99684. x_end = -1;
  99685. y_start = 0;
  99686. y_step = 1;
  99687. y_end = header.height;
  99688. break;
  99689. case TGATools._ORIGIN_BR:
  99690. x_start = header.width - 1;
  99691. x_step = -1;
  99692. x_end = -1;
  99693. y_start = header.height - 1;
  99694. y_step = -1;
  99695. y_end = -1;
  99696. break;
  99697. }
  99698. // Load the specify method
  99699. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  99700. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  99701. var engine = texture.getEngine();
  99702. engine._uploadDataToTextureDirectly(texture, imageData);
  99703. };
  99704. /** @hidden */
  99705. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99706. var image = pixel_data, colormap = palettes;
  99707. var width = header.width, height = header.height;
  99708. var color, i = 0, x, y;
  99709. var imageData = new Uint8Array(width * height * 4);
  99710. for (y = y_start; y !== y_end; y += y_step) {
  99711. for (x = x_start; x !== x_end; x += x_step, i++) {
  99712. color = image[i];
  99713. imageData[(x + width * y) * 4 + 3] = 255;
  99714. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  99715. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  99716. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  99717. }
  99718. }
  99719. return imageData;
  99720. };
  99721. /** @hidden */
  99722. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99723. var image = pixel_data;
  99724. var width = header.width, height = header.height;
  99725. var color, i = 0, x, y;
  99726. var imageData = new Uint8Array(width * height * 4);
  99727. for (y = y_start; y !== y_end; y += y_step) {
  99728. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  99729. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  99730. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  99731. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  99732. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  99733. imageData[(x + width * y) * 4 + 0] = r;
  99734. imageData[(x + width * y) * 4 + 1] = g;
  99735. imageData[(x + width * y) * 4 + 2] = b;
  99736. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  99737. }
  99738. }
  99739. return imageData;
  99740. };
  99741. /** @hidden */
  99742. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99743. var image = pixel_data;
  99744. var width = header.width, height = header.height;
  99745. var i = 0, x, y;
  99746. var imageData = new Uint8Array(width * height * 4);
  99747. for (y = y_start; y !== y_end; y += y_step) {
  99748. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  99749. imageData[(x + width * y) * 4 + 3] = 255;
  99750. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  99751. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  99752. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  99753. }
  99754. }
  99755. return imageData;
  99756. };
  99757. /** @hidden */
  99758. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99759. var image = pixel_data;
  99760. var width = header.width, height = header.height;
  99761. var i = 0, x, y;
  99762. var imageData = new Uint8Array(width * height * 4);
  99763. for (y = y_start; y !== y_end; y += y_step) {
  99764. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  99765. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  99766. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  99767. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  99768. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  99769. }
  99770. }
  99771. return imageData;
  99772. };
  99773. /** @hidden */
  99774. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99775. var image = pixel_data;
  99776. var width = header.width, height = header.height;
  99777. var color, i = 0, x, y;
  99778. var imageData = new Uint8Array(width * height * 4);
  99779. for (y = y_start; y !== y_end; y += y_step) {
  99780. for (x = x_start; x !== x_end; x += x_step, i++) {
  99781. color = image[i];
  99782. imageData[(x + width * y) * 4 + 0] = color;
  99783. imageData[(x + width * y) * 4 + 1] = color;
  99784. imageData[(x + width * y) * 4 + 2] = color;
  99785. imageData[(x + width * y) * 4 + 3] = 255;
  99786. }
  99787. }
  99788. return imageData;
  99789. };
  99790. /** @hidden */
  99791. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  99792. var image = pixel_data;
  99793. var width = header.width, height = header.height;
  99794. var i = 0, x, y;
  99795. var imageData = new Uint8Array(width * height * 4);
  99796. for (y = y_start; y !== y_end; y += y_step) {
  99797. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  99798. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  99799. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  99800. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  99801. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  99802. }
  99803. }
  99804. return imageData;
  99805. };
  99806. //private static _TYPE_NO_DATA = 0;
  99807. TGATools._TYPE_INDEXED = 1;
  99808. TGATools._TYPE_RGB = 2;
  99809. TGATools._TYPE_GREY = 3;
  99810. TGATools._TYPE_RLE_INDEXED = 9;
  99811. TGATools._TYPE_RLE_RGB = 10;
  99812. TGATools._TYPE_RLE_GREY = 11;
  99813. TGATools._ORIGIN_MASK = 0x30;
  99814. TGATools._ORIGIN_SHIFT = 0x04;
  99815. TGATools._ORIGIN_BL = 0x00;
  99816. TGATools._ORIGIN_BR = 0x01;
  99817. TGATools._ORIGIN_UL = 0x02;
  99818. TGATools._ORIGIN_UR = 0x03;
  99819. return TGATools;
  99820. }());
  99821. BABYLON.TGATools = TGATools;
  99822. })(BABYLON || (BABYLON = {}));
  99823. //# sourceMappingURL=tga.js.map
  99824. var BABYLON;
  99825. (function (BABYLON) {
  99826. /**
  99827. * Implementation of the TGA Texture Loader.
  99828. */
  99829. var TGATextureLoader = /** @class */ (function () {
  99830. function TGATextureLoader() {
  99831. /**
  99832. * Defines wether the loader supports cascade loading the different faces.
  99833. */
  99834. this.supportCascades = false;
  99835. }
  99836. /**
  99837. * This returns if the loader support the current file information.
  99838. * @param extension defines the file extension of the file being loaded
  99839. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99840. * @param fallback defines the fallback internal texture if any
  99841. * @param isBase64 defines whether the texture is encoded as a base64
  99842. * @param isBuffer defines whether the texture data are stored as a buffer
  99843. * @returns true if the loader can load the specified file
  99844. */
  99845. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  99846. return extension.indexOf(".tga") === 0;
  99847. };
  99848. /**
  99849. * Transform the url before loading if required.
  99850. * @param rootUrl the url of the texture
  99851. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99852. * @returns the transformed texture
  99853. */
  99854. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  99855. return rootUrl;
  99856. };
  99857. /**
  99858. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  99859. * @param rootUrl the url of the texture
  99860. * @param textureFormatInUse defines the current compressed format in use iun the engine
  99861. * @returns the fallback texture
  99862. */
  99863. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  99864. return null;
  99865. };
  99866. /**
  99867. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  99868. * @param data contains the texture data
  99869. * @param texture defines the BabylonJS internal texture
  99870. * @param createPolynomials will be true if polynomials have been requested
  99871. * @param onLoad defines the callback to trigger once the texture is ready
  99872. * @param onError defines the callback to trigger in case of error
  99873. */
  99874. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  99875. throw ".env not supported in Cube.";
  99876. };
  99877. /**
  99878. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  99879. * @param data contains the texture data
  99880. * @param texture defines the BabylonJS internal texture
  99881. * @param callback defines the method to call once ready to upload
  99882. */
  99883. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  99884. var uintData = new Uint8Array(data);
  99885. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  99886. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  99887. BABYLON.TGATools.UploadContent(texture, uintData);
  99888. });
  99889. };
  99890. return TGATextureLoader;
  99891. }());
  99892. // Register the loader.
  99893. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  99894. })(BABYLON || (BABYLON = {}));
  99895. //# sourceMappingURL=tgaTextureLoader.js.map
  99896. var BABYLON;
  99897. (function (BABYLON) {
  99898. /**
  99899. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  99900. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  99901. */
  99902. var KhronosTextureContainer = /** @class */ (function () {
  99903. /**
  99904. * Creates a new KhronosTextureContainer
  99905. * @param arrayBuffer contents of the KTX container file
  99906. * @param facesExpected should be either 1 or 6, based whether a cube texture or or
  99907. * @param threeDExpected provision for indicating that data should be a 3D texture, not implemented
  99908. * @param textureArrayExpected provision for indicating that data should be a texture array, not implemented
  99909. */
  99910. function KhronosTextureContainer(
  99911. /** contents of the KTX container file */
  99912. arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  99913. this.arrayBuffer = arrayBuffer;
  99914. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  99915. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  99916. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  99917. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  99918. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  99919. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  99920. BABYLON.Tools.Error("texture missing KTX identifier");
  99921. return;
  99922. }
  99923. // load the reset of the header in native 32 bit int
  99924. var header = new Int32Array(this.arrayBuffer, 12, 13);
  99925. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  99926. var oppositeEndianess = header[0] === 0x01020304;
  99927. // read all the header elements in order they exist in the file, without modification (sans endainness)
  99928. this.glType = oppositeEndianess ? this.switchEndianness(header[1]) : header[1]; // must be 0 for compressed textures
  99929. this.glTypeSize = oppositeEndianess ? this.switchEndianness(header[2]) : header[2]; // must be 1 for compressed textures
  99930. this.glFormat = oppositeEndianess ? this.switchEndianness(header[3]) : header[3]; // must be 0 for compressed textures
  99931. this.glInternalFormat = oppositeEndianess ? this.switchEndianness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  99932. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndianness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  99933. this.pixelWidth = oppositeEndianess ? this.switchEndianness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  99934. this.pixelHeight = oppositeEndianess ? this.switchEndianness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  99935. this.pixelDepth = oppositeEndianess ? this.switchEndianness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  99936. this.numberOfArrayElements = oppositeEndianess ? this.switchEndianness(header[9]) : header[9]; // used for texture arrays
  99937. this.numberOfFaces = oppositeEndianess ? this.switchEndianness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  99938. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndianness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  99939. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndianness(header[12]) : header[12]; // the amount of space after the header for meta-data
  99940. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  99941. if (this.glType !== 0) {
  99942. BABYLON.Tools.Error("only compressed formats currently supported");
  99943. return;
  99944. }
  99945. else {
  99946. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  99947. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  99948. }
  99949. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  99950. BABYLON.Tools.Error("only 2D textures currently supported");
  99951. return;
  99952. }
  99953. if (this.numberOfArrayElements !== 0) {
  99954. BABYLON.Tools.Error("texture arrays not currently supported");
  99955. return;
  99956. }
  99957. if (this.numberOfFaces !== facesExpected) {
  99958. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  99959. return;
  99960. }
  99961. // we now have a completely validated file, so could use existence of loadType as success
  99962. // would need to make this more elaborate & adjust checks above to support more than one load type
  99963. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  99964. }
  99965. //
  99966. /**
  99967. * Revert the endianness of a value.
  99968. * Not as fast hardware based, but will probably never need to use
  99969. * @param val defines the value to convert
  99970. * @returns the new value
  99971. */
  99972. KhronosTextureContainer.prototype.switchEndianness = function (val) {
  99973. return ((val & 0xFF) << 24)
  99974. | ((val & 0xFF00) << 8)
  99975. | ((val >> 8) & 0xFF00)
  99976. | ((val >> 24) & 0xFF);
  99977. };
  99978. /**
  99979. * Uploads KTX content to a Babylon Texture.
  99980. * It is assumed that the texture has already been created & is currently bound
  99981. * @hidden
  99982. */
  99983. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  99984. switch (this.loadType) {
  99985. case KhronosTextureContainer.COMPRESSED_2D:
  99986. this._upload2DCompressedLevels(texture, loadMipmaps);
  99987. break;
  99988. case KhronosTextureContainer.TEX_2D:
  99989. case KhronosTextureContainer.COMPRESSED_3D:
  99990. case KhronosTextureContainer.TEX_3D:
  99991. }
  99992. };
  99993. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  99994. // initialize width & height for level 1
  99995. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  99996. var width = this.pixelWidth;
  99997. var height = this.pixelHeight;
  99998. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  99999. for (var level = 0; level < mipmapCount; level++) {
  100000. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  100001. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  100002. for (var face = 0; face < this.numberOfFaces; face++) {
  100003. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  100004. var engine = texture.getEngine();
  100005. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  100006. dataOffset += imageSize; // add size of the image for the next face/mipmap
  100007. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  100008. }
  100009. width = Math.max(1.0, width * 0.5);
  100010. height = Math.max(1.0, height * 0.5);
  100011. }
  100012. };
  100013. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  100014. // load types
  100015. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  100016. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  100017. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  100018. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  100019. return KhronosTextureContainer;
  100020. }());
  100021. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  100022. })(BABYLON || (BABYLON = {}));
  100023. //# sourceMappingURL=khronosTextureContainer.js.map
  100024. var BABYLON;
  100025. (function (BABYLON) {
  100026. /**
  100027. * Implementation of the KTX Texture Loader.
  100028. */
  100029. var KTXTextureLoader = /** @class */ (function () {
  100030. function KTXTextureLoader() {
  100031. /**
  100032. * Defines wether the loader supports cascade loading the different faces.
  100033. */
  100034. this.supportCascades = false;
  100035. }
  100036. /**
  100037. * This returns if the loader support the current file information.
  100038. * @param extension defines the file extension of the file being loaded
  100039. * @param textureFormatInUse defines the current compressed format in use iun the engine
  100040. * @param fallback defines the fallback internal texture if any
  100041. * @param isBase64 defines whether the texture is encoded as a base64
  100042. * @param isBuffer defines whether the texture data are stored as a buffer
  100043. * @returns true if the loader can load the specified file
  100044. */
  100045. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  100046. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  100047. return true;
  100048. }
  100049. return false;
  100050. };
  100051. /**
  100052. * Transform the url before loading if required.
  100053. * @param rootUrl the url of the texture
  100054. * @param textureFormatInUse defines the current compressed format in use iun the engine
  100055. * @returns the transformed texture
  100056. */
  100057. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  100058. var lastDot = rootUrl.lastIndexOf('.');
  100059. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  100060. };
  100061. /**
  100062. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  100063. * @param rootUrl the url of the texture
  100064. * @param textureFormatInUse defines the current compressed format in use iun the engine
  100065. * @returns the fallback texture
  100066. */
  100067. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  100068. // remove the format appended to the rootUrl in the original createCubeTexture call.
  100069. var exp = new RegExp("" + textureFormatInUse + "$");
  100070. return rootUrl.replace(exp, "");
  100071. };
  100072. /**
  100073. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  100074. * @param data contains the texture data
  100075. * @param texture defines the BabylonJS internal texture
  100076. * @param createPolynomials will be true if polynomials have been requested
  100077. * @param onLoad defines the callback to trigger once the texture is ready
  100078. * @param onError defines the callback to trigger in case of error
  100079. */
  100080. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  100081. if (Array.isArray(data)) {
  100082. return;
  100083. }
  100084. var engine = texture.getEngine();
  100085. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  100086. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  100087. engine._unpackFlipY(true);
  100088. ktx.uploadLevels(texture, texture.generateMipMaps);
  100089. texture.width = ktx.pixelWidth;
  100090. texture.height = ktx.pixelHeight;
  100091. engine._setCubeMapTextureParams(loadMipmap);
  100092. texture.isReady = true;
  100093. };
  100094. /**
  100095. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  100096. * @param data contains the texture data
  100097. * @param texture defines the BabylonJS internal texture
  100098. * @param callback defines the method to call once ready to upload
  100099. */
  100100. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  100101. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  100102. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  100103. ktx.uploadLevels(texture, texture.generateMipMaps);
  100104. });
  100105. };
  100106. return KTXTextureLoader;
  100107. }());
  100108. // Register the loader.
  100109. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  100110. })(BABYLON || (BABYLON = {}));
  100111. //# sourceMappingURL=ktxTextureLoader.js.map
  100112. var BABYLON;
  100113. (function (BABYLON) {
  100114. /**
  100115. * Sets of helpers addressing the serialization and deserialization of environment texture
  100116. * stored in a BabylonJS env file.
  100117. * Those files are usually stored as .env files.
  100118. */
  100119. var EnvironmentTextureTools = /** @class */ (function () {
  100120. function EnvironmentTextureTools() {
  100121. }
  100122. /**
  100123. * Gets the environment info from an env file.
  100124. * @param data The array buffer containing the .env bytes.
  100125. * @returns the environment file info (the json header) if successfully parsed.
  100126. */
  100127. EnvironmentTextureTools.GetEnvInfo = function (data) {
  100128. var dataView = new DataView(data);
  100129. var pos = 0;
  100130. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  100131. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  100132. BABYLON.Tools.Error('Not a babylon environment map');
  100133. return null;
  100134. }
  100135. }
  100136. // Read json manifest - collect characters up to null terminator
  100137. var manifestString = '';
  100138. var charCode = 0x00;
  100139. while ((charCode = dataView.getUint8(pos++))) {
  100140. manifestString += String.fromCharCode(charCode);
  100141. }
  100142. var manifest = JSON.parse(manifestString);
  100143. if (manifest.specular) {
  100144. // Extend the header with the position of the payload.
  100145. manifest.specular.specularDataPosition = pos;
  100146. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  100147. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  100148. }
  100149. return manifest;
  100150. };
  100151. /**
  100152. * Creates an environment texture from a loaded cube texture.
  100153. * @param texture defines the cube texture to convert in env file
  100154. * @return a promise containing the environment data if succesfull.
  100155. */
  100156. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  100157. var _this = this;
  100158. var internalTexture = texture.getInternalTexture();
  100159. if (!internalTexture) {
  100160. return Promise.reject("The cube texture is invalid.");
  100161. }
  100162. if (!texture._prefiltered) {
  100163. return Promise.reject("The cube texture is invalid (not prefiltered).");
  100164. }
  100165. var engine = internalTexture.getEngine();
  100166. if (engine && engine.premultipliedAlpha) {
  100167. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  100168. }
  100169. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  100170. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  100171. }
  100172. var canvas = engine.getRenderingCanvas();
  100173. if (!canvas) {
  100174. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  100175. }
  100176. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  100177. if (!engine.getCaps().textureFloatRender) {
  100178. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  100179. if (!engine.getCaps().textureHalfFloatRender) {
  100180. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  100181. }
  100182. }
  100183. var cubeWidth = internalTexture.width;
  100184. var hostingScene = new BABYLON.Scene(engine);
  100185. var specularTextures = {};
  100186. var promises = [];
  100187. // Read and collect all mipmaps data from the cube.
  100188. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  100189. mipmapsCount = Math.round(mipmapsCount);
  100190. var _loop_1 = function (i) {
  100191. var faceWidth = Math.pow(2, mipmapsCount - i);
  100192. var _loop_2 = function (face) {
  100193. var data = texture.readPixels(face, i);
  100194. // Creates a temp texture with the face data.
  100195. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  100196. // And rgbdEncode them.
  100197. var promise = new Promise(function (resolve, reject) {
  100198. 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);
  100199. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  100200. rgbdPostProcess.onApply = function (effect) {
  100201. effect._bindTexture("textureSampler", tempTexture);
  100202. };
  100203. // As the process needs to happen on the main canvas, keep track of the current size
  100204. var currentW = engine.getRenderWidth();
  100205. var currentH = engine.getRenderHeight();
  100206. // Set the desired size for the texture
  100207. engine.setSize(faceWidth, faceWidth);
  100208. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  100209. // Reading datas from WebGL
  100210. BABYLON.Tools.ToBlob(canvas, function (blob) {
  100211. var fileReader = new FileReader();
  100212. fileReader.onload = function (event) {
  100213. var arrayBuffer = event.target.result;
  100214. specularTextures[i * 6 + face] = arrayBuffer;
  100215. resolve();
  100216. };
  100217. fileReader.readAsArrayBuffer(blob);
  100218. });
  100219. // Reapply the previous canvas size
  100220. engine.setSize(currentW, currentH);
  100221. });
  100222. });
  100223. promises.push(promise);
  100224. };
  100225. // All faces of the cube.
  100226. for (var face = 0; face < 6; face++) {
  100227. _loop_2(face);
  100228. }
  100229. };
  100230. for (var i = 0; i <= mipmapsCount; i++) {
  100231. _loop_1(i);
  100232. }
  100233. // Once all the textures haves been collected as RGBD stored in PNGs
  100234. return Promise.all(promises).then(function () {
  100235. // We can delete the hosting scene keeping track of all the creation objects
  100236. hostingScene.dispose();
  100237. // Creates the json header for the env texture
  100238. var info = {
  100239. version: 1,
  100240. width: cubeWidth,
  100241. irradiance: _this._CreateEnvTextureIrradiance(texture),
  100242. specular: {
  100243. mipmaps: [],
  100244. lodGenerationScale: texture.lodGenerationScale
  100245. }
  100246. };
  100247. // Sets the specular image data information
  100248. var position = 0;
  100249. for (var i = 0; i <= mipmapsCount; i++) {
  100250. for (var face = 0; face < 6; face++) {
  100251. var byteLength = specularTextures[i * 6 + face].byteLength;
  100252. info.specular.mipmaps.push({
  100253. length: byteLength,
  100254. position: position
  100255. });
  100256. position += byteLength;
  100257. }
  100258. }
  100259. // Encode the JSON as an array buffer
  100260. var infoString = JSON.stringify(info);
  100261. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  100262. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  100263. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  100264. infoView[i] = infoString.charCodeAt(i);
  100265. }
  100266. // Ends up with a null terminator for easier parsing
  100267. infoView[infoString.length] = 0x00;
  100268. // Computes the final required size and creates the storage
  100269. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  100270. var finalBuffer = new ArrayBuffer(totalSize);
  100271. var finalBufferView = new Uint8Array(finalBuffer);
  100272. var dataView = new DataView(finalBuffer);
  100273. // Copy the magic bytes identifying the file in
  100274. var pos = 0;
  100275. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  100276. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  100277. }
  100278. // Add the json info
  100279. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  100280. pos += infoBuffer.byteLength;
  100281. // Finally inserts the texture data
  100282. for (var i = 0; i <= mipmapsCount; i++) {
  100283. for (var face = 0; face < 6; face++) {
  100284. var dataBuffer = specularTextures[i * 6 + face];
  100285. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  100286. pos += dataBuffer.byteLength;
  100287. }
  100288. }
  100289. // Voila
  100290. return finalBuffer;
  100291. });
  100292. };
  100293. /**
  100294. * Creates a JSON representation of the spherical data.
  100295. * @param texture defines the texture containing the polynomials
  100296. * @return the JSON representation of the spherical info
  100297. */
  100298. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  100299. var polynmials = texture.sphericalPolynomial;
  100300. if (polynmials == null) {
  100301. return null;
  100302. }
  100303. return {
  100304. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  100305. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  100306. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  100307. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  100308. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  100309. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  100310. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  100311. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  100312. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  100313. };
  100314. };
  100315. /**
  100316. * Uploads the texture info contained in the env file to the GPU.
  100317. * @param texture defines the internal texture to upload to
  100318. * @param arrayBuffer defines the buffer cotaining the data to load
  100319. * @param info defines the texture info retrieved through the GetEnvInfo method
  100320. * @returns a promise
  100321. */
  100322. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  100323. if (info.version !== 1) {
  100324. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  100325. }
  100326. var specularInfo = info.specular;
  100327. if (!specularInfo) {
  100328. // Nothing else parsed so far
  100329. return Promise.resolve();
  100330. }
  100331. // Double checks the enclosed info
  100332. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  100333. mipmapsCount = Math.round(mipmapsCount) + 1;
  100334. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  100335. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  100336. }
  100337. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  100338. var imageData = new Array(mipmapsCount);
  100339. for (var i = 0; i < mipmapsCount; i++) {
  100340. imageData[i] = new Array(6);
  100341. for (var face = 0; face < 6; face++) {
  100342. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  100343. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  100344. }
  100345. }
  100346. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  100347. };
  100348. /**
  100349. * Uploads the levels of image data to the GPU.
  100350. * @param texture defines the internal texture to upload to
  100351. * @param imageData defines the array buffer views of image data [mipmap][face]
  100352. * @returns a promise
  100353. */
  100354. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  100355. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  100356. throw new Error("Texture size must be a power of two");
  100357. }
  100358. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  100359. // Gets everything ready.
  100360. var engine = texture.getEngine();
  100361. var expandTexture = false;
  100362. var generateNonLODTextures = false;
  100363. var rgbdPostProcess = null;
  100364. var cubeRtt = null;
  100365. var lodTextures = null;
  100366. var caps = engine.getCaps();
  100367. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  100368. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100369. texture.generateMipMaps = true;
  100370. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  100371. // Add extra process if texture lod is not supported
  100372. if (!caps.textureLOD) {
  100373. expandTexture = false;
  100374. generateNonLODTextures = true;
  100375. lodTextures = {};
  100376. }
  100377. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  100378. else if (engine.webGLVersion < 2) {
  100379. expandTexture = false;
  100380. }
  100381. // If half float available we can uncompress the texture
  100382. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  100383. expandTexture = true;
  100384. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  100385. }
  100386. // If full float available we can uncompress the texture
  100387. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  100388. expandTexture = true;
  100389. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  100390. }
  100391. // Expand the texture if possible
  100392. if (expandTexture) {
  100393. // Simply run through the decode PP
  100394. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  100395. texture._isRGBD = false;
  100396. texture.invertY = false;
  100397. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  100398. generateDepthBuffer: false,
  100399. generateMipMaps: true,
  100400. generateStencilBuffer: false,
  100401. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  100402. type: texture.type,
  100403. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  100404. });
  100405. }
  100406. else {
  100407. texture._isRGBD = true;
  100408. texture.invertY = true;
  100409. // In case of missing support, applies the same patch than DDS files.
  100410. if (generateNonLODTextures) {
  100411. var mipSlices = 3;
  100412. var scale = texture._lodGenerationScale;
  100413. var offset = texture._lodGenerationOffset;
  100414. for (var i = 0; i < mipSlices; i++) {
  100415. //compute LOD from even spacing in smoothness (matching shader calculation)
  100416. var smoothness = i / (mipSlices - 1);
  100417. var roughness = 1 - smoothness;
  100418. var minLODIndex = offset; // roughness = 0
  100419. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  100420. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  100421. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  100422. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  100423. glTextureFromLod.isCube = true;
  100424. glTextureFromLod.invertY = true;
  100425. glTextureFromLod.generateMipMaps = false;
  100426. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  100427. // Wrap in a base texture for easy binding.
  100428. var lodTexture = new BABYLON.BaseTexture(null);
  100429. lodTexture.isCube = true;
  100430. lodTexture._texture = glTextureFromLod;
  100431. lodTextures[mipmapIndex] = lodTexture;
  100432. switch (i) {
  100433. case 0:
  100434. texture._lodTextureLow = lodTexture;
  100435. break;
  100436. case 1:
  100437. texture._lodTextureMid = lodTexture;
  100438. break;
  100439. case 2:
  100440. texture._lodTextureHigh = lodTexture;
  100441. break;
  100442. }
  100443. }
  100444. }
  100445. }
  100446. var promises = [];
  100447. var _loop_3 = function (i) {
  100448. var _loop_4 = function (face) {
  100449. // Constructs an image element from image data
  100450. var bytes = imageData[i][face];
  100451. var blob = new Blob([bytes], { type: 'image/png' });
  100452. var url = URL.createObjectURL(blob);
  100453. var image = new Image();
  100454. image.src = url;
  100455. // Enqueue promise to upload to the texture.
  100456. var promise = new Promise(function (resolve, reject) {
  100457. image.onload = function () {
  100458. if (expandTexture) {
  100459. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  100460. reject(message);
  100461. }, image);
  100462. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  100463. // Uncompress the data to a RTT
  100464. rgbdPostProcess.onApply = function (effect) {
  100465. effect._bindTexture("textureSampler", tempTexture_1);
  100466. effect.setFloat2("scale", 1, 1);
  100467. };
  100468. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  100469. // Cleanup
  100470. engine.restoreDefaultFramebuffer();
  100471. tempTexture_1.dispose();
  100472. window.URL.revokeObjectURL(url);
  100473. resolve();
  100474. });
  100475. }
  100476. else {
  100477. engine._uploadImageToTexture(texture, image, face, i);
  100478. // Upload the face to the non lod texture support
  100479. if (generateNonLODTextures) {
  100480. var lodTexture = lodTextures[i];
  100481. if (lodTexture) {
  100482. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  100483. }
  100484. }
  100485. resolve();
  100486. }
  100487. };
  100488. image.onerror = function (error) {
  100489. reject(error);
  100490. };
  100491. });
  100492. promises.push(promise);
  100493. };
  100494. // All faces
  100495. for (var face = 0; face < 6; face++) {
  100496. _loop_4(face);
  100497. }
  100498. };
  100499. // All mipmaps up to provided number of images
  100500. for (var i = 0; i < imageData.length; i++) {
  100501. _loop_3(i);
  100502. }
  100503. // Fill remaining mipmaps with black textures.
  100504. if (imageData.length < mipmapsCount) {
  100505. var data = void 0;
  100506. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  100507. var dataLength = size * size * 4;
  100508. switch (texture.type) {
  100509. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  100510. data = new Uint8Array(dataLength);
  100511. break;
  100512. }
  100513. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  100514. data = new Uint16Array(dataLength);
  100515. break;
  100516. }
  100517. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  100518. data = new Float32Array(dataLength);
  100519. break;
  100520. }
  100521. }
  100522. for (var i = imageData.length; i < mipmapsCount; i++) {
  100523. for (var face = 0; face < 6; face++) {
  100524. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  100525. }
  100526. }
  100527. }
  100528. // Once all done, finishes the cleanup and return
  100529. return Promise.all(promises).then(function () {
  100530. // Release temp RTT.
  100531. if (cubeRtt) {
  100532. engine._releaseFramebufferObjects(cubeRtt);
  100533. cubeRtt._swapAndDie(texture);
  100534. }
  100535. // Release temp Post Process.
  100536. if (rgbdPostProcess) {
  100537. rgbdPostProcess.dispose();
  100538. }
  100539. // Flag internal texture as ready in case they are in use.
  100540. if (generateNonLODTextures) {
  100541. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  100542. texture._lodTextureHigh._texture.isReady = true;
  100543. }
  100544. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  100545. texture._lodTextureMid._texture.isReady = true;
  100546. }
  100547. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  100548. texture._lodTextureLow._texture.isReady = true;
  100549. }
  100550. }
  100551. });
  100552. };
  100553. /**
  100554. * Uploads spherical polynomials information to the texture.
  100555. * @param texture defines the texture we are trying to upload the information to
  100556. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  100557. */
  100558. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  100559. if (info.version !== 1) {
  100560. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  100561. }
  100562. var irradianceInfo = info.irradiance;
  100563. if (!irradianceInfo) {
  100564. return;
  100565. }
  100566. var sp = new BABYLON.SphericalPolynomial();
  100567. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  100568. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  100569. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  100570. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  100571. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  100572. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  100573. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  100574. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  100575. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  100576. texture._sphericalPolynomial = sp;
  100577. };
  100578. /**
  100579. * Magic number identifying the env file.
  100580. */
  100581. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  100582. return EnvironmentTextureTools;
  100583. }());
  100584. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  100585. })(BABYLON || (BABYLON = {}));
  100586. //# sourceMappingURL=environmentTextureTools.js.map
  100587. var BABYLON;
  100588. (function (BABYLON) {
  100589. /**
  100590. * Implementation of the ENV Texture Loader.
  100591. */
  100592. var ENVTextureLoader = /** @class */ (function () {
  100593. function ENVTextureLoader() {
  100594. /**
  100595. * Defines wether the loader supports cascade loading the different faces.
  100596. */
  100597. this.supportCascades = false;
  100598. }
  100599. /**
  100600. * This returns if the loader support the current file information.
  100601. * @param extension defines the file extension of the file being loaded
  100602. * @param textureFormatInUse defines the current compressed format in use iun the engine
  100603. * @param fallback defines the fallback internal texture if any
  100604. * @param isBase64 defines whether the texture is encoded as a base64
  100605. * @param isBuffer defines whether the texture data are stored as a buffer
  100606. * @returns true if the loader can load the specified file
  100607. */
  100608. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  100609. return extension.indexOf(".env") === 0;
  100610. };
  100611. /**
  100612. * Transform the url before loading if required.
  100613. * @param rootUrl the url of the texture
  100614. * @param textureFormatInUse defines the current compressed format in use iun the engine
  100615. * @returns the transformed texture
  100616. */
  100617. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  100618. return rootUrl;
  100619. };
  100620. /**
  100621. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  100622. * @param rootUrl the url of the texture
  100623. * @param textureFormatInUse defines the current compressed format in use iun the engine
  100624. * @returns the fallback texture
  100625. */
  100626. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  100627. return null;
  100628. };
  100629. /**
  100630. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  100631. * @param data contains the texture data
  100632. * @param texture defines the BabylonJS internal texture
  100633. * @param createPolynomials will be true if polynomials have been requested
  100634. * @param onLoad defines the callback to trigger once the texture is ready
  100635. * @param onError defines the callback to trigger in case of error
  100636. */
  100637. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  100638. if (Array.isArray(data)) {
  100639. return;
  100640. }
  100641. data = data;
  100642. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  100643. if (info) {
  100644. texture.width = info.width;
  100645. texture.height = info.width;
  100646. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  100647. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  100648. texture.isReady = true;
  100649. if (onLoad) {
  100650. onLoad();
  100651. }
  100652. });
  100653. }
  100654. else if (onError) {
  100655. onError("Can not parse the environment file", null);
  100656. }
  100657. };
  100658. /**
  100659. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  100660. * @param data contains the texture data
  100661. * @param texture defines the BabylonJS internal texture
  100662. * @param callback defines the method to call once ready to upload
  100663. */
  100664. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  100665. throw ".env not supported in 2d.";
  100666. };
  100667. return ENVTextureLoader;
  100668. }());
  100669. // Register the loader.
  100670. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  100671. })(BABYLON || (BABYLON = {}));
  100672. //# sourceMappingURL=envTextureLoader.js.map
  100673. var BABYLON;
  100674. (function (BABYLON) {
  100675. /**
  100676. * Renders a layer on top of an existing scene
  100677. */
  100678. var UtilityLayerRenderer = /** @class */ (function () {
  100679. /**
  100680. * Instantiates a UtilityLayerRenderer
  100681. * @param originalScene the original scene that will be rendered on top of
  100682. */
  100683. function UtilityLayerRenderer(
  100684. /** the original scene that will be rendered on top of */
  100685. originalScene) {
  100686. var _this = this;
  100687. this.originalScene = originalScene;
  100688. this._pointerCaptures = {};
  100689. this._lastPointerEvents = {};
  100690. /**
  100691. * If the utility layer should automatically be rendered on top of existing scene
  100692. */
  100693. this.shouldRender = true;
  100694. /**
  100695. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  100696. */
  100697. this.onlyCheckPointerDownEvents = true;
  100698. /**
  100699. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  100700. */
  100701. this.processAllEvents = false;
  100702. /**
  100703. * Observable raised when the pointer move from the utility layer scene to the main scene
  100704. */
  100705. this.onPointerOutObservable = new BABYLON.Observable();
  100706. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  100707. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  100708. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  100709. this.utilityLayerScene._allowPostProcessClearColor = false;
  100710. originalScene.getEngine().scenes.pop();
  100711. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  100712. this.utilityLayerScene.detachControl();
  100713. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  100714. if (!_this.processAllEvents) {
  100715. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  100716. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  100717. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  100718. return;
  100719. }
  100720. }
  100721. var pointerEvent = (prePointerInfo.event);
  100722. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  100723. _this._pointerCaptures[pointerEvent.pointerId] = false;
  100724. return;
  100725. }
  100726. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  100727. if (!prePointerInfo.ray && utilityScenePick) {
  100728. prePointerInfo.ray = utilityScenePick.ray;
  100729. }
  100730. // always fire the prepointer oversvable
  100731. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  100732. // allow every non pointer down event to flow to the utility layer
  100733. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  100734. if (!prePointerInfo.skipOnPointerObservable) {
  100735. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  100736. }
  100737. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  100738. _this._pointerCaptures[pointerEvent.pointerId] = false;
  100739. }
  100740. return;
  100741. }
  100742. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  100743. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  100744. if (utilityScenePick && utilityScenePick.hit) {
  100745. if (!prePointerInfo.skipOnPointerObservable) {
  100746. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  100747. }
  100748. prePointerInfo.skipOnPointerObservable = true;
  100749. }
  100750. }
  100751. else {
  100752. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  100753. var pointerEvent_1 = (prePointerInfo.event);
  100754. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  100755. if (originalScenePick && utilityScenePick) {
  100756. // No pick in utility scene
  100757. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  100758. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  100759. // We touched an utility mesh present in the main scene
  100760. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  100761. prePointerInfo.skipOnPointerObservable = true;
  100762. }
  100763. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  100764. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  100765. }
  100766. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  100767. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  100768. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  100769. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  100770. }
  100771. }
  100772. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  100773. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  100774. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  100775. // If a previous utility layer set this, do not unset this
  100776. if (!prePointerInfo.skipOnPointerObservable) {
  100777. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  100778. }
  100779. }
  100780. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  100781. // We have a pick in both scenes but main is closer than utility
  100782. // We touched an utility mesh present in the main scene
  100783. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  100784. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  100785. prePointerInfo.skipOnPointerObservable = true;
  100786. }
  100787. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  100788. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  100789. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  100790. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  100791. }
  100792. }
  100793. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  100794. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  100795. }
  100796. }
  100797. }
  100798. });
  100799. // Render directly on top of existing scene without clearing
  100800. this.utilityLayerScene.autoClear = false;
  100801. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  100802. if (_this.shouldRender) {
  100803. _this.render();
  100804. }
  100805. });
  100806. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  100807. _this.dispose();
  100808. });
  100809. this._updateCamera();
  100810. }
  100811. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  100812. /**
  100813. * 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)
  100814. */
  100815. get: function () {
  100816. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  100817. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  100818. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  100819. UtilityLayerRenderer._DefaultUtilityLayer = null;
  100820. });
  100821. }
  100822. return UtilityLayerRenderer._DefaultUtilityLayer;
  100823. },
  100824. enumerable: true,
  100825. configurable: true
  100826. });
  100827. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  100828. /**
  100829. * 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)
  100830. */
  100831. get: function () {
  100832. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  100833. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  100834. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  100835. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  100836. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  100837. });
  100838. }
  100839. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  100840. },
  100841. enumerable: true,
  100842. configurable: true
  100843. });
  100844. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  100845. if (!prePointerInfo.skipOnPointerObservable) {
  100846. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  100847. this._lastPointerEvents[pointerEvent.pointerId] = true;
  100848. }
  100849. };
  100850. /**
  100851. * Renders the utility layers scene on top of the original scene
  100852. */
  100853. UtilityLayerRenderer.prototype.render = function () {
  100854. this._updateCamera();
  100855. if (this.utilityLayerScene.activeCamera) {
  100856. // Set the camera's scene to utility layers scene
  100857. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  100858. var camera = this.utilityLayerScene.activeCamera;
  100859. camera._scene = this.utilityLayerScene;
  100860. if (camera.leftCamera) {
  100861. camera.leftCamera._scene = this.utilityLayerScene;
  100862. }
  100863. if (camera.rightCamera) {
  100864. camera.rightCamera._scene = this.utilityLayerScene;
  100865. }
  100866. this.utilityLayerScene.render(false);
  100867. // Reset camera's scene back to original
  100868. camera._scene = oldScene;
  100869. if (camera.leftCamera) {
  100870. camera.leftCamera._scene = oldScene;
  100871. }
  100872. if (camera.rightCamera) {
  100873. camera.rightCamera._scene = oldScene;
  100874. }
  100875. }
  100876. };
  100877. /**
  100878. * Disposes of the renderer
  100879. */
  100880. UtilityLayerRenderer.prototype.dispose = function () {
  100881. this.onPointerOutObservable.clear();
  100882. if (this._afterRenderObserver) {
  100883. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  100884. }
  100885. if (this._sceneDisposeObserver) {
  100886. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  100887. }
  100888. if (this._originalPointerObserver) {
  100889. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  100890. }
  100891. this.utilityLayerScene.dispose();
  100892. };
  100893. UtilityLayerRenderer.prototype._updateCamera = function () {
  100894. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  100895. };
  100896. UtilityLayerRenderer._DefaultUtilityLayer = null;
  100897. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  100898. return UtilityLayerRenderer;
  100899. }());
  100900. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  100901. })(BABYLON || (BABYLON = {}));
  100902. //# sourceMappingURL=utilityLayerRenderer.js.map
  100903. //# sourceMappingURL=behavior.js.map
  100904. var BABYLON;
  100905. (function (BABYLON) {
  100906. /**
  100907. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  100908. */
  100909. var PointerDragBehavior = /** @class */ (function () {
  100910. /**
  100911. * Creates a pointer drag behavior that can be attached to a mesh
  100912. * @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)
  100913. */
  100914. function PointerDragBehavior(options) {
  100915. /**
  100916. * 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)
  100917. */
  100918. this.maxDragAngle = 0;
  100919. /**
  100920. * @hidden
  100921. */
  100922. this._useAlternatePickedPointAboveMaxDragAngle = false;
  100923. /**
  100924. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  100925. */
  100926. this.currentDraggingPointerID = -1;
  100927. /**
  100928. * If the behavior is currently in a dragging state
  100929. */
  100930. this.dragging = false;
  100931. /**
  100932. * 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)
  100933. */
  100934. this.dragDeltaRatio = 0.2;
  100935. /**
  100936. * If the drag plane orientation should be updated during the dragging (Default: true)
  100937. */
  100938. this.updateDragPlane = true;
  100939. // Debug mode will display drag planes to help visualize behavior
  100940. this._debugMode = false;
  100941. this._moving = false;
  100942. /**
  100943. * Fires each time the attached mesh is dragged with the pointer
  100944. * * delta between last drag position and current drag position in world space
  100945. * * dragDistance along the drag axis
  100946. * * dragPlaneNormal normal of the current drag plane used during the drag
  100947. * * dragPlanePoint in world space where the drag intersects the drag plane
  100948. */
  100949. this.onDragObservable = new BABYLON.Observable();
  100950. /**
  100951. * Fires each time a drag begins (eg. mouse down on mesh)
  100952. */
  100953. this.onDragStartObservable = new BABYLON.Observable();
  100954. /**
  100955. * Fires each time a drag ends (eg. mouse release after drag)
  100956. */
  100957. this.onDragEndObservable = new BABYLON.Observable();
  100958. /**
  100959. * If the attached mesh should be moved when dragged
  100960. */
  100961. this.moveAttached = true;
  100962. /**
  100963. * If the drag behavior will react to drag events (Default: true)
  100964. */
  100965. this.enabled = true;
  100966. /**
  100967. * If camera controls should be detached during the drag
  100968. */
  100969. this.detachCameraControls = true;
  100970. /**
  100971. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  100972. */
  100973. this.useObjectOrienationForDragging = true;
  100974. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  100975. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  100976. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  100977. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  100978. this._attachedElement = null;
  100979. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  100980. this._lastPointerRay = {};
  100981. this._dragDelta = new BABYLON.Vector3();
  100982. // Variables to avoid instantiation in the below method
  100983. this._pointA = new BABYLON.Vector3(0, 0, 0);
  100984. this._pointB = new BABYLON.Vector3(0, 0, 0);
  100985. this._pointC = new BABYLON.Vector3(0, 0, 0);
  100986. this._lineA = new BABYLON.Vector3(0, 0, 0);
  100987. this._lineB = new BABYLON.Vector3(0, 0, 0);
  100988. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  100989. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  100990. this._options = options ? options : {};
  100991. var optionCount = 0;
  100992. if (this._options.dragAxis) {
  100993. optionCount++;
  100994. }
  100995. if (this._options.dragPlaneNormal) {
  100996. optionCount++;
  100997. }
  100998. if (optionCount > 1) {
  100999. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  101000. }
  101001. }
  101002. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  101003. /**
  101004. * The name of the behavior
  101005. */
  101006. get: function () {
  101007. return "PointerDrag";
  101008. },
  101009. enumerable: true,
  101010. configurable: true
  101011. });
  101012. /**
  101013. * Initializes the behavior
  101014. */
  101015. PointerDragBehavior.prototype.init = function () { };
  101016. /**
  101017. * Attaches the drag behavior the passed in mesh
  101018. * @param ownerNode The mesh that will be dragged around once attached
  101019. */
  101020. PointerDragBehavior.prototype.attach = function (ownerNode) {
  101021. var _this = this;
  101022. this._scene = ownerNode.getScene();
  101023. this._attachedNode = ownerNode;
  101024. // Initialize drag plane to not interfere with existing scene
  101025. if (!PointerDragBehavior._planeScene) {
  101026. if (this._debugMode) {
  101027. PointerDragBehavior._planeScene = this._scene;
  101028. }
  101029. else {
  101030. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  101031. PointerDragBehavior._planeScene.detachControl();
  101032. this._scene.getEngine().scenes.pop();
  101033. this._scene.onDisposeObservable.addOnce(function () {
  101034. PointerDragBehavior._planeScene.dispose();
  101035. PointerDragBehavior._planeScene = null;
  101036. });
  101037. }
  101038. }
  101039. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  101040. // State of the drag
  101041. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  101042. var pickPredicate = function (m) {
  101043. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  101044. };
  101045. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  101046. if (!_this.enabled) {
  101047. return;
  101048. }
  101049. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  101050. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  101051. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  101052. }
  101053. }
  101054. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  101055. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  101056. _this.releaseDrag();
  101057. }
  101058. }
  101059. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  101060. var pointerId = pointerInfo.event.pointerId;
  101061. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  101062. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  101063. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  101064. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  101065. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  101066. }
  101067. _this.currentDraggingPointerID = pointerId;
  101068. }
  101069. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  101070. if (!_this._lastPointerRay[pointerId]) {
  101071. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  101072. }
  101073. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  101074. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  101075. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  101076. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  101077. _this._moveDrag(pointerInfo.pickInfo.ray);
  101078. }
  101079. }
  101080. }
  101081. });
  101082. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  101083. if (_this._moving && _this.moveAttached) {
  101084. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  101085. // Slowly move mesh to avoid jitter
  101086. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  101087. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  101088. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  101089. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  101090. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  101091. }
  101092. });
  101093. };
  101094. /**
  101095. * Force relase the drag action by code.
  101096. */
  101097. PointerDragBehavior.prototype.releaseDrag = function () {
  101098. this.dragging = false;
  101099. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  101100. this.currentDraggingPointerID = -1;
  101101. this._moving = false;
  101102. // Reattach camera controls
  101103. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  101104. this._scene.activeCamera.attachControl(this._attachedElement, true);
  101105. }
  101106. };
  101107. /**
  101108. * Simulates the start of a pointer drag event on the behavior
  101109. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  101110. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  101111. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  101112. */
  101113. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  101114. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  101115. this._startDrag(pointerId, fromRay, startPickedPoint);
  101116. var lastRay = this._lastPointerRay[pointerId];
  101117. if (pointerId === PointerDragBehavior._AnyMouseID) {
  101118. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  101119. }
  101120. if (lastRay) {
  101121. // if there was a last pointer ray drag the object there
  101122. this._moveDrag(lastRay);
  101123. }
  101124. };
  101125. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  101126. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  101127. return;
  101128. }
  101129. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  101130. // Create start ray from the camera to the object
  101131. if (fromRay) {
  101132. this._startDragRay.direction.copyFrom(fromRay.direction);
  101133. this._startDragRay.origin.copyFrom(fromRay.origin);
  101134. }
  101135. else {
  101136. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  101137. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  101138. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  101139. }
  101140. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  101141. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  101142. if (pickedPoint) {
  101143. this.dragging = true;
  101144. this.currentDraggingPointerID = pointerId;
  101145. this.lastDragPosition.copyFrom(pickedPoint);
  101146. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  101147. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  101148. // Detatch camera controls
  101149. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  101150. if (this._scene.activeCamera.inputs.attachedElement) {
  101151. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  101152. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  101153. }
  101154. else {
  101155. this._attachedElement = null;
  101156. }
  101157. }
  101158. }
  101159. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  101160. };
  101161. PointerDragBehavior.prototype._moveDrag = function (ray) {
  101162. this._moving = true;
  101163. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  101164. if (pickedPoint) {
  101165. if (this.updateDragPlane) {
  101166. this._updateDragPlanePosition(ray, pickedPoint);
  101167. }
  101168. var dragLength = 0;
  101169. // depending on the drag mode option drag accordingly
  101170. if (this._options.dragAxis) {
  101171. // Convert local drag axis to world
  101172. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  101173. // Project delta drag from the drag plane onto the drag axis
  101174. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  101175. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  101176. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  101177. }
  101178. else {
  101179. dragLength = this._dragDelta.length();
  101180. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  101181. }
  101182. this._targetPosition.addInPlace(this._dragDelta);
  101183. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  101184. this.lastDragPosition.copyFrom(pickedPoint);
  101185. }
  101186. };
  101187. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  101188. var _this = this;
  101189. if (!ray) {
  101190. return null;
  101191. }
  101192. // Calculate angle between plane normal and ray
  101193. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  101194. // Correct if ray is casted from oposite side
  101195. if (angle > Math.PI / 2) {
  101196. angle = Math.PI - angle;
  101197. }
  101198. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  101199. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  101200. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  101201. // Invert ray direction along the towards object axis
  101202. this._tmpVector.copyFrom(ray.direction);
  101203. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  101204. this._alternatePickedPoint.normalize();
  101205. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  101206. this._tmpVector.addInPlace(this._alternatePickedPoint);
  101207. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  101208. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  101209. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  101210. this._alternatePickedPoint.addInPlace(this._tmpVector);
  101211. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  101212. return this._alternatePickedPoint;
  101213. }
  101214. else {
  101215. return null;
  101216. }
  101217. }
  101218. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  101219. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  101220. return pickResult.pickedPoint;
  101221. }
  101222. else {
  101223. return null;
  101224. }
  101225. };
  101226. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  101227. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  101228. this._pointA.copyFrom(dragPlanePosition);
  101229. if (this._options.dragAxis) {
  101230. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  101231. // Calculate plane normal in direction of camera but perpendicular to drag axis
  101232. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  101233. ray.origin.subtractToRef(this._pointA, this._pointC);
  101234. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  101235. // Get perpendicular line from direction to camera and drag axis
  101236. this._pointB.subtractToRef(this._pointA, this._lineA);
  101237. this._pointC.subtractToRef(this._pointA, this._lineB);
  101238. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  101239. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  101240. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  101241. this._lookAt.normalize();
  101242. this._dragPlane.position.copyFrom(this._pointA);
  101243. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  101244. this._dragPlane.lookAt(this._lookAt);
  101245. }
  101246. else if (this._options.dragPlaneNormal) {
  101247. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  101248. this._dragPlane.position.copyFrom(this._pointA);
  101249. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  101250. this._dragPlane.lookAt(this._lookAt);
  101251. }
  101252. else {
  101253. this._dragPlane.position.copyFrom(this._pointA);
  101254. this._dragPlane.lookAt(ray.origin);
  101255. }
  101256. this._dragPlane.computeWorldMatrix(true);
  101257. };
  101258. /**
  101259. * Detaches the behavior from the mesh
  101260. */
  101261. PointerDragBehavior.prototype.detach = function () {
  101262. if (this._pointerObserver) {
  101263. this._scene.onPointerObservable.remove(this._pointerObserver);
  101264. }
  101265. if (this._beforeRenderObserver) {
  101266. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  101267. }
  101268. };
  101269. PointerDragBehavior._AnyMouseID = -2;
  101270. return PointerDragBehavior;
  101271. }());
  101272. BABYLON.PointerDragBehavior = PointerDragBehavior;
  101273. })(BABYLON || (BABYLON = {}));
  101274. //# sourceMappingURL=pointerDragBehavior.js.map
  101275. var BABYLON;
  101276. (function (BABYLON) {
  101277. /**
  101278. * A behavior that when attached to a mesh will allow the mesh to be scaled
  101279. */
  101280. var MultiPointerScaleBehavior = /** @class */ (function () {
  101281. /**
  101282. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  101283. */
  101284. function MultiPointerScaleBehavior() {
  101285. this._startDistance = 0;
  101286. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  101287. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  101288. this._sceneRenderObserver = null;
  101289. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  101290. this._dragBehaviorA.moveAttached = false;
  101291. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  101292. this._dragBehaviorB.moveAttached = false;
  101293. }
  101294. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  101295. /**
  101296. * The name of the behavior
  101297. */
  101298. get: function () {
  101299. return "MultiPointerScale";
  101300. },
  101301. enumerable: true,
  101302. configurable: true
  101303. });
  101304. /**
  101305. * Initializes the behavior
  101306. */
  101307. MultiPointerScaleBehavior.prototype.init = function () { };
  101308. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  101309. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  101310. };
  101311. /**
  101312. * Attaches the scale behavior the passed in mesh
  101313. * @param ownerNode The mesh that will be scaled around once attached
  101314. */
  101315. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  101316. var _this = this;
  101317. this._ownerNode = ownerNode;
  101318. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  101319. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  101320. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  101321. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  101322. _this._dragBehaviorA.releaseDrag();
  101323. }
  101324. else {
  101325. _this._initialScale.copyFrom(ownerNode.scaling);
  101326. _this._startDistance = _this._getCurrentDistance();
  101327. }
  101328. }
  101329. });
  101330. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  101331. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  101332. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  101333. _this._dragBehaviorB.releaseDrag();
  101334. }
  101335. else {
  101336. _this._initialScale.copyFrom(ownerNode.scaling);
  101337. _this._startDistance = _this._getCurrentDistance();
  101338. }
  101339. }
  101340. });
  101341. // Once both drag behaviors are active scale based on the distance between the two pointers
  101342. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  101343. behavior.onDragObservable.add(function () {
  101344. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  101345. var ratio = _this._getCurrentDistance() / _this._startDistance;
  101346. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  101347. }
  101348. });
  101349. });
  101350. ownerNode.addBehavior(this._dragBehaviorA);
  101351. ownerNode.addBehavior(this._dragBehaviorB);
  101352. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  101353. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  101354. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  101355. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  101356. if (change.length() > 0.01) {
  101357. ownerNode.scaling.addInPlace(change);
  101358. }
  101359. }
  101360. });
  101361. };
  101362. /**
  101363. * Detaches the behavior from the mesh
  101364. */
  101365. MultiPointerScaleBehavior.prototype.detach = function () {
  101366. var _this = this;
  101367. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  101368. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  101369. behavior.onDragStartObservable.clear();
  101370. behavior.onDragObservable.clear();
  101371. _this._ownerNode.removeBehavior(behavior);
  101372. });
  101373. };
  101374. return MultiPointerScaleBehavior;
  101375. }());
  101376. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  101377. })(BABYLON || (BABYLON = {}));
  101378. //# sourceMappingURL=multiPointerScaleBehavior.js.map
  101379. var BABYLON;
  101380. (function (BABYLON) {
  101381. /**
  101382. * 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
  101383. */
  101384. var SixDofDragBehavior = /** @class */ (function () {
  101385. /**
  101386. * 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
  101387. */
  101388. function SixDofDragBehavior() {
  101389. this._sceneRenderObserver = null;
  101390. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  101391. this._moving = false;
  101392. this._startingOrientation = new BABYLON.Quaternion();
  101393. /**
  101394. * 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)
  101395. */
  101396. this.zDragFactor = 3;
  101397. /**
  101398. * If the behavior is currently in a dragging state
  101399. */
  101400. this.dragging = false;
  101401. /**
  101402. * 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)
  101403. */
  101404. this.dragDeltaRatio = 0.2;
  101405. /**
  101406. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  101407. */
  101408. this.currentDraggingPointerID = -1;
  101409. /**
  101410. * If camera controls should be detached during the drag
  101411. */
  101412. this.detachCameraControls = true;
  101413. /**
  101414. * Fires each time a drag starts
  101415. */
  101416. this.onDragStartObservable = new BABYLON.Observable();
  101417. /**
  101418. * Fires each time a drag ends (eg. mouse release after drag)
  101419. */
  101420. this.onDragEndObservable = new BABYLON.Observable();
  101421. }
  101422. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  101423. /**
  101424. * The name of the behavior
  101425. */
  101426. get: function () {
  101427. return "SixDofDrag";
  101428. },
  101429. enumerable: true,
  101430. configurable: true
  101431. });
  101432. /**
  101433. * Initializes the behavior
  101434. */
  101435. SixDofDragBehavior.prototype.init = function () { };
  101436. /**
  101437. * Attaches the scale behavior the passed in mesh
  101438. * @param ownerNode The mesh that will be scaled around once attached
  101439. */
  101440. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  101441. var _this = this;
  101442. this._ownerNode = ownerNode;
  101443. this._scene = this._ownerNode.getScene();
  101444. if (!SixDofDragBehavior._virtualScene) {
  101445. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  101446. SixDofDragBehavior._virtualScene.detachControl();
  101447. this._scene.getEngine().scenes.pop();
  101448. }
  101449. var pickedMesh = null;
  101450. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  101451. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  101452. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  101453. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  101454. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  101455. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  101456. var pickPredicate = function (m) {
  101457. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  101458. };
  101459. var attachedElement = null;
  101460. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  101461. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  101462. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  101463. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  101464. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  101465. }
  101466. pickedMesh = _this._ownerNode;
  101467. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  101468. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  101469. // Set position and orientation of the controller
  101470. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  101471. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  101472. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  101473. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  101474. pickedMesh.computeWorldMatrix();
  101475. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  101476. if (!pickedMesh.rotationQuaternion) {
  101477. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  101478. }
  101479. var oldParent = pickedMesh.parent;
  101480. pickedMesh.setParent(null);
  101481. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  101482. pickedMesh.setParent(oldParent);
  101483. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  101484. // Update state
  101485. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  101486. _this.dragging = true;
  101487. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  101488. // Detatch camera controls
  101489. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  101490. if (_this._scene.activeCamera.inputs.attachedElement) {
  101491. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  101492. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  101493. }
  101494. else {
  101495. attachedElement = null;
  101496. }
  101497. }
  101498. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  101499. _this.onDragStartObservable.notifyObservers({});
  101500. }
  101501. }
  101502. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  101503. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  101504. _this.dragging = false;
  101505. _this._moving = false;
  101506. _this.currentDraggingPointerID = -1;
  101507. pickedMesh = null;
  101508. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  101509. // Reattach camera controls
  101510. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  101511. _this._scene.activeCamera.attachControl(attachedElement, true);
  101512. }
  101513. _this.onDragEndObservable.notifyObservers({});
  101514. }
  101515. }
  101516. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  101517. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  101518. var zDragFactor = _this.zDragFactor;
  101519. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  101520. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  101521. zDragFactor = 0;
  101522. }
  101523. // Calculate controller drag distance in controller space
  101524. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  101525. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  101526. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  101527. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  101528. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  101529. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  101530. if (_this._virtualDragMesh.position.z < 0) {
  101531. _this._virtualDragMesh.position.z = 0;
  101532. }
  101533. // Update the controller position
  101534. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  101535. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  101536. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  101537. // Move the virtualObjectsPosition into the picked mesh's space if needed
  101538. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  101539. if (pickedMesh.parent) {
  101540. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  101541. }
  101542. if (!_this._moving) {
  101543. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  101544. }
  101545. _this._moving = true;
  101546. }
  101547. }
  101548. });
  101549. var tmpQuaternion = new BABYLON.Quaternion();
  101550. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  101551. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  101552. if (_this.dragging && _this._moving && pickedMesh) {
  101553. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  101554. // Slowly move mesh to avoid jitter
  101555. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  101556. // Get change in rotation
  101557. tmpQuaternion.copyFrom(_this._startingOrientation);
  101558. tmpQuaternion.x = -tmpQuaternion.x;
  101559. tmpQuaternion.y = -tmpQuaternion.y;
  101560. tmpQuaternion.z = -tmpQuaternion.z;
  101561. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  101562. // Convert change in rotation to only y axis rotation
  101563. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  101564. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  101565. // Slowly move mesh to avoid jitter
  101566. var oldParent = pickedMesh.parent;
  101567. pickedMesh.setParent(null);
  101568. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  101569. pickedMesh.setParent(oldParent);
  101570. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  101571. }
  101572. });
  101573. };
  101574. /**
  101575. * Detaches the behavior from the mesh
  101576. */
  101577. SixDofDragBehavior.prototype.detach = function () {
  101578. if (this._scene) {
  101579. this._scene.onPointerObservable.remove(this._pointerObserver);
  101580. }
  101581. if (this._ownerNode) {
  101582. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  101583. }
  101584. if (this._virtualOriginMesh) {
  101585. this._virtualOriginMesh.dispose();
  101586. }
  101587. if (this._virtualDragMesh) {
  101588. this._virtualDragMesh.dispose();
  101589. }
  101590. this.onDragEndObservable.clear();
  101591. this.onDragStartObservable.clear();
  101592. };
  101593. return SixDofDragBehavior;
  101594. }());
  101595. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  101596. })(BABYLON || (BABYLON = {}));
  101597. //# sourceMappingURL=sixDofDragBehavior.js.map
  101598. var BABYLON;
  101599. (function (BABYLON) {
  101600. /**
  101601. * @hidden
  101602. */
  101603. var FaceDirectionInfo = /** @class */ (function () {
  101604. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  101605. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  101606. if (diff === void 0) { diff = 0; }
  101607. if (ignore === void 0) { ignore = false; }
  101608. this.direction = direction;
  101609. this.rotatedDirection = rotatedDirection;
  101610. this.diff = diff;
  101611. this.ignore = ignore;
  101612. }
  101613. return FaceDirectionInfo;
  101614. }());
  101615. /**
  101616. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  101617. */
  101618. var AttachToBoxBehavior = /** @class */ (function () {
  101619. /**
  101620. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  101621. * @param ui The transform node that should be attched to the mesh
  101622. */
  101623. function AttachToBoxBehavior(ui) {
  101624. this.ui = ui;
  101625. /**
  101626. * The name of the behavior
  101627. */
  101628. this.name = "AttachToBoxBehavior";
  101629. /**
  101630. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  101631. */
  101632. this.distanceAwayFromFace = 0.15;
  101633. /**
  101634. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  101635. */
  101636. this.distanceAwayFromBottomOfFace = 0.15;
  101637. 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))];
  101638. this._tmpMatrix = new BABYLON.Matrix();
  101639. this._tmpVector = new BABYLON.Vector3();
  101640. this._zeroVector = BABYLON.Vector3.Zero();
  101641. this._lookAtTmpMatrix = new BABYLON.Matrix();
  101642. /* Does nothing */
  101643. }
  101644. /**
  101645. * Initializes the behavior
  101646. */
  101647. AttachToBoxBehavior.prototype.init = function () {
  101648. /* Does nothing */
  101649. };
  101650. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  101651. var _this = this;
  101652. // Go over each face and calculate the angle between the face's normal and targetDirection
  101653. this._faceVectors.forEach(function (v) {
  101654. if (!_this._target.rotationQuaternion) {
  101655. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  101656. }
  101657. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  101658. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  101659. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  101660. });
  101661. // Return the face information of the one with the normal closeset to target direction
  101662. return this._faceVectors.reduce(function (min, p) {
  101663. if (min.ignore) {
  101664. return p;
  101665. }
  101666. else if (p.ignore) {
  101667. return min;
  101668. }
  101669. else {
  101670. return min.diff < p.diff ? min : p;
  101671. }
  101672. }, this._faceVectors[0]);
  101673. };
  101674. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  101675. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  101676. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  101677. this._lookAtTmpMatrix.invert();
  101678. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  101679. };
  101680. /**
  101681. * Attaches the AttachToBoxBehavior to the passed in mesh
  101682. * @param target The mesh that the specified node will be attached to
  101683. */
  101684. AttachToBoxBehavior.prototype.attach = function (target) {
  101685. var _this = this;
  101686. this._target = target;
  101687. this._scene = this._target.getScene();
  101688. // Every frame, update the app bars position
  101689. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  101690. if (!_this._scene.activeCamera) {
  101691. return;
  101692. }
  101693. // Find the face closest to the cameras position
  101694. var cameraPos = _this._scene.activeCamera.position;
  101695. if (_this._scene.activeCamera.devicePosition) {
  101696. cameraPos = _this._scene.activeCamera.devicePosition;
  101697. }
  101698. var facing = _this._closestFace(cameraPos.subtract(target.position));
  101699. if (_this._scene.activeCamera.leftCamera) {
  101700. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  101701. }
  101702. else {
  101703. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  101704. }
  101705. // Get camera up direction
  101706. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  101707. // Ignore faces to not select a parrelel face for the up vector of the UI
  101708. _this._faceVectors.forEach(function (v) {
  101709. if (facing.direction.x && v.direction.x) {
  101710. v.ignore = true;
  101711. }
  101712. if (facing.direction.y && v.direction.y) {
  101713. v.ignore = true;
  101714. }
  101715. if (facing.direction.z && v.direction.z) {
  101716. v.ignore = true;
  101717. }
  101718. });
  101719. var facingUp = _this._closestFace(_this._tmpVector);
  101720. // Unignore faces
  101721. _this._faceVectors.forEach(function (v) {
  101722. v.ignore = false;
  101723. });
  101724. // Position the app bar on that face
  101725. _this.ui.position.copyFrom(target.position);
  101726. if (facing.direction.x) {
  101727. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  101728. _this.ui.position.addInPlace(_this._tmpVector);
  101729. }
  101730. if (facing.direction.y) {
  101731. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  101732. _this.ui.position.addInPlace(_this._tmpVector);
  101733. }
  101734. if (facing.direction.z) {
  101735. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  101736. _this.ui.position.addInPlace(_this._tmpVector);
  101737. }
  101738. // Rotate to be oriented properly to the camera
  101739. if (!_this.ui.rotationQuaternion) {
  101740. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  101741. }
  101742. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  101743. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  101744. // Place ui the correct distance from the bottom of the mesh
  101745. if (facingUp.direction.x) {
  101746. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  101747. }
  101748. if (facingUp.direction.y) {
  101749. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  101750. }
  101751. if (facingUp.direction.z) {
  101752. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  101753. }
  101754. _this.ui.position.addInPlace(_this._tmpVector);
  101755. });
  101756. };
  101757. /**
  101758. * Detaches the behavior from the mesh
  101759. */
  101760. AttachToBoxBehavior.prototype.detach = function () {
  101761. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  101762. };
  101763. return AttachToBoxBehavior;
  101764. }());
  101765. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  101766. })(BABYLON || (BABYLON = {}));
  101767. //# sourceMappingURL=attachToBoxBehavior.js.map
  101768. var BABYLON;
  101769. (function (BABYLON) {
  101770. /**
  101771. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  101772. */
  101773. var FadeInOutBehavior = /** @class */ (function () {
  101774. /**
  101775. * Instatiates the FadeInOutBehavior
  101776. */
  101777. function FadeInOutBehavior() {
  101778. var _this = this;
  101779. /**
  101780. * Time in milliseconds to delay before fading in (Default: 0)
  101781. */
  101782. this.delay = 0;
  101783. /**
  101784. * Time in milliseconds for the mesh to fade in (Default: 300)
  101785. */
  101786. this.fadeInTime = 300;
  101787. this._millisecondsPerFrame = 1000 / 60;
  101788. this._hovered = false;
  101789. this._hoverValue = 0;
  101790. this._ownerNode = null;
  101791. this._update = function () {
  101792. if (_this._ownerNode) {
  101793. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  101794. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  101795. if (_this._ownerNode.visibility > 1) {
  101796. _this._setAllVisibility(_this._ownerNode, 1);
  101797. _this._hoverValue = _this.fadeInTime + _this.delay;
  101798. return;
  101799. }
  101800. else if (_this._ownerNode.visibility < 0) {
  101801. _this._setAllVisibility(_this._ownerNode, 0);
  101802. if (_this._hoverValue < 0) {
  101803. _this._hoverValue = 0;
  101804. return;
  101805. }
  101806. }
  101807. setTimeout(_this._update, _this._millisecondsPerFrame);
  101808. }
  101809. };
  101810. }
  101811. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  101812. /**
  101813. * The name of the behavior
  101814. */
  101815. get: function () {
  101816. return "FadeInOut";
  101817. },
  101818. enumerable: true,
  101819. configurable: true
  101820. });
  101821. /**
  101822. * Initializes the behavior
  101823. */
  101824. FadeInOutBehavior.prototype.init = function () {
  101825. };
  101826. /**
  101827. * Attaches the fade behavior on the passed in mesh
  101828. * @param ownerNode The mesh that will be faded in/out once attached
  101829. */
  101830. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  101831. this._ownerNode = ownerNode;
  101832. this._setAllVisibility(this._ownerNode, 0);
  101833. };
  101834. /**
  101835. * Detaches the behavior from the mesh
  101836. */
  101837. FadeInOutBehavior.prototype.detach = function () {
  101838. this._ownerNode = null;
  101839. };
  101840. /**
  101841. * Triggers the mesh to begin fading in or out
  101842. * @param value if the object should fade in or out (true to fade in)
  101843. */
  101844. FadeInOutBehavior.prototype.fadeIn = function (value) {
  101845. this._hovered = value;
  101846. this._update();
  101847. };
  101848. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  101849. var _this = this;
  101850. mesh.visibility = value;
  101851. mesh.getChildMeshes().forEach(function (c) {
  101852. _this._setAllVisibility(c, value);
  101853. });
  101854. };
  101855. return FadeInOutBehavior;
  101856. }());
  101857. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  101858. })(BABYLON || (BABYLON = {}));
  101859. //# sourceMappingURL=fadeInOutBehavior.js.map
  101860. var BABYLON;
  101861. (function (BABYLON) {
  101862. /**
  101863. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  101864. */
  101865. var Gizmo = /** @class */ (function () {
  101866. /**
  101867. * Creates a gizmo
  101868. * @param gizmoLayer The utility layer the gizmo will be added to
  101869. */
  101870. function Gizmo(
  101871. /** The utility layer the gizmo will be added to */
  101872. gizmoLayer) {
  101873. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  101874. var _this = this;
  101875. this.gizmoLayer = gizmoLayer;
  101876. /**
  101877. * Ratio for the scale of the gizmo (Default: 1)
  101878. */
  101879. this.scaleRatio = 1;
  101880. this._tmpMatrix = new BABYLON.Matrix();
  101881. /**
  101882. * If a custom mesh has been set (Default: false)
  101883. */
  101884. this._customMeshSet = false;
  101885. /**
  101886. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  101887. */
  101888. this.updateGizmoRotationToMatchAttachedMesh = true;
  101889. /**
  101890. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  101891. */
  101892. this.updateGizmoPositionToMatchAttachedMesh = true;
  101893. /**
  101894. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  101895. */
  101896. this._updateScale = true;
  101897. this._interactionsEnabled = true;
  101898. this._tempVector = new BABYLON.Vector3();
  101899. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  101900. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  101901. _this._update();
  101902. });
  101903. this.attachedMesh = null;
  101904. }
  101905. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  101906. /**
  101907. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  101908. * * When set, interactions will be enabled
  101909. */
  101910. get: function () {
  101911. return this._attachedMesh;
  101912. },
  101913. set: function (value) {
  101914. this._attachedMesh = value;
  101915. this._rootMesh.setEnabled(value ? true : false);
  101916. this._attachedMeshChanged(value);
  101917. },
  101918. enumerable: true,
  101919. configurable: true
  101920. });
  101921. /**
  101922. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  101923. * @param mesh The mesh to replace the default mesh of the gizmo
  101924. */
  101925. Gizmo.prototype.setCustomMesh = function (mesh) {
  101926. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  101927. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  101928. }
  101929. this._rootMesh.getChildMeshes().forEach(function (c) {
  101930. c.dispose();
  101931. });
  101932. mesh.parent = this._rootMesh;
  101933. this._customMeshSet = true;
  101934. };
  101935. Gizmo.prototype._attachedMeshChanged = function (value) {
  101936. };
  101937. /**
  101938. * @hidden
  101939. * Updates the gizmo to match the attached mesh's position/rotation
  101940. */
  101941. Gizmo.prototype._update = function () {
  101942. if (this.attachedMesh) {
  101943. if (this.updateGizmoRotationToMatchAttachedMesh) {
  101944. if (!this._rootMesh.rotationQuaternion) {
  101945. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  101946. }
  101947. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  101948. this._tempVector.copyFrom(this.attachedMesh.scaling);
  101949. if (this.attachedMesh.scaling.x < 0) {
  101950. this.attachedMesh.scaling.x *= -1;
  101951. }
  101952. if (this.attachedMesh.scaling.y < 0) {
  101953. this.attachedMesh.scaling.y *= -1;
  101954. }
  101955. if (this.attachedMesh.scaling.z < 0) {
  101956. this.attachedMesh.scaling.z *= -1;
  101957. }
  101958. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  101959. this.attachedMesh.scaling.copyFrom(this._tempVector);
  101960. this.attachedMesh.computeWorldMatrix();
  101961. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  101962. }
  101963. else if (this._rootMesh.rotationQuaternion) {
  101964. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  101965. }
  101966. if (this.updateGizmoPositionToMatchAttachedMesh) {
  101967. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  101968. }
  101969. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  101970. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.globalPosition;
  101971. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  101972. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  101973. }
  101974. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  101975. var dist = this._tempVector.length() * this.scaleRatio;
  101976. this._rootMesh.scaling.set(dist, dist, dist);
  101977. }
  101978. }
  101979. };
  101980. /**
  101981. * Disposes of the gizmo
  101982. */
  101983. Gizmo.prototype.dispose = function () {
  101984. this._rootMesh.dispose();
  101985. if (this._beforeRenderObserver) {
  101986. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  101987. }
  101988. };
  101989. return Gizmo;
  101990. }());
  101991. BABYLON.Gizmo = Gizmo;
  101992. })(BABYLON || (BABYLON = {}));
  101993. //# sourceMappingURL=gizmo.js.map
  101994. var BABYLON;
  101995. (function (BABYLON) {
  101996. /**
  101997. * Single axis drag gizmo
  101998. */
  101999. var AxisDragGizmo = /** @class */ (function (_super) {
  102000. __extends(AxisDragGizmo, _super);
  102001. /**
  102002. * Creates an AxisDragGizmo
  102003. * @param gizmoLayer The utility layer the gizmo will be added to
  102004. * @param dragAxis The axis which the gizmo will be able to drag on
  102005. * @param color The color of the gizmo
  102006. */
  102007. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  102008. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  102009. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102010. var _this = _super.call(this, gizmoLayer) || this;
  102011. _this._pointerObserver = null;
  102012. /**
  102013. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  102014. */
  102015. _this.snapDistance = 0;
  102016. /**
  102017. * Event that fires each time the gizmo snaps to a new location.
  102018. * * snapDistance is the the change in distance
  102019. */
  102020. _this.onSnapObservable = new BABYLON.Observable();
  102021. // Create Material
  102022. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102023. coloredMaterial.disableLighting = true;
  102024. coloredMaterial.emissiveColor = color;
  102025. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102026. hoverMaterial.disableLighting = true;
  102027. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  102028. // Build mesh on root node
  102029. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102030. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  102031. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  102032. arrowTail.color = coloredMaterial.emissiveColor;
  102033. arrow.addChild(arrowMesh);
  102034. arrow.addChild(arrowTail);
  102035. // Position arrow pointing in its drag axis
  102036. arrowMesh.scaling.scaleInPlace(0.05);
  102037. arrowMesh.material = coloredMaterial;
  102038. arrowMesh.rotation.x = Math.PI / 2;
  102039. arrowMesh.position.z += 0.3;
  102040. arrowTail.scaling.scaleInPlace(0.26);
  102041. arrowTail.rotation.x = Math.PI / 2;
  102042. arrowTail.material = coloredMaterial;
  102043. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  102044. arrow.scaling.scaleInPlace(1 / 3);
  102045. _this._rootMesh.addChild(arrow);
  102046. var currentSnapDragDistance = 0;
  102047. var tmpVector = new BABYLON.Vector3();
  102048. var tmpSnapEvent = { snapDistance: 0 };
  102049. // Add drag behavior to handle events when the gizmo is dragged
  102050. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  102051. _this.dragBehavior.moveAttached = false;
  102052. _this._rootMesh.addBehavior(_this.dragBehavior);
  102053. var localDelta = new BABYLON.Vector3();
  102054. var tmpMatrix = new BABYLON.Matrix();
  102055. _this.dragBehavior.onDragObservable.add(function (event) {
  102056. if (_this.attachedMesh) {
  102057. // Convert delta to local translation if it has a parent
  102058. if (_this.attachedMesh.parent) {
  102059. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  102060. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  102061. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  102062. }
  102063. else {
  102064. localDelta.copyFrom(event.delta);
  102065. }
  102066. // Snapping logic
  102067. if (_this.snapDistance == 0) {
  102068. _this.attachedMesh.position.addInPlace(localDelta);
  102069. }
  102070. else {
  102071. currentSnapDragDistance += event.dragDistance;
  102072. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  102073. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  102074. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  102075. localDelta.normalizeToRef(tmpVector);
  102076. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  102077. _this.attachedMesh.position.addInPlace(tmpVector);
  102078. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  102079. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  102080. }
  102081. }
  102082. }
  102083. });
  102084. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  102085. if (_this._customMeshSet) {
  102086. return;
  102087. }
  102088. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  102089. var material = isHovered ? hoverMaterial : coloredMaterial;
  102090. _this._rootMesh.getChildMeshes().forEach(function (m) {
  102091. m.material = material;
  102092. if (m.color) {
  102093. m.color = material.emissiveColor;
  102094. }
  102095. });
  102096. });
  102097. return _this;
  102098. }
  102099. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  102100. if (this.dragBehavior) {
  102101. this.dragBehavior.enabled = value ? true : false;
  102102. }
  102103. };
  102104. /**
  102105. * Disposes of the gizmo
  102106. */
  102107. AxisDragGizmo.prototype.dispose = function () {
  102108. this.onSnapObservable.clear();
  102109. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  102110. this.dragBehavior.detach();
  102111. _super.prototype.dispose.call(this);
  102112. };
  102113. return AxisDragGizmo;
  102114. }(BABYLON.Gizmo));
  102115. BABYLON.AxisDragGizmo = AxisDragGizmo;
  102116. })(BABYLON || (BABYLON = {}));
  102117. //# sourceMappingURL=axisDragGizmo.js.map
  102118. var BABYLON;
  102119. (function (BABYLON) {
  102120. /**
  102121. * Single axis scale gizmo
  102122. */
  102123. var AxisScaleGizmo = /** @class */ (function (_super) {
  102124. __extends(AxisScaleGizmo, _super);
  102125. /**
  102126. * Creates an AxisScaleGizmo
  102127. * @param gizmoLayer The utility layer the gizmo will be added to
  102128. * @param dragAxis The axis which the gizmo will be able to scale on
  102129. * @param color The color of the gizmo
  102130. */
  102131. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  102132. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  102133. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102134. var _this = _super.call(this, gizmoLayer) || this;
  102135. _this._pointerObserver = null;
  102136. /**
  102137. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  102138. */
  102139. _this.snapDistance = 0;
  102140. /**
  102141. * Event that fires each time the gizmo snaps to a new location.
  102142. * * snapDistance is the the change in distance
  102143. */
  102144. _this.onSnapObservable = new BABYLON.Observable();
  102145. /**
  102146. * If the scaling operation should be done on all axis (default: false)
  102147. */
  102148. _this.uniformScaling = false;
  102149. // Create Material
  102150. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102151. _this._coloredMaterial.disableLighting = true;
  102152. _this._coloredMaterial.emissiveColor = color;
  102153. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102154. hoverMaterial.disableLighting = true;
  102155. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  102156. // Build mesh on root node
  102157. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102158. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  102159. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  102160. arrowTail.color = _this._coloredMaterial.emissiveColor;
  102161. arrow.addChild(arrowMesh);
  102162. arrow.addChild(arrowTail);
  102163. // Position arrow pointing in its drag axis
  102164. arrowMesh.scaling.scaleInPlace(0.1);
  102165. arrowMesh.material = _this._coloredMaterial;
  102166. arrowMesh.rotation.x = Math.PI / 2;
  102167. arrowMesh.position.z += 0.3;
  102168. arrowTail.scaling.scaleInPlace(0.26);
  102169. arrowTail.rotation.x = Math.PI / 2;
  102170. arrowTail.material = _this._coloredMaterial;
  102171. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  102172. _this._rootMesh.addChild(arrow);
  102173. arrow.scaling.scaleInPlace(1 / 3);
  102174. // Add drag behavior to handle events when the gizmo is dragged
  102175. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  102176. _this.dragBehavior.moveAttached = false;
  102177. _this._rootMesh.addBehavior(_this.dragBehavior);
  102178. var currentSnapDragDistance = 0;
  102179. var tmpVector = new BABYLON.Vector3();
  102180. var tmpSnapEvent = { snapDistance: 0 };
  102181. _this.dragBehavior.onDragObservable.add(function (event) {
  102182. if (_this.attachedMesh) {
  102183. // Snapping logic
  102184. var snapped = false;
  102185. var dragSteps = 0;
  102186. if (_this.uniformScaling) {
  102187. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  102188. if (tmpVector.y < 0) {
  102189. tmpVector.scaleInPlace(-1);
  102190. }
  102191. }
  102192. else {
  102193. tmpVector.copyFrom(dragAxis);
  102194. }
  102195. if (_this.snapDistance == 0) {
  102196. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  102197. }
  102198. else {
  102199. currentSnapDragDistance += event.dragDistance;
  102200. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  102201. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  102202. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  102203. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  102204. snapped = true;
  102205. }
  102206. else {
  102207. tmpVector.scaleInPlace(0);
  102208. }
  102209. }
  102210. _this.attachedMesh.scaling.addInPlace(tmpVector);
  102211. if (snapped) {
  102212. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  102213. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  102214. }
  102215. }
  102216. });
  102217. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  102218. if (_this._customMeshSet) {
  102219. return;
  102220. }
  102221. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  102222. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  102223. _this._rootMesh.getChildMeshes().forEach(function (m) {
  102224. m.material = material;
  102225. if (m.color) {
  102226. m.color = material.emissiveColor;
  102227. }
  102228. });
  102229. });
  102230. return _this;
  102231. }
  102232. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  102233. if (this.dragBehavior) {
  102234. this.dragBehavior.enabled = value ? true : false;
  102235. }
  102236. };
  102237. /**
  102238. * Disposes of the gizmo
  102239. */
  102240. AxisScaleGizmo.prototype.dispose = function () {
  102241. this.onSnapObservable.clear();
  102242. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  102243. this.dragBehavior.detach();
  102244. _super.prototype.dispose.call(this);
  102245. };
  102246. /**
  102247. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  102248. * @param mesh The mesh to replace the default mesh of the gizmo
  102249. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  102250. */
  102251. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  102252. var _this = this;
  102253. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  102254. _super.prototype.setCustomMesh.call(this, mesh);
  102255. if (useGizmoMaterial) {
  102256. this._rootMesh.getChildMeshes().forEach(function (m) {
  102257. m.material = _this._coloredMaterial;
  102258. if (m.color) {
  102259. m.color = _this._coloredMaterial.emissiveColor;
  102260. }
  102261. });
  102262. this._customMeshSet = false;
  102263. }
  102264. };
  102265. return AxisScaleGizmo;
  102266. }(BABYLON.Gizmo));
  102267. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  102268. })(BABYLON || (BABYLON = {}));
  102269. //# sourceMappingURL=axisScaleGizmo.js.map
  102270. var BABYLON;
  102271. (function (BABYLON) {
  102272. /**
  102273. * Single plane rotation gizmo
  102274. */
  102275. var PlaneRotationGizmo = /** @class */ (function (_super) {
  102276. __extends(PlaneRotationGizmo, _super);
  102277. /**
  102278. * Creates a PlaneRotationGizmo
  102279. * @param gizmoLayer The utility layer the gizmo will be added to
  102280. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  102281. * @param color The color of the gizmo
  102282. * @param tessellation Amount of tessellation to be used when creating rotation circles
  102283. */
  102284. function PlaneRotationGizmo(planeNormal, color, gizmoLayer, tessellation) {
  102285. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  102286. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102287. if (tessellation === void 0) { tessellation = 32; }
  102288. var _this = _super.call(this, gizmoLayer) || this;
  102289. _this._pointerObserver = null;
  102290. /**
  102291. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  102292. */
  102293. _this.snapDistance = 0;
  102294. /**
  102295. * Event that fires each time the gizmo snaps to a new location.
  102296. * * snapDistance is the the change in distance
  102297. */
  102298. _this.onSnapObservable = new BABYLON.Observable();
  102299. // Create Material
  102300. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102301. coloredMaterial.disableLighting = true;
  102302. coloredMaterial.emissiveColor = color;
  102303. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102304. hoverMaterial.disableLighting = true;
  102305. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  102306. // Build mesh on root node
  102307. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102308. // Create circle out of lines
  102309. var radius = 0.8;
  102310. var points = new Array();
  102311. for (var i = 0; i < tessellation; i++) {
  102312. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  102313. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  102314. }
  102315. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  102316. rotationMesh.color = coloredMaterial.emissiveColor;
  102317. // Position arrow pointing in its drag axis
  102318. rotationMesh.scaling.scaleInPlace(0.26);
  102319. rotationMesh.material = coloredMaterial;
  102320. rotationMesh.rotation.x = Math.PI / 2;
  102321. parentMesh.addChild(rotationMesh);
  102322. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  102323. _this._rootMesh.addChild(parentMesh);
  102324. parentMesh.scaling.scaleInPlace(1 / 3);
  102325. // Add drag behavior to handle events when the gizmo is dragged
  102326. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  102327. _this.dragBehavior.moveAttached = false;
  102328. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  102329. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  102330. _this._rootMesh.addBehavior(_this.dragBehavior);
  102331. var lastDragPosition = new BABYLON.Vector3();
  102332. _this.dragBehavior.onDragStartObservable.add(function (e) {
  102333. if (_this.attachedMesh) {
  102334. lastDragPosition.copyFrom(e.dragPlanePoint);
  102335. }
  102336. });
  102337. var rotationMatrix = new BABYLON.Matrix();
  102338. var planeNormalTowardsCamera = new BABYLON.Vector3();
  102339. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  102340. var tmpSnapEvent = { snapDistance: 0 };
  102341. var currentSnapDragDistance = 0;
  102342. var tmpMatrix = new BABYLON.Matrix();
  102343. var tmpVector = new BABYLON.Vector3();
  102344. var amountToRotate = new BABYLON.Quaternion();
  102345. _this.dragBehavior.onDragObservable.add(function (event) {
  102346. if (_this.attachedMesh) {
  102347. if (!_this.attachedMesh.rotationQuaternion) {
  102348. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  102349. }
  102350. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  102351. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  102352. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  102353. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  102354. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  102355. var angle = Math.atan2(cross.length(), dot);
  102356. planeNormalTowardsCamera.copyFrom(planeNormal);
  102357. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  102358. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  102359. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  102360. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  102361. }
  102362. // Flip up vector depending on which side the camera is on
  102363. if (gizmoLayer.utilityLayerScene.activeCamera) {
  102364. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  102365. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  102366. planeNormalTowardsCamera.scaleInPlace(-1);
  102367. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  102368. }
  102369. }
  102370. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  102371. if (halfCircleSide) {
  102372. angle = -angle;
  102373. }
  102374. // Snapping logic
  102375. var snapped = false;
  102376. if (_this.snapDistance != 0) {
  102377. currentSnapDragDistance += angle;
  102378. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  102379. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  102380. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  102381. angle = _this.snapDistance * dragSteps;
  102382. snapped = true;
  102383. }
  102384. else {
  102385. angle = 0;
  102386. }
  102387. }
  102388. // If the mesh has a parent, convert needed world rotation to local rotation
  102389. tmpMatrix.reset();
  102390. if (_this.attachedMesh.parent) {
  102391. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  102392. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  102393. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  102394. }
  102395. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  102396. var quaternionCoefficient = Math.sin(angle / 2);
  102397. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  102398. // 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
  102399. if (tmpMatrix.determinant() > 0) {
  102400. amountToRotate.toEulerAnglesToRef(tmpVector);
  102401. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  102402. }
  102403. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  102404. // Rotate selected mesh quaternion over fixed axis
  102405. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  102406. }
  102407. else {
  102408. // Rotate selected mesh quaternion over rotated axis
  102409. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  102410. }
  102411. lastDragPosition.copyFrom(event.dragPlanePoint);
  102412. if (snapped) {
  102413. tmpSnapEvent.snapDistance = angle;
  102414. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  102415. }
  102416. }
  102417. });
  102418. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  102419. if (_this._customMeshSet) {
  102420. return;
  102421. }
  102422. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  102423. var material = isHovered ? hoverMaterial : coloredMaterial;
  102424. _this._rootMesh.getChildMeshes().forEach(function (m) {
  102425. m.material = material;
  102426. if (m.color) {
  102427. m.color = material.emissiveColor;
  102428. }
  102429. });
  102430. });
  102431. return _this;
  102432. }
  102433. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  102434. if (this.dragBehavior) {
  102435. this.dragBehavior.enabled = value ? true : false;
  102436. }
  102437. };
  102438. /**
  102439. * Disposes of the gizmo
  102440. */
  102441. PlaneRotationGizmo.prototype.dispose = function () {
  102442. this.onSnapObservable.clear();
  102443. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  102444. this.dragBehavior.detach();
  102445. _super.prototype.dispose.call(this);
  102446. };
  102447. return PlaneRotationGizmo;
  102448. }(BABYLON.Gizmo));
  102449. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  102450. })(BABYLON || (BABYLON = {}));
  102451. //# sourceMappingURL=planeRotationGizmo.js.map
  102452. var BABYLON;
  102453. (function (BABYLON) {
  102454. /**
  102455. * Gizmo that enables dragging a mesh along 3 axis
  102456. */
  102457. var PositionGizmo = /** @class */ (function (_super) {
  102458. __extends(PositionGizmo, _super);
  102459. /**
  102460. * Creates a PositionGizmo
  102461. * @param gizmoLayer The utility layer the gizmo will be added to
  102462. */
  102463. function PositionGizmo(gizmoLayer) {
  102464. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102465. var _this = _super.call(this, gizmoLayer) || this;
  102466. /** Fires an event when any of it's sub gizmos are dragged */
  102467. _this.onDragStartObservable = new BABYLON.Observable();
  102468. /** Fires an event when any of it's sub gizmos are released from dragging */
  102469. _this.onDragEndObservable = new BABYLON.Observable();
  102470. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  102471. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  102472. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  102473. // Relay drag events
  102474. [_this.xGizmo, _this.yGizmo, _this.zGizmo].forEach(function (gizmo) {
  102475. gizmo.dragBehavior.onDragStartObservable.add(function () {
  102476. _this.onDragStartObservable.notifyObservers({});
  102477. });
  102478. gizmo.dragBehavior.onDragEndObservable.add(function () {
  102479. _this.onDragEndObservable.notifyObservers({});
  102480. });
  102481. });
  102482. _this.attachedMesh = null;
  102483. return _this;
  102484. }
  102485. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  102486. set: function (mesh) {
  102487. if (this.xGizmo) {
  102488. this.xGizmo.attachedMesh = mesh;
  102489. this.yGizmo.attachedMesh = mesh;
  102490. this.zGizmo.attachedMesh = mesh;
  102491. }
  102492. },
  102493. enumerable: true,
  102494. configurable: true
  102495. });
  102496. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  102497. get: function () {
  102498. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  102499. },
  102500. set: function (value) {
  102501. if (this.xGizmo) {
  102502. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102503. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102504. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102505. }
  102506. },
  102507. enumerable: true,
  102508. configurable: true
  102509. });
  102510. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  102511. get: function () {
  102512. return this.xGizmo.snapDistance;
  102513. },
  102514. /**
  102515. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  102516. */
  102517. set: function (value) {
  102518. if (this.xGizmo) {
  102519. this.xGizmo.snapDistance = value;
  102520. this.yGizmo.snapDistance = value;
  102521. this.zGizmo.snapDistance = value;
  102522. }
  102523. },
  102524. enumerable: true,
  102525. configurable: true
  102526. });
  102527. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  102528. get: function () {
  102529. return this.xGizmo.scaleRatio;
  102530. },
  102531. /**
  102532. * Ratio for the scale of the gizmo (Default: 1)
  102533. */
  102534. set: function (value) {
  102535. if (this.xGizmo) {
  102536. this.xGizmo.scaleRatio = value;
  102537. this.yGizmo.scaleRatio = value;
  102538. this.zGizmo.scaleRatio = value;
  102539. }
  102540. },
  102541. enumerable: true,
  102542. configurable: true
  102543. });
  102544. /**
  102545. * Disposes of the gizmo
  102546. */
  102547. PositionGizmo.prototype.dispose = function () {
  102548. this.xGizmo.dispose();
  102549. this.yGizmo.dispose();
  102550. this.zGizmo.dispose();
  102551. this.onDragStartObservable.clear();
  102552. this.onDragEndObservable.clear();
  102553. };
  102554. /**
  102555. * CustomMeshes are not supported by this gizmo
  102556. * @param mesh The mesh to replace the default mesh of the gizmo
  102557. */
  102558. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  102559. 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)");
  102560. };
  102561. return PositionGizmo;
  102562. }(BABYLON.Gizmo));
  102563. BABYLON.PositionGizmo = PositionGizmo;
  102564. })(BABYLON || (BABYLON = {}));
  102565. //# sourceMappingURL=positionGizmo.js.map
  102566. var BABYLON;
  102567. (function (BABYLON) {
  102568. /**
  102569. * Gizmo that enables rotating a mesh along 3 axis
  102570. */
  102571. var RotationGizmo = /** @class */ (function (_super) {
  102572. __extends(RotationGizmo, _super);
  102573. /**
  102574. * Creates a RotationGizmo
  102575. * @param gizmoLayer The utility layer the gizmo will be added to
  102576. * @param tessellation Amount of tessellation to be used when creating rotation circles
  102577. */
  102578. function RotationGizmo(gizmoLayer, tessellation) {
  102579. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102580. if (tessellation === void 0) { tessellation = 32; }
  102581. var _this = _super.call(this, gizmoLayer) || this;
  102582. /** Fires an event when any of it's sub gizmos are dragged */
  102583. _this.onDragStartObservable = new BABYLON.Observable();
  102584. /** Fires an event when any of it's sub gizmos are released from dragging */
  102585. _this.onDragEndObservable = new BABYLON.Observable();
  102586. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer, tessellation);
  102587. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer, tessellation);
  102588. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer, tessellation);
  102589. // Relay drag events
  102590. [_this.xGizmo, _this.yGizmo, _this.zGizmo].forEach(function (gizmo) {
  102591. gizmo.dragBehavior.onDragStartObservable.add(function () {
  102592. _this.onDragStartObservable.notifyObservers({});
  102593. });
  102594. gizmo.dragBehavior.onDragEndObservable.add(function () {
  102595. _this.onDragEndObservable.notifyObservers({});
  102596. });
  102597. });
  102598. _this.attachedMesh = null;
  102599. return _this;
  102600. }
  102601. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  102602. set: function (mesh) {
  102603. if (this.xGizmo) {
  102604. this.xGizmo.attachedMesh = mesh;
  102605. this.yGizmo.attachedMesh = mesh;
  102606. this.zGizmo.attachedMesh = mesh;
  102607. }
  102608. },
  102609. enumerable: true,
  102610. configurable: true
  102611. });
  102612. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  102613. get: function () {
  102614. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  102615. },
  102616. set: function (value) {
  102617. if (this.xGizmo) {
  102618. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102619. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102620. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102621. }
  102622. },
  102623. enumerable: true,
  102624. configurable: true
  102625. });
  102626. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  102627. get: function () {
  102628. return this.xGizmo.snapDistance;
  102629. },
  102630. /**
  102631. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  102632. */
  102633. set: function (value) {
  102634. if (this.xGizmo) {
  102635. this.xGizmo.snapDistance = value;
  102636. this.yGizmo.snapDistance = value;
  102637. this.zGizmo.snapDistance = value;
  102638. }
  102639. },
  102640. enumerable: true,
  102641. configurable: true
  102642. });
  102643. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  102644. get: function () {
  102645. return this.xGizmo.scaleRatio;
  102646. },
  102647. /**
  102648. * Ratio for the scale of the gizmo (Default: 1)
  102649. */
  102650. set: function (value) {
  102651. if (this.xGizmo) {
  102652. this.xGizmo.scaleRatio = value;
  102653. this.yGizmo.scaleRatio = value;
  102654. this.zGizmo.scaleRatio = value;
  102655. }
  102656. },
  102657. enumerable: true,
  102658. configurable: true
  102659. });
  102660. /**
  102661. * Disposes of the gizmo
  102662. */
  102663. RotationGizmo.prototype.dispose = function () {
  102664. this.xGizmo.dispose();
  102665. this.yGizmo.dispose();
  102666. this.zGizmo.dispose();
  102667. this.onDragStartObservable.clear();
  102668. this.onDragEndObservable.clear();
  102669. };
  102670. /**
  102671. * CustomMeshes are not supported by this gizmo
  102672. * @param mesh The mesh to replace the default mesh of the gizmo
  102673. */
  102674. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  102675. 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)");
  102676. };
  102677. return RotationGizmo;
  102678. }(BABYLON.Gizmo));
  102679. BABYLON.RotationGizmo = RotationGizmo;
  102680. })(BABYLON || (BABYLON = {}));
  102681. //# sourceMappingURL=rotationGizmo.js.map
  102682. var BABYLON;
  102683. (function (BABYLON) {
  102684. /**
  102685. * Gizmo that enables scaling a mesh along 3 axis
  102686. */
  102687. var ScaleGizmo = /** @class */ (function (_super) {
  102688. __extends(ScaleGizmo, _super);
  102689. /**
  102690. * Creates a ScaleGizmo
  102691. * @param gizmoLayer The utility layer the gizmo will be added to
  102692. */
  102693. function ScaleGizmo(gizmoLayer) {
  102694. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  102695. var _this = _super.call(this, gizmoLayer) || this;
  102696. /** Fires an event when any of it's sub gizmos are dragged */
  102697. _this.onDragStartObservable = new BABYLON.Observable();
  102698. /** Fires an event when any of it's sub gizmos are released from dragging */
  102699. _this.onDragEndObservable = new BABYLON.Observable();
  102700. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  102701. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  102702. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  102703. // Create uniform scale gizmo
  102704. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  102705. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  102706. _this.uniformScaleGizmo.uniformScaling = true;
  102707. var uniformScalingMesh = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  102708. uniformScalingMesh.scaling.scaleInPlace(0.02);
  102709. uniformScalingMesh.visibility = 0;
  102710. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  102711. octahedron.scaling.scaleInPlace(0.007);
  102712. uniformScalingMesh.addChild(octahedron);
  102713. _this.uniformScaleGizmo.setCustomMesh(uniformScalingMesh, true);
  102714. // Relay drag events
  102715. [_this.xGizmo, _this.yGizmo, _this.zGizmo, _this.uniformScaleGizmo].forEach(function (gizmo) {
  102716. gizmo.dragBehavior.onDragStartObservable.add(function () {
  102717. _this.onDragStartObservable.notifyObservers({});
  102718. });
  102719. gizmo.dragBehavior.onDragEndObservable.add(function () {
  102720. _this.onDragEndObservable.notifyObservers({});
  102721. });
  102722. });
  102723. _this.attachedMesh = null;
  102724. return _this;
  102725. }
  102726. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  102727. set: function (mesh) {
  102728. if (this.xGizmo) {
  102729. this.xGizmo.attachedMesh = mesh;
  102730. this.yGizmo.attachedMesh = mesh;
  102731. this.zGizmo.attachedMesh = mesh;
  102732. this.uniformScaleGizmo.attachedMesh = mesh;
  102733. }
  102734. },
  102735. enumerable: true,
  102736. configurable: true
  102737. });
  102738. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  102739. get: function () {
  102740. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  102741. },
  102742. set: function (value) {
  102743. if (!value) {
  102744. BABYLON.Tools.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.");
  102745. }
  102746. if (this.xGizmo) {
  102747. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102748. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102749. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  102750. }
  102751. },
  102752. enumerable: true,
  102753. configurable: true
  102754. });
  102755. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  102756. get: function () {
  102757. return this.xGizmo.snapDistance;
  102758. },
  102759. /**
  102760. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  102761. */
  102762. set: function (value) {
  102763. if (this.xGizmo) {
  102764. this.xGizmo.snapDistance = value;
  102765. this.yGizmo.snapDistance = value;
  102766. this.zGizmo.snapDistance = value;
  102767. this.uniformScaleGizmo.snapDistance = value;
  102768. }
  102769. },
  102770. enumerable: true,
  102771. configurable: true
  102772. });
  102773. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  102774. get: function () {
  102775. return this.xGizmo.scaleRatio;
  102776. },
  102777. /**
  102778. * Ratio for the scale of the gizmo (Default: 1)
  102779. */
  102780. set: function (value) {
  102781. if (this.xGizmo) {
  102782. this.xGizmo.scaleRatio = value;
  102783. this.yGizmo.scaleRatio = value;
  102784. this.zGizmo.scaleRatio = value;
  102785. this.uniformScaleGizmo.scaleRatio = value;
  102786. }
  102787. },
  102788. enumerable: true,
  102789. configurable: true
  102790. });
  102791. /**
  102792. * Disposes of the gizmo
  102793. */
  102794. ScaleGizmo.prototype.dispose = function () {
  102795. this.xGizmo.dispose();
  102796. this.yGizmo.dispose();
  102797. this.zGizmo.dispose();
  102798. this.uniformScaleGizmo.dispose();
  102799. this.onDragStartObservable.clear();
  102800. this.onDragEndObservable.clear();
  102801. };
  102802. return ScaleGizmo;
  102803. }(BABYLON.Gizmo));
  102804. BABYLON.ScaleGizmo = ScaleGizmo;
  102805. })(BABYLON || (BABYLON = {}));
  102806. //# sourceMappingURL=scaleGizmo.js.map
  102807. var BABYLON;
  102808. (function (BABYLON) {
  102809. /**
  102810. * Bounding box gizmo
  102811. */
  102812. var BoundingBoxGizmo = /** @class */ (function (_super) {
  102813. __extends(BoundingBoxGizmo, _super);
  102814. /**
  102815. * Creates an BoundingBoxGizmo
  102816. * @param gizmoLayer The utility layer the gizmo will be added to
  102817. * @param color The color of the gizmo
  102818. */
  102819. function BoundingBoxGizmo(color, gizmoLayer) {
  102820. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  102821. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  102822. var _this = _super.call(this, gizmoLayer) || this;
  102823. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  102824. _this._renderObserver = null;
  102825. _this._pointerObserver = null;
  102826. _this._scaleDragSpeed = 0.2;
  102827. _this._tmpQuaternion = new BABYLON.Quaternion();
  102828. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  102829. _this._tmpRotationMatrix = new BABYLON.Matrix();
  102830. /**
  102831. * 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)
  102832. */
  102833. _this.ignoreChildren = false;
  102834. /**
  102835. * 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)
  102836. */
  102837. _this.includeChildPredicate = null;
  102838. /**
  102839. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  102840. */
  102841. _this.rotationSphereSize = 0.1;
  102842. /**
  102843. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  102844. */
  102845. _this.scaleBoxSize = 0.1;
  102846. /**
  102847. * 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)
  102848. */
  102849. _this.fixedDragMeshScreenSize = false;
  102850. /**
  102851. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  102852. */
  102853. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  102854. /**
  102855. * Fired when a rotation sphere or scale box is dragged
  102856. */
  102857. _this.onDragStartObservable = new BABYLON.Observable();
  102858. /**
  102859. * Fired when a scale box is dragged
  102860. */
  102861. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  102862. /**
  102863. * Fired when a scale box drag is ended
  102864. */
  102865. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  102866. /**
  102867. * Fired when a rotation sphere is dragged
  102868. */
  102869. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  102870. /**
  102871. * Fired when a rotation sphere drag is ended
  102872. */
  102873. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  102874. /**
  102875. * 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)
  102876. */
  102877. _this.scalePivot = null;
  102878. _this._existingMeshScale = new BABYLON.Vector3();
  102879. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  102880. _this._updateScale = false;
  102881. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  102882. // Create Materials
  102883. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102884. coloredMaterial.disableLighting = true;
  102885. coloredMaterial.emissiveColor = color;
  102886. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  102887. hoverColoredMaterial.disableLighting = true;
  102888. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  102889. // Build bounding box out of lines
  102890. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102891. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  102892. var lines = [];
  102893. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  102894. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  102895. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  102896. 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));
  102897. 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));
  102898. 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));
  102899. 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));
  102900. 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));
  102901. 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));
  102902. 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));
  102903. 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));
  102904. 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));
  102905. lines.forEach(function (l) {
  102906. l.color = color;
  102907. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  102908. l.isPickable = false;
  102909. _this._lineBoundingBox.addChild(l);
  102910. });
  102911. _this._rootMesh.addChild(_this._lineBoundingBox);
  102912. // Create rotation spheres
  102913. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102914. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  102915. var _loop_1 = function (i_1) {
  102916. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  102917. sphere.rotationQuaternion = new BABYLON.Quaternion();
  102918. sphere.material = coloredMaterial;
  102919. // Drag behavior
  102920. _dragBehavior = new BABYLON.PointerDragBehavior({});
  102921. _dragBehavior.moveAttached = false;
  102922. _dragBehavior.updateDragPlane = false;
  102923. sphere.addBehavior(_dragBehavior);
  102924. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  102925. var totalTurnAmountOfDrag = 0;
  102926. _dragBehavior.onDragStartObservable.add(function (event) {
  102927. startingTurnDirection.copyFrom(sphere.forward);
  102928. totalTurnAmountOfDrag = 0;
  102929. });
  102930. _dragBehavior.onDragObservable.add(function (event) {
  102931. _this.onRotationSphereDragObservable.notifyObservers({});
  102932. if (_this.attachedMesh) {
  102933. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  102934. var worldDragDirection = startingTurnDirection;
  102935. // Project the world right on to the drag plane
  102936. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  102937. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  102938. // project drag delta on to the resulting drag axis and rotate based on that
  102939. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  102940. // Make rotation relative to size of mesh.
  102941. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  102942. // Rotate based on axis
  102943. if (!_this.attachedMesh.rotationQuaternion) {
  102944. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  102945. }
  102946. if (!_this._anchorMesh.rotationQuaternion) {
  102947. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  102948. }
  102949. // Do not allow the object to turn more than a full circle
  102950. totalTurnAmountOfDrag += projectDist;
  102951. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  102952. if (i_1 >= 8) {
  102953. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  102954. }
  102955. else if (i_1 >= 4) {
  102956. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  102957. }
  102958. else {
  102959. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  102960. }
  102961. // Rotate around center of bounding box
  102962. _this._anchorMesh.addChild(_this.attachedMesh);
  102963. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  102964. _this._anchorMesh.removeChild(_this.attachedMesh);
  102965. }
  102966. _this.updateBoundingBox();
  102967. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  102968. }
  102969. });
  102970. // Selection/deselection
  102971. _dragBehavior.onDragStartObservable.add(function () {
  102972. _this.onDragStartObservable.notifyObservers({});
  102973. _this._selectNode(sphere);
  102974. });
  102975. _dragBehavior.onDragEndObservable.add(function () {
  102976. _this.onRotationSphereDragEndObservable.notifyObservers({});
  102977. _this._selectNode(null);
  102978. });
  102979. this_1._rotateSpheresParent.addChild(sphere);
  102980. };
  102981. var this_1 = this, _dragBehavior;
  102982. for (var i_1 = 0; i_1 < 12; i_1++) {
  102983. _loop_1(i_1);
  102984. }
  102985. _this._rootMesh.addChild(_this._rotateSpheresParent);
  102986. // Create scale cubes
  102987. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  102988. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  102989. for (var i = 0; i < 2; i++) {
  102990. for (var j = 0; j < 2; j++) {
  102991. var _loop_2 = function () {
  102992. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  102993. box.material = coloredMaterial;
  102994. // Dragging logic
  102995. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  102996. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  102997. _dragBehavior.moveAttached = false;
  102998. box.addBehavior(_dragBehavior);
  102999. _dragBehavior.onDragObservable.add(function (event) {
  103000. _this.onScaleBoxDragObservable.notifyObservers({});
  103001. if (_this.attachedMesh) {
  103002. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  103003. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  103004. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  103005. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  103006. _this.updateBoundingBox();
  103007. if (_this.scalePivot) {
  103008. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  103009. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  103010. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  103011. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  103012. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  103013. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  103014. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  103015. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  103016. }
  103017. else {
  103018. // Scale from the position of the opposite corner
  103019. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  103020. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  103021. }
  103022. _this._anchorMesh.addChild(_this.attachedMesh);
  103023. _this._anchorMesh.scaling.addInPlace(deltaScale);
  103024. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  103025. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  103026. }
  103027. _this._anchorMesh.removeChild(_this.attachedMesh);
  103028. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  103029. }
  103030. });
  103031. // Selection/deselection
  103032. _dragBehavior.onDragStartObservable.add(function () {
  103033. _this.onDragStartObservable.notifyObservers({});
  103034. _this._selectNode(box);
  103035. });
  103036. _dragBehavior.onDragEndObservable.add(function () {
  103037. _this.onScaleBoxDragEndObservable.notifyObservers({});
  103038. _this._selectNode(null);
  103039. });
  103040. this_2._scaleBoxesParent.addChild(box);
  103041. };
  103042. var this_2 = this, _dragBehavior;
  103043. for (var k = 0; k < 2; k++) {
  103044. _loop_2();
  103045. }
  103046. }
  103047. }
  103048. _this._rootMesh.addChild(_this._scaleBoxesParent);
  103049. // Hover color change
  103050. var pointerIds = new Array();
  103051. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  103052. if (!pointerIds[pointerInfo.event.pointerId]) {
  103053. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  103054. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  103055. pointerIds[pointerInfo.event.pointerId] = mesh;
  103056. mesh.material = hoverColoredMaterial;
  103057. }
  103058. });
  103059. }
  103060. else {
  103061. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  103062. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  103063. delete pointerIds[pointerInfo.event.pointerId];
  103064. }
  103065. }
  103066. });
  103067. // Update bounding box positions
  103068. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  103069. // Only update the bouding box if scaling has changed
  103070. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  103071. _this.updateBoundingBox();
  103072. }
  103073. });
  103074. _this.updateBoundingBox();
  103075. return _this;
  103076. }
  103077. /** @hidden */
  103078. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  103079. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  103080. // Save old pivot and set pivot to 0,0,0
  103081. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  103082. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  103083. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  103084. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  103085. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  103086. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  103087. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  103088. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  103089. }
  103090. }
  103091. BoundingBoxGizmo._PivotCached++;
  103092. };
  103093. /** @hidden */
  103094. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  103095. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  103096. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  103097. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  103098. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  103099. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  103100. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  103101. }
  103102. this._PivotCached--;
  103103. };
  103104. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  103105. if (value) {
  103106. // Reset anchor mesh to match attached mesh's scale
  103107. // This is needed to avoid invalid box/sphere position on first drag
  103108. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  103109. this._anchorMesh.addChild(value);
  103110. this._anchorMesh.removeChild(value);
  103111. BoundingBoxGizmo._RestorePivotPoint(value);
  103112. this.updateBoundingBox();
  103113. }
  103114. };
  103115. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  103116. this._rotateSpheresParent.getChildMeshes()
  103117. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  103118. m.isVisible = (!selectedMesh || m == selectedMesh);
  103119. });
  103120. };
  103121. /**
  103122. * Updates the bounding box information for the Gizmo
  103123. */
  103124. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  103125. if (this.attachedMesh) {
  103126. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  103127. this._update();
  103128. // Rotate based on axis
  103129. if (!this.attachedMesh.rotationQuaternion) {
  103130. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  103131. }
  103132. if (!this._anchorMesh.rotationQuaternion) {
  103133. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  103134. }
  103135. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  103136. // Store original position and reset mesh to origin before computing the bounding box
  103137. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  103138. this._tmpVector.copyFrom(this.attachedMesh.position);
  103139. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  103140. this.attachedMesh.position.set(0, 0, 0);
  103141. // Update bounding dimensions/positions
  103142. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  103143. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  103144. // Update gizmo to match bounding box scaling and rotation
  103145. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  103146. 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);
  103147. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  103148. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  103149. this._lineBoundingBox.computeWorldMatrix();
  103150. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  103151. // restore position/rotation values
  103152. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  103153. this.attachedMesh.position.copyFrom(this._tmpVector);
  103154. }
  103155. // Update rotation sphere locations
  103156. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  103157. for (var i = 0; i < 3; i++) {
  103158. for (var j = 0; j < 2; j++) {
  103159. for (var k = 0; k < 2; k++) {
  103160. var index = ((i * 4) + (j * 2)) + k;
  103161. if (i == 0) {
  103162. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  103163. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  103164. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  103165. }
  103166. if (i == 1) {
  103167. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  103168. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  103169. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  103170. }
  103171. if (i == 2) {
  103172. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  103173. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  103174. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  103175. }
  103176. if (this.fixedDragMeshScreenSize) {
  103177. this._rootMesh.computeWorldMatrix();
  103178. this._rotateSpheresParent.computeWorldMatrix();
  103179. rotateSpheres[index].computeWorldMatrix();
  103180. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  103181. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  103182. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  103183. }
  103184. else {
  103185. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  103186. }
  103187. }
  103188. }
  103189. }
  103190. // Update scale box locations
  103191. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  103192. for (var i = 0; i < 2; i++) {
  103193. for (var j = 0; j < 2; j++) {
  103194. for (var k = 0; k < 2; k++) {
  103195. var index = ((i * 4) + (j * 2)) + k;
  103196. if (scaleBoxes[index]) {
  103197. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  103198. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  103199. if (this.fixedDragMeshScreenSize) {
  103200. this._rootMesh.computeWorldMatrix();
  103201. this._scaleBoxesParent.computeWorldMatrix();
  103202. scaleBoxes[index].computeWorldMatrix();
  103203. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  103204. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  103205. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  103206. }
  103207. else {
  103208. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  103209. }
  103210. }
  103211. }
  103212. }
  103213. }
  103214. if (this.attachedMesh) {
  103215. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  103216. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  103217. }
  103218. };
  103219. /**
  103220. * Enables rotation on the specified axis and disables rotation on the others
  103221. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  103222. */
  103223. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  103224. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  103225. if (i < 4) {
  103226. m.setEnabled(axis.indexOf("x") != -1);
  103227. }
  103228. else if (i < 8) {
  103229. m.setEnabled(axis.indexOf("y") != -1);
  103230. }
  103231. else {
  103232. m.setEnabled(axis.indexOf("z") != -1);
  103233. }
  103234. });
  103235. };
  103236. /**
  103237. * Disposes of the gizmo
  103238. */
  103239. BoundingBoxGizmo.prototype.dispose = function () {
  103240. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  103241. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  103242. this._lineBoundingBox.dispose();
  103243. this._rotateSpheresParent.dispose();
  103244. this._scaleBoxesParent.dispose();
  103245. _super.prototype.dispose.call(this);
  103246. };
  103247. /**
  103248. * 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)
  103249. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  103250. * @returns the bounding box mesh with the passed in mesh as a child
  103251. */
  103252. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  103253. var makeNotPickable = function (root) {
  103254. root.isPickable = false;
  103255. root.getChildMeshes().forEach(function (c) {
  103256. makeNotPickable(c);
  103257. });
  103258. };
  103259. makeNotPickable(mesh);
  103260. // Reset position to get boudning box from origin with no rotation
  103261. if (!mesh.rotationQuaternion) {
  103262. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  103263. }
  103264. var oldPos = mesh.position.clone();
  103265. var oldRot = mesh.rotationQuaternion.clone();
  103266. mesh.rotationQuaternion.set(0, 0, 0, 1);
  103267. mesh.position.set(0, 0, 0);
  103268. // Update bounding dimensions/positions
  103269. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  103270. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  103271. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  103272. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  103273. // Restore original positions
  103274. mesh.addChild(box);
  103275. mesh.rotationQuaternion.copyFrom(oldRot);
  103276. mesh.position.copyFrom(oldPos);
  103277. // Reverse parenting
  103278. mesh.removeChild(box);
  103279. box.addChild(mesh);
  103280. box.visibility = 0;
  103281. return box;
  103282. };
  103283. /**
  103284. * CustomMeshes are not supported by this gizmo
  103285. * @param mesh The mesh to replace the default mesh of the gizmo
  103286. */
  103287. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  103288. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  103289. };
  103290. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  103291. // store/remove pivot point should only be applied during their outermost calls
  103292. BoundingBoxGizmo._PivotCached = 0;
  103293. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  103294. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  103295. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  103296. return BoundingBoxGizmo;
  103297. }(BABYLON.Gizmo));
  103298. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  103299. })(BABYLON || (BABYLON = {}));
  103300. //# sourceMappingURL=boundingBoxGizmo.js.map
  103301. var BABYLON;
  103302. (function (BABYLON) {
  103303. /**
  103304. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  103305. */
  103306. var GizmoManager = /** @class */ (function () {
  103307. /**
  103308. * Instatiates a gizmo manager
  103309. * @param scene the scene to overlay the gizmos on top of
  103310. */
  103311. function GizmoManager(scene) {
  103312. var _this = this;
  103313. this.scene = scene;
  103314. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  103315. this._pointerObserver = null;
  103316. this._attachedMesh = null;
  103317. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  103318. /**
  103319. * When bounding box gizmo is enabled, this can be used to track drag/end events
  103320. */
  103321. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  103322. /**
  103323. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  103324. */
  103325. this.attachableMeshes = null;
  103326. /**
  103327. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  103328. */
  103329. this.usePointerToAttachGizmos = true;
  103330. this._defaultKeepDepthUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  103331. this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  103332. this._defaultUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  103333. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  103334. // Instatiate/dispose gizmos based on pointer actions
  103335. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  103336. if (!_this.usePointerToAttachGizmos) {
  103337. return;
  103338. }
  103339. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  103340. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  103341. var node = pointerInfo.pickInfo.pickedMesh;
  103342. if (_this.attachableMeshes == null) {
  103343. // Attach to the most parent node
  103344. while (node && node.parent != null) {
  103345. node = node.parent;
  103346. }
  103347. }
  103348. else {
  103349. // Attach to the parent node that is an attachableMesh
  103350. var found = false;
  103351. _this.attachableMeshes.forEach(function (mesh) {
  103352. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  103353. node = mesh;
  103354. found = true;
  103355. }
  103356. });
  103357. if (!found) {
  103358. node = null;
  103359. }
  103360. }
  103361. if (node instanceof BABYLON.AbstractMesh) {
  103362. if (_this._attachedMesh != node) {
  103363. _this.attachToMesh(node);
  103364. }
  103365. }
  103366. else {
  103367. _this.attachToMesh(null);
  103368. }
  103369. }
  103370. else {
  103371. _this.attachToMesh(null);
  103372. }
  103373. }
  103374. });
  103375. }
  103376. /**
  103377. * Attaches a set of gizmos to the specified mesh
  103378. * @param mesh The mesh the gizmo's should be attached to
  103379. */
  103380. GizmoManager.prototype.attachToMesh = function (mesh) {
  103381. if (this._attachedMesh) {
  103382. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  103383. }
  103384. this._attachedMesh = mesh;
  103385. for (var key in this.gizmos) {
  103386. var gizmo = (this.gizmos[key]);
  103387. if (gizmo && this._gizmosEnabled[key]) {
  103388. gizmo.attachedMesh = mesh;
  103389. }
  103390. }
  103391. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  103392. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  103393. }
  103394. };
  103395. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  103396. get: function () {
  103397. return this._gizmosEnabled.positionGizmo;
  103398. },
  103399. /**
  103400. * If the position gizmo is enabled
  103401. */
  103402. set: function (value) {
  103403. if (value) {
  103404. if (!this.gizmos.positionGizmo) {
  103405. this.gizmos.positionGizmo = new BABYLON.PositionGizmo(this._defaultUtilityLayer);
  103406. }
  103407. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  103408. }
  103409. else if (this.gizmos.positionGizmo) {
  103410. this.gizmos.positionGizmo.attachedMesh = null;
  103411. }
  103412. this._gizmosEnabled.positionGizmo = value;
  103413. },
  103414. enumerable: true,
  103415. configurable: true
  103416. });
  103417. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  103418. get: function () {
  103419. return this._gizmosEnabled.rotationGizmo;
  103420. },
  103421. /**
  103422. * If the rotation gizmo is enabled
  103423. */
  103424. set: function (value) {
  103425. if (value) {
  103426. if (!this.gizmos.rotationGizmo) {
  103427. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo(this._defaultUtilityLayer);
  103428. }
  103429. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  103430. }
  103431. else if (this.gizmos.rotationGizmo) {
  103432. this.gizmos.rotationGizmo.attachedMesh = null;
  103433. }
  103434. this._gizmosEnabled.rotationGizmo = value;
  103435. },
  103436. enumerable: true,
  103437. configurable: true
  103438. });
  103439. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  103440. get: function () {
  103441. return this._gizmosEnabled.scaleGizmo;
  103442. },
  103443. /**
  103444. * If the scale gizmo is enabled
  103445. */
  103446. set: function (value) {
  103447. if (value) {
  103448. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo(this._defaultUtilityLayer);
  103449. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  103450. }
  103451. else if (this.gizmos.scaleGizmo) {
  103452. this.gizmos.scaleGizmo.attachedMesh = null;
  103453. }
  103454. this._gizmosEnabled.scaleGizmo = value;
  103455. },
  103456. enumerable: true,
  103457. configurable: true
  103458. });
  103459. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  103460. get: function () {
  103461. return this._gizmosEnabled.boundingBoxGizmo;
  103462. },
  103463. /**
  103464. * If the boundingBox gizmo is enabled
  103465. */
  103466. set: function (value) {
  103467. if (value) {
  103468. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor, this._defaultKeepDepthUtilityLayer);
  103469. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  103470. if (this._attachedMesh) {
  103471. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  103472. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  103473. }
  103474. }
  103475. else if (this.gizmos.boundingBoxGizmo) {
  103476. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  103477. }
  103478. this._gizmosEnabled.boundingBoxGizmo = value;
  103479. },
  103480. enumerable: true,
  103481. configurable: true
  103482. });
  103483. /**
  103484. * Disposes of the gizmo manager
  103485. */
  103486. GizmoManager.prototype.dispose = function () {
  103487. this.scene.onPointerObservable.remove(this._pointerObserver);
  103488. for (var key in this.gizmos) {
  103489. var gizmo = (this.gizmos[key]);
  103490. if (gizmo) {
  103491. gizmo.dispose();
  103492. }
  103493. }
  103494. this._defaultKeepDepthUtilityLayer.dispose();
  103495. this._defaultUtilityLayer.dispose();
  103496. this.boundingBoxDragBehavior.detach();
  103497. };
  103498. return GizmoManager;
  103499. }());
  103500. BABYLON.GizmoManager = GizmoManager;
  103501. })(BABYLON || (BABYLON = {}));
  103502. //# sourceMappingURL=gizmoManager.js.map
  103503. var BABYLON;
  103504. (function (BABYLON) {
  103505. /**
  103506. * Defines a target to use with MorphTargetManager
  103507. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  103508. */
  103509. var MorphTarget = /** @class */ (function () {
  103510. /**
  103511. * Creates a new MorphTarget
  103512. * @param name defines the name of the target
  103513. * @param influence defines the influence to use
  103514. */
  103515. function MorphTarget(
  103516. /** defines the name of the target */
  103517. name, influence, scene) {
  103518. if (influence === void 0) { influence = 0; }
  103519. if (scene === void 0) { scene = null; }
  103520. this.name = name;
  103521. /**
  103522. * Gets or sets the list of animations
  103523. */
  103524. this.animations = new Array();
  103525. this._positions = null;
  103526. this._normals = null;
  103527. this._tangents = null;
  103528. /**
  103529. * Observable raised when the influence changes
  103530. */
  103531. this.onInfluenceChanged = new BABYLON.Observable();
  103532. /** @hidden */
  103533. this._onDataLayoutChanged = new BABYLON.Observable();
  103534. this._animationPropertiesOverride = null;
  103535. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  103536. this.influence = influence;
  103537. }
  103538. Object.defineProperty(MorphTarget.prototype, "influence", {
  103539. /**
  103540. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  103541. */
  103542. get: function () {
  103543. return this._influence;
  103544. },
  103545. set: function (influence) {
  103546. if (this._influence === influence) {
  103547. return;
  103548. }
  103549. var previous = this._influence;
  103550. this._influence = influence;
  103551. if (this.onInfluenceChanged.hasObservers) {
  103552. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  103553. }
  103554. },
  103555. enumerable: true,
  103556. configurable: true
  103557. });
  103558. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  103559. /**
  103560. * Gets or sets the animation properties override
  103561. */
  103562. get: function () {
  103563. if (!this._animationPropertiesOverride && this._scene) {
  103564. return this._scene.animationPropertiesOverride;
  103565. }
  103566. return this._animationPropertiesOverride;
  103567. },
  103568. set: function (value) {
  103569. this._animationPropertiesOverride = value;
  103570. },
  103571. enumerable: true,
  103572. configurable: true
  103573. });
  103574. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  103575. /**
  103576. * Gets a boolean defining if the target contains position data
  103577. */
  103578. get: function () {
  103579. return !!this._positions;
  103580. },
  103581. enumerable: true,
  103582. configurable: true
  103583. });
  103584. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  103585. /**
  103586. * Gets a boolean defining if the target contains normal data
  103587. */
  103588. get: function () {
  103589. return !!this._normals;
  103590. },
  103591. enumerable: true,
  103592. configurable: true
  103593. });
  103594. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  103595. /**
  103596. * Gets a boolean defining if the target contains tangent data
  103597. */
  103598. get: function () {
  103599. return !!this._tangents;
  103600. },
  103601. enumerable: true,
  103602. configurable: true
  103603. });
  103604. /**
  103605. * Affects position data to this target
  103606. * @param data defines the position data to use
  103607. */
  103608. MorphTarget.prototype.setPositions = function (data) {
  103609. var hadPositions = this.hasPositions;
  103610. this._positions = data;
  103611. if (hadPositions !== this.hasPositions) {
  103612. this._onDataLayoutChanged.notifyObservers(undefined);
  103613. }
  103614. };
  103615. /**
  103616. * Gets the position data stored in this target
  103617. * @returns a FloatArray containing the position data (or null if not present)
  103618. */
  103619. MorphTarget.prototype.getPositions = function () {
  103620. return this._positions;
  103621. };
  103622. /**
  103623. * Affects normal data to this target
  103624. * @param data defines the normal data to use
  103625. */
  103626. MorphTarget.prototype.setNormals = function (data) {
  103627. var hadNormals = this.hasNormals;
  103628. this._normals = data;
  103629. if (hadNormals !== this.hasNormals) {
  103630. this._onDataLayoutChanged.notifyObservers(undefined);
  103631. }
  103632. };
  103633. /**
  103634. * Gets the normal data stored in this target
  103635. * @returns a FloatArray containing the normal data (or null if not present)
  103636. */
  103637. MorphTarget.prototype.getNormals = function () {
  103638. return this._normals;
  103639. };
  103640. /**
  103641. * Affects tangent data to this target
  103642. * @param data defines the tangent data to use
  103643. */
  103644. MorphTarget.prototype.setTangents = function (data) {
  103645. var hadTangents = this.hasTangents;
  103646. this._tangents = data;
  103647. if (hadTangents !== this.hasTangents) {
  103648. this._onDataLayoutChanged.notifyObservers(undefined);
  103649. }
  103650. };
  103651. /**
  103652. * Gets the tangent data stored in this target
  103653. * @returns a FloatArray containing the tangent data (or null if not present)
  103654. */
  103655. MorphTarget.prototype.getTangents = function () {
  103656. return this._tangents;
  103657. };
  103658. /**
  103659. * Serializes the current target into a Serialization object
  103660. * @returns the serialized object
  103661. */
  103662. MorphTarget.prototype.serialize = function () {
  103663. var serializationObject = {};
  103664. serializationObject.name = this.name;
  103665. serializationObject.influence = this.influence;
  103666. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  103667. if (this.hasNormals) {
  103668. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  103669. }
  103670. if (this.hasTangents) {
  103671. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  103672. }
  103673. // Animations
  103674. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  103675. return serializationObject;
  103676. };
  103677. // Statics
  103678. /**
  103679. * Creates a new target from serialized data
  103680. * @param serializationObject defines the serialized data to use
  103681. * @returns a new MorphTarget
  103682. */
  103683. MorphTarget.Parse = function (serializationObject) {
  103684. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  103685. result.setPositions(serializationObject.positions);
  103686. if (serializationObject.normals) {
  103687. result.setNormals(serializationObject.normals);
  103688. }
  103689. if (serializationObject.tangents) {
  103690. result.setTangents(serializationObject.tangents);
  103691. }
  103692. // Animations
  103693. if (serializationObject.animations) {
  103694. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  103695. var parsedAnimation = serializationObject.animations[animationIndex];
  103696. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  103697. }
  103698. }
  103699. return result;
  103700. };
  103701. /**
  103702. * Creates a MorphTarget from mesh data
  103703. * @param mesh defines the source mesh
  103704. * @param name defines the name to use for the new target
  103705. * @param influence defines the influence to attach to the target
  103706. * @returns a new MorphTarget
  103707. */
  103708. MorphTarget.FromMesh = function (mesh, name, influence) {
  103709. if (!name) {
  103710. name = mesh.name;
  103711. }
  103712. var result = new MorphTarget(name, influence, mesh.getScene());
  103713. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  103714. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  103715. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  103716. }
  103717. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  103718. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  103719. }
  103720. return result;
  103721. };
  103722. return MorphTarget;
  103723. }());
  103724. BABYLON.MorphTarget = MorphTarget;
  103725. })(BABYLON || (BABYLON = {}));
  103726. //# sourceMappingURL=morphTarget.js.map
  103727. var BABYLON;
  103728. (function (BABYLON) {
  103729. /**
  103730. * This class is used to deform meshes using morphing between different targets
  103731. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  103732. */
  103733. var MorphTargetManager = /** @class */ (function () {
  103734. /**
  103735. * Creates a new MorphTargetManager
  103736. * @param scene defines the current scene
  103737. */
  103738. function MorphTargetManager(scene) {
  103739. if (scene === void 0) { scene = null; }
  103740. this._targets = new Array();
  103741. this._targetInfluenceChangedObservers = new Array();
  103742. this._targetDataLayoutChangedObservers = new Array();
  103743. this._activeTargets = new BABYLON.SmartArray(16);
  103744. this._supportsNormals = false;
  103745. this._supportsTangents = false;
  103746. this._vertexCount = 0;
  103747. this._uniqueId = 0;
  103748. this._tempInfluences = new Array();
  103749. if (!scene) {
  103750. scene = BABYLON.Engine.LastCreatedScene;
  103751. }
  103752. this._scene = scene;
  103753. if (this._scene) {
  103754. this._scene.morphTargetManagers.push(this);
  103755. this._uniqueId = this._scene.getUniqueId();
  103756. }
  103757. }
  103758. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  103759. /**
  103760. * Gets the unique ID of this manager
  103761. */
  103762. get: function () {
  103763. return this._uniqueId;
  103764. },
  103765. enumerable: true,
  103766. configurable: true
  103767. });
  103768. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  103769. /**
  103770. * Gets the number of vertices handled by this manager
  103771. */
  103772. get: function () {
  103773. return this._vertexCount;
  103774. },
  103775. enumerable: true,
  103776. configurable: true
  103777. });
  103778. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  103779. /**
  103780. * Gets a boolean indicating if this manager supports morphing of normals
  103781. */
  103782. get: function () {
  103783. return this._supportsNormals;
  103784. },
  103785. enumerable: true,
  103786. configurable: true
  103787. });
  103788. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  103789. /**
  103790. * Gets a boolean indicating if this manager supports morphing of tangents
  103791. */
  103792. get: function () {
  103793. return this._supportsTangents;
  103794. },
  103795. enumerable: true,
  103796. configurable: true
  103797. });
  103798. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  103799. /**
  103800. * Gets the number of targets stored in this manager
  103801. */
  103802. get: function () {
  103803. return this._targets.length;
  103804. },
  103805. enumerable: true,
  103806. configurable: true
  103807. });
  103808. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  103809. /**
  103810. * Gets the number of influencers (ie. the number of targets with influences > 0)
  103811. */
  103812. get: function () {
  103813. return this._activeTargets.length;
  103814. },
  103815. enumerable: true,
  103816. configurable: true
  103817. });
  103818. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  103819. /**
  103820. * Gets the list of influences (one per target)
  103821. */
  103822. get: function () {
  103823. return this._influences;
  103824. },
  103825. enumerable: true,
  103826. configurable: true
  103827. });
  103828. /**
  103829. * Gets the active target at specified index. An active target is a target with an influence > 0
  103830. * @param index defines the index to check
  103831. * @returns the requested target
  103832. */
  103833. MorphTargetManager.prototype.getActiveTarget = function (index) {
  103834. return this._activeTargets.data[index];
  103835. };
  103836. /**
  103837. * Gets the target at specified index
  103838. * @param index defines the index to check
  103839. * @returns the requested target
  103840. */
  103841. MorphTargetManager.prototype.getTarget = function (index) {
  103842. return this._targets[index];
  103843. };
  103844. /**
  103845. * Add a new target to this manager
  103846. * @param target defines the target to add
  103847. */
  103848. MorphTargetManager.prototype.addTarget = function (target) {
  103849. var _this = this;
  103850. this._targets.push(target);
  103851. this._targetInfluenceChangedObservers.push(target.onInfluenceChanged.add(function (needUpdate) {
  103852. _this._syncActiveTargets(needUpdate);
  103853. }));
  103854. this._targetDataLayoutChangedObservers.push(target._onDataLayoutChanged.add(function () {
  103855. _this._syncActiveTargets(true);
  103856. }));
  103857. this._syncActiveTargets(true);
  103858. };
  103859. /**
  103860. * Removes a target from the manager
  103861. * @param target defines the target to remove
  103862. */
  103863. MorphTargetManager.prototype.removeTarget = function (target) {
  103864. var index = this._targets.indexOf(target);
  103865. if (index >= 0) {
  103866. this._targets.splice(index, 1);
  103867. target.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(index, 1)[0]);
  103868. target._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(index, 1)[0]);
  103869. this._syncActiveTargets(true);
  103870. }
  103871. };
  103872. /**
  103873. * Serializes the current manager into a Serialization object
  103874. * @returns the serialized object
  103875. */
  103876. MorphTargetManager.prototype.serialize = function () {
  103877. var serializationObject = {};
  103878. serializationObject.id = this.uniqueId;
  103879. serializationObject.targets = [];
  103880. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  103881. var target = _a[_i];
  103882. serializationObject.targets.push(target.serialize());
  103883. }
  103884. return serializationObject;
  103885. };
  103886. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  103887. var influenceCount = 0;
  103888. this._activeTargets.reset();
  103889. this._supportsNormals = true;
  103890. this._supportsTangents = true;
  103891. this._vertexCount = 0;
  103892. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  103893. var target = _a[_i];
  103894. if (target.influence === 0) {
  103895. continue;
  103896. }
  103897. this._activeTargets.push(target);
  103898. this._tempInfluences[influenceCount++] = target.influence;
  103899. this._supportsNormals = this._supportsNormals && target.hasNormals;
  103900. this._supportsTangents = this._supportsTangents && target.hasTangents;
  103901. var positions = target.getPositions();
  103902. if (positions) {
  103903. var vertexCount = positions.length / 3;
  103904. if (this._vertexCount === 0) {
  103905. this._vertexCount = vertexCount;
  103906. }
  103907. else if (this._vertexCount !== vertexCount) {
  103908. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  103909. return;
  103910. }
  103911. }
  103912. }
  103913. if (!this._influences || this._influences.length !== influenceCount) {
  103914. this._influences = new Float32Array(influenceCount);
  103915. }
  103916. for (var index = 0; index < influenceCount; index++) {
  103917. this._influences[index] = this._tempInfluences[index];
  103918. }
  103919. if (needUpdate) {
  103920. this.synchronize();
  103921. }
  103922. };
  103923. /**
  103924. * Syncrhonize the targets with all the meshes using this morph target manager
  103925. */
  103926. MorphTargetManager.prototype.synchronize = function () {
  103927. if (!this._scene) {
  103928. return;
  103929. }
  103930. // Flag meshes as dirty to resync with the active targets
  103931. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  103932. var mesh = _a[_i];
  103933. if (mesh.morphTargetManager === this) {
  103934. mesh._syncGeometryWithMorphTargetManager();
  103935. }
  103936. }
  103937. };
  103938. // Statics
  103939. /**
  103940. * Creates a new MorphTargetManager from serialized data
  103941. * @param serializationObject defines the serialized data
  103942. * @param scene defines the hosting scene
  103943. * @returns the new MorphTargetManager
  103944. */
  103945. MorphTargetManager.Parse = function (serializationObject, scene) {
  103946. var result = new MorphTargetManager(scene);
  103947. result._uniqueId = serializationObject.id;
  103948. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  103949. var targetData = _a[_i];
  103950. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  103951. }
  103952. return result;
  103953. };
  103954. return MorphTargetManager;
  103955. }());
  103956. BABYLON.MorphTargetManager = MorphTargetManager;
  103957. })(BABYLON || (BABYLON = {}));
  103958. //# sourceMappingURL=morphTargetManager.js.map
  103959. var BABYLON;
  103960. (function (BABYLON) {
  103961. /**
  103962. * Octrees are a really powerful data structure that can quickly select entities based on space coordinates.
  103963. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  103964. */
  103965. var Octree = /** @class */ (function () {
  103966. /**
  103967. * Creates a octree
  103968. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  103969. * @param creationFunc function to be used to instatiate the octree
  103970. * @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64)
  103971. * @param maxDepth defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.)
  103972. */
  103973. function Octree(creationFunc, maxBlockCapacity,
  103974. /** Defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.) */
  103975. maxDepth) {
  103976. if (maxDepth === void 0) { maxDepth = 2; }
  103977. this.maxDepth = maxDepth;
  103978. /**
  103979. * Content stored in the octree
  103980. */
  103981. this.dynamicContent = new Array();
  103982. this._maxBlockCapacity = maxBlockCapacity || 64;
  103983. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  103984. this._creationFunc = creationFunc;
  103985. }
  103986. // Methods
  103987. /**
  103988. * Updates the octree by adding blocks for the passed in meshes within the min and max world parameters
  103989. * @param worldMin worldMin for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  103990. * @param worldMax worldMax for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  103991. * @param entries meshes to be added to the octree blocks
  103992. */
  103993. Octree.prototype.update = function (worldMin, worldMax, entries) {
  103994. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  103995. };
  103996. /**
  103997. * Adds a mesh to the octree
  103998. * @param entry Mesh to add to the octree
  103999. */
  104000. Octree.prototype.addMesh = function (entry) {
  104001. for (var index = 0; index < this.blocks.length; index++) {
  104002. var block = this.blocks[index];
  104003. block.addEntry(entry);
  104004. }
  104005. };
  104006. /**
  104007. * Selects an array of meshes within the frustum
  104008. * @param frustumPlanes The frustum planes to use which will select all meshes within it
  104009. * @param allowDuplicate If duplicate objects are allowed in the resulting object array
  104010. * @returns array of meshes within the frustum
  104011. */
  104012. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  104013. this._selectionContent.reset();
  104014. for (var index = 0; index < this.blocks.length; index++) {
  104015. var block = this.blocks[index];
  104016. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  104017. }
  104018. if (allowDuplicate) {
  104019. this._selectionContent.concat(this.dynamicContent);
  104020. }
  104021. else {
  104022. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  104023. }
  104024. return this._selectionContent;
  104025. };
  104026. /**
  104027. * Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array
  104028. * @param sphereCenter defines the bounding sphere center
  104029. * @param sphereRadius defines the bounding sphere radius
  104030. * @param allowDuplicate defines if the selection array can contains duplicated entries
  104031. * @returns an array of objects that intersect the sphere
  104032. */
  104033. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  104034. this._selectionContent.reset();
  104035. for (var index = 0; index < this.blocks.length; index++) {
  104036. var block = this.blocks[index];
  104037. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  104038. }
  104039. if (allowDuplicate) {
  104040. this._selectionContent.concat(this.dynamicContent);
  104041. }
  104042. else {
  104043. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  104044. }
  104045. return this._selectionContent;
  104046. };
  104047. /**
  104048. * Test if the octree intersect with the given ray and if yes, then add its content to resulting array
  104049. * @param ray defines the ray to test with
  104050. * @returns array of intersected objects
  104051. */
  104052. Octree.prototype.intersectsRay = function (ray) {
  104053. this._selectionContent.reset();
  104054. for (var index = 0; index < this.blocks.length; index++) {
  104055. var block = this.blocks[index];
  104056. block.intersectsRay(ray, this._selectionContent);
  104057. }
  104058. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  104059. return this._selectionContent;
  104060. };
  104061. /**
  104062. * @hidden
  104063. */
  104064. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  104065. target.blocks = new Array();
  104066. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  104067. // Segmenting space
  104068. for (var x = 0; x < 2; x++) {
  104069. for (var y = 0; y < 2; y++) {
  104070. for (var z = 0; z < 2; z++) {
  104071. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  104072. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  104073. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  104074. block.addEntries(entries);
  104075. target.blocks.push(block);
  104076. }
  104077. }
  104078. }
  104079. };
  104080. /**
  104081. * Adds a mesh into the octree block if it intersects the block
  104082. */
  104083. Octree.CreationFuncForMeshes = function (entry, block) {
  104084. var boundingInfo = entry.getBoundingInfo();
  104085. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  104086. block.entries.push(entry);
  104087. }
  104088. };
  104089. /**
  104090. * Adds a submesh into the octree block if it intersects the block
  104091. */
  104092. Octree.CreationFuncForSubMeshes = function (entry, block) {
  104093. var boundingInfo = entry.getBoundingInfo();
  104094. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  104095. block.entries.push(entry);
  104096. }
  104097. };
  104098. return Octree;
  104099. }());
  104100. BABYLON.Octree = Octree;
  104101. })(BABYLON || (BABYLON = {}));
  104102. //# sourceMappingURL=octree.js.map
  104103. var BABYLON;
  104104. (function (BABYLON) {
  104105. /**
  104106. * Class used to store a cell in an octree
  104107. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  104108. */
  104109. var OctreeBlock = /** @class */ (function () {
  104110. /**
  104111. * Creates a new block
  104112. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  104113. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  104114. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  104115. * @param depth defines the current depth of this block in the octree
  104116. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  104117. * @param creationFunc defines a callback to call when an element is added to the block
  104118. */
  104119. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  104120. /**
  104121. * Gets the content of the current block
  104122. */
  104123. this.entries = new Array();
  104124. this._boundingVectors = new Array();
  104125. this._capacity = capacity;
  104126. this._depth = depth;
  104127. this._maxDepth = maxDepth;
  104128. this._creationFunc = creationFunc;
  104129. this._minPoint = minPoint;
  104130. this._maxPoint = maxPoint;
  104131. this._boundingVectors.push(minPoint.clone());
  104132. this._boundingVectors.push(maxPoint.clone());
  104133. this._boundingVectors.push(minPoint.clone());
  104134. this._boundingVectors[2].x = maxPoint.x;
  104135. this._boundingVectors.push(minPoint.clone());
  104136. this._boundingVectors[3].y = maxPoint.y;
  104137. this._boundingVectors.push(minPoint.clone());
  104138. this._boundingVectors[4].z = maxPoint.z;
  104139. this._boundingVectors.push(maxPoint.clone());
  104140. this._boundingVectors[5].z = minPoint.z;
  104141. this._boundingVectors.push(maxPoint.clone());
  104142. this._boundingVectors[6].x = minPoint.x;
  104143. this._boundingVectors.push(maxPoint.clone());
  104144. this._boundingVectors[7].y = minPoint.y;
  104145. }
  104146. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  104147. // Property
  104148. /**
  104149. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  104150. */
  104151. get: function () {
  104152. return this._capacity;
  104153. },
  104154. enumerable: true,
  104155. configurable: true
  104156. });
  104157. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  104158. /**
  104159. * Gets the minimum vector (in world space) of the block's bounding box
  104160. */
  104161. get: function () {
  104162. return this._minPoint;
  104163. },
  104164. enumerable: true,
  104165. configurable: true
  104166. });
  104167. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  104168. /**
  104169. * Gets the maximum vector (in world space) of the block's bounding box
  104170. */
  104171. get: function () {
  104172. return this._maxPoint;
  104173. },
  104174. enumerable: true,
  104175. configurable: true
  104176. });
  104177. // Methods
  104178. /**
  104179. * Add a new element to this block
  104180. * @param entry defines the element to add
  104181. */
  104182. OctreeBlock.prototype.addEntry = function (entry) {
  104183. if (this.blocks) {
  104184. for (var index = 0; index < this.blocks.length; index++) {
  104185. var block = this.blocks[index];
  104186. block.addEntry(entry);
  104187. }
  104188. return;
  104189. }
  104190. this._creationFunc(entry, this);
  104191. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  104192. this.createInnerBlocks();
  104193. }
  104194. };
  104195. /**
  104196. * Add an array of elements to this block
  104197. * @param entries defines the array of elements to add
  104198. */
  104199. OctreeBlock.prototype.addEntries = function (entries) {
  104200. for (var index = 0; index < entries.length; index++) {
  104201. var mesh = entries[index];
  104202. this.addEntry(mesh);
  104203. }
  104204. };
  104205. /**
  104206. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  104207. * @param frustumPlanes defines the frustum planes to test
  104208. * @param selection defines the array to store current content if selection is positive
  104209. * @param allowDuplicate defines if the selection array can contains duplicated entries
  104210. */
  104211. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  104212. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  104213. if (this.blocks) {
  104214. for (var index = 0; index < this.blocks.length; index++) {
  104215. var block = this.blocks[index];
  104216. block.select(frustumPlanes, selection, allowDuplicate);
  104217. }
  104218. return;
  104219. }
  104220. if (allowDuplicate) {
  104221. selection.concat(this.entries);
  104222. }
  104223. else {
  104224. selection.concatWithNoDuplicate(this.entries);
  104225. }
  104226. }
  104227. };
  104228. /**
  104229. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  104230. * @param sphereCenter defines the bounding sphere center
  104231. * @param sphereRadius defines the bounding sphere radius
  104232. * @param selection defines the array to store current content if selection is positive
  104233. * @param allowDuplicate defines if the selection array can contains duplicated entries
  104234. */
  104235. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  104236. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  104237. if (this.blocks) {
  104238. for (var index = 0; index < this.blocks.length; index++) {
  104239. var block = this.blocks[index];
  104240. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  104241. }
  104242. return;
  104243. }
  104244. if (allowDuplicate) {
  104245. selection.concat(this.entries);
  104246. }
  104247. else {
  104248. selection.concatWithNoDuplicate(this.entries);
  104249. }
  104250. }
  104251. };
  104252. /**
  104253. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  104254. * @param ray defines the ray to test with
  104255. * @param selection defines the array to store current content if selection is positive
  104256. */
  104257. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  104258. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  104259. if (this.blocks) {
  104260. for (var index = 0; index < this.blocks.length; index++) {
  104261. var block = this.blocks[index];
  104262. block.intersectsRay(ray, selection);
  104263. }
  104264. return;
  104265. }
  104266. selection.concatWithNoDuplicate(this.entries);
  104267. }
  104268. };
  104269. /**
  104270. * Subdivide the content into child blocks (this block will then be empty)
  104271. */
  104272. OctreeBlock.prototype.createInnerBlocks = function () {
  104273. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  104274. };
  104275. return OctreeBlock;
  104276. }());
  104277. BABYLON.OctreeBlock = OctreeBlock;
  104278. })(BABYLON || (BABYLON = {}));
  104279. //# sourceMappingURL=octreeBlock.js.map
  104280. var BABYLON;
  104281. (function (BABYLON) {
  104282. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  104283. if (maxCapacity === void 0) { maxCapacity = 64; }
  104284. if (maxDepth === void 0) { maxDepth = 2; }
  104285. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  104286. if (!component) {
  104287. component = new OctreeSceneComponent(this);
  104288. this._addComponent(component);
  104289. }
  104290. if (!this._selectionOctree) {
  104291. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  104292. }
  104293. var worldExtends = this.getWorldExtends();
  104294. // Update octree
  104295. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  104296. return this._selectionOctree;
  104297. };
  104298. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  104299. get: function () {
  104300. return this._selectionOctree;
  104301. },
  104302. enumerable: true,
  104303. configurable: true
  104304. });
  104305. /**
  104306. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  104307. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  104308. * @param maxCapacity defines the maximum size of each block (64 by default)
  104309. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  104310. * @returns the new octree
  104311. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  104312. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  104313. */
  104314. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  104315. if (maxCapacity === void 0) { maxCapacity = 64; }
  104316. if (maxDepth === void 0) { maxDepth = 2; }
  104317. var scene = this.getScene();
  104318. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  104319. if (!component) {
  104320. component = new OctreeSceneComponent(scene);
  104321. scene._addComponent(component);
  104322. }
  104323. if (!this._submeshesOctree) {
  104324. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  104325. }
  104326. this.computeWorldMatrix(true);
  104327. var boundingInfo = this.getBoundingInfo();
  104328. // Update octree
  104329. var bbox = boundingInfo.boundingBox;
  104330. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  104331. return this._submeshesOctree;
  104332. };
  104333. /**
  104334. * Defines the octree scene component responsible to manage any octrees
  104335. * in a given scene.
  104336. */
  104337. var OctreeSceneComponent = /** @class */ (function () {
  104338. /**
  104339. * Creates a new instance of the component for the given scene
  104340. * @param scene Defines the scene to register the component in
  104341. */
  104342. function OctreeSceneComponent(scene) {
  104343. /**
  104344. * The component name helpfull to identify the component in the list of scene components.
  104345. */
  104346. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  104347. /**
  104348. * Indicates if the meshes have been checked to make sure they are isEnabled()
  104349. */
  104350. this.checksIsEnabled = true;
  104351. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  104352. this.scene = scene;
  104353. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  104354. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  104355. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  104356. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  104357. }
  104358. /**
  104359. * Registers the component in a given scene
  104360. */
  104361. OctreeSceneComponent.prototype.register = function () {
  104362. var _this = this;
  104363. this.scene.onMeshRemovedObservable.add(function (mesh) {
  104364. var sceneOctree = _this.scene.selectionOctree;
  104365. if (sceneOctree !== undefined && sceneOctree !== null) {
  104366. var index = sceneOctree.dynamicContent.indexOf(mesh);
  104367. if (index !== -1) {
  104368. sceneOctree.dynamicContent.splice(index, 1);
  104369. }
  104370. }
  104371. });
  104372. this.scene.onMeshImportedObservable.add(function (mesh) {
  104373. var sceneOctree = _this.scene.selectionOctree;
  104374. if (sceneOctree !== undefined && sceneOctree !== null) {
  104375. sceneOctree.addMesh(mesh);
  104376. }
  104377. });
  104378. };
  104379. /**
  104380. * Return the list of active meshes
  104381. * @returns the list of active meshes
  104382. */
  104383. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  104384. if (this.scene._selectionOctree) {
  104385. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  104386. return selection;
  104387. }
  104388. return this.scene._getDefaultMeshCandidates();
  104389. };
  104390. /**
  104391. * Return the list of active sub meshes
  104392. * @param mesh The mesh to get the candidates sub meshes from
  104393. * @returns the list of active sub meshes
  104394. */
  104395. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  104396. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  104397. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  104398. return intersections;
  104399. }
  104400. return this.scene._getDefaultSubMeshCandidates(mesh);
  104401. };
  104402. /**
  104403. * Return the list of sub meshes intersecting with a given local ray
  104404. * @param mesh defines the mesh to find the submesh for
  104405. * @param localRay defines the ray in local space
  104406. * @returns the list of intersecting sub meshes
  104407. */
  104408. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  104409. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  104410. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  104411. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  104412. return intersections;
  104413. }
  104414. return this.scene._getDefaultSubMeshCandidates(mesh);
  104415. };
  104416. /**
  104417. * Return the list of sub meshes colliding with a collider
  104418. * @param mesh defines the mesh to find the submesh for
  104419. * @param collider defines the collider to evaluate the collision against
  104420. * @returns the list of colliding sub meshes
  104421. */
  104422. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  104423. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  104424. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  104425. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  104426. return intersections;
  104427. }
  104428. return this.scene._getDefaultSubMeshCandidates(mesh);
  104429. };
  104430. /**
  104431. * Rebuilds the elements related to this component in case of
  104432. * context lost for instance.
  104433. */
  104434. OctreeSceneComponent.prototype.rebuild = function () {
  104435. // Nothing to do here.
  104436. };
  104437. /**
  104438. * Disposes the component and the associated ressources.
  104439. */
  104440. OctreeSceneComponent.prototype.dispose = function () {
  104441. // Nothing to do here.
  104442. };
  104443. return OctreeSceneComponent;
  104444. }());
  104445. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  104446. })(BABYLON || (BABYLON = {}));
  104447. //# sourceMappingURL=octreeSceneComponent.js.map
  104448. var BABYLON;
  104449. (function (BABYLON) {
  104450. /**
  104451. * Postprocess used to generate anaglyphic rendering
  104452. */
  104453. var AnaglyphPostProcess = /** @class */ (function (_super) {
  104454. __extends(AnaglyphPostProcess, _super);
  104455. /**
  104456. * Creates a new AnaglyphPostProcess
  104457. * @param name defines postprocess name
  104458. * @param options defines creation options or target ratio scale
  104459. * @param rigCameras defines cameras using this postprocess
  104460. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  104461. * @param engine defines hosting engine
  104462. * @param reusable defines if the postprocess will be reused multiple times per frame
  104463. */
  104464. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  104465. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  104466. _this._passedProcess = rigCameras[0]._rigPostProcess;
  104467. _this.onApplyObservable.add(function (effect) {
  104468. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  104469. });
  104470. return _this;
  104471. }
  104472. return AnaglyphPostProcess;
  104473. }(BABYLON.PostProcess));
  104474. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  104475. })(BABYLON || (BABYLON = {}));
  104476. //# sourceMappingURL=anaglyphPostProcess.js.map
  104477. var BABYLON;
  104478. (function (BABYLON) {
  104479. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  104480. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  104481. });
  104482. /**
  104483. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  104484. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  104485. */
  104486. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  104487. __extends(AnaglyphArcRotateCamera, _super);
  104488. /**
  104489. * Creates a new AnaglyphArcRotateCamera
  104490. * @param name defines camera name
  104491. * @param alpha defines alpha angle (in radians)
  104492. * @param beta defines beta angle (in radians)
  104493. * @param radius defines radius
  104494. * @param target defines camera target
  104495. * @param interaxialDistance defines distance between each color axis
  104496. * @param scene defines the hosting scene
  104497. */
  104498. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  104499. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  104500. _this.interaxialDistance = interaxialDistance;
  104501. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  104502. return _this;
  104503. }
  104504. /**
  104505. * Gets camera class name
  104506. * @returns AnaglyphArcRotateCamera
  104507. */
  104508. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  104509. return "AnaglyphArcRotateCamera";
  104510. };
  104511. return AnaglyphArcRotateCamera;
  104512. }(BABYLON.ArcRotateCamera));
  104513. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  104514. })(BABYLON || (BABYLON = {}));
  104515. //# sourceMappingURL=anaglyphArcRotateCamera.js.map
  104516. var BABYLON;
  104517. (function (BABYLON) {
  104518. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  104519. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  104520. });
  104521. /**
  104522. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  104523. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  104524. */
  104525. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  104526. __extends(AnaglyphFreeCamera, _super);
  104527. /**
  104528. * Creates a new AnaglyphFreeCamera
  104529. * @param name defines camera name
  104530. * @param position defines initial position
  104531. * @param interaxialDistance defines distance between each color axis
  104532. * @param scene defines the hosting scene
  104533. */
  104534. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  104535. var _this = _super.call(this, name, position, scene) || this;
  104536. _this.interaxialDistance = interaxialDistance;
  104537. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  104538. return _this;
  104539. }
  104540. /**
  104541. * Gets camera class name
  104542. * @returns AnaglyphFreeCamera
  104543. */
  104544. AnaglyphFreeCamera.prototype.getClassName = function () {
  104545. return "AnaglyphFreeCamera";
  104546. };
  104547. return AnaglyphFreeCamera;
  104548. }(BABYLON.FreeCamera));
  104549. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  104550. })(BABYLON || (BABYLON = {}));
  104551. //# sourceMappingURL=anaglyphFreeCamera.js.map
  104552. var BABYLON;
  104553. (function (BABYLON) {
  104554. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  104555. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  104556. });
  104557. /**
  104558. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  104559. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  104560. */
  104561. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  104562. __extends(AnaglyphGamepadCamera, _super);
  104563. /**
  104564. * Creates a new AnaglyphGamepadCamera
  104565. * @param name defines camera name
  104566. * @param position defines initial position
  104567. * @param interaxialDistance defines distance between each color axis
  104568. * @param scene defines the hosting scene
  104569. */
  104570. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  104571. var _this = _super.call(this, name, position, scene) || this;
  104572. _this.interaxialDistance = interaxialDistance;
  104573. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  104574. return _this;
  104575. }
  104576. /**
  104577. * Gets camera class name
  104578. * @returns AnaglyphGamepadCamera
  104579. */
  104580. AnaglyphGamepadCamera.prototype.getClassName = function () {
  104581. return "AnaglyphGamepadCamera";
  104582. };
  104583. return AnaglyphGamepadCamera;
  104584. }(BABYLON.GamepadCamera));
  104585. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  104586. })(BABYLON || (BABYLON = {}));
  104587. //# sourceMappingURL=anaglyphGamepadCamera.js.map
  104588. var BABYLON;
  104589. (function (BABYLON) {
  104590. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  104591. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  104592. });
  104593. /**
  104594. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  104595. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  104596. */
  104597. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  104598. __extends(AnaglyphUniversalCamera, _super);
  104599. /**
  104600. * Creates a new AnaglyphUniversalCamera
  104601. * @param name defines camera name
  104602. * @param position defines initial position
  104603. * @param interaxialDistance defines distance between each color axis
  104604. * @param scene defines the hosting scene
  104605. */
  104606. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  104607. var _this = _super.call(this, name, position, scene) || this;
  104608. _this.interaxialDistance = interaxialDistance;
  104609. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  104610. return _this;
  104611. }
  104612. /**
  104613. * Gets camera class name
  104614. * @returns AnaglyphUniversalCamera
  104615. */
  104616. AnaglyphUniversalCamera.prototype.getClassName = function () {
  104617. return "AnaglyphUniversalCamera";
  104618. };
  104619. return AnaglyphUniversalCamera;
  104620. }(BABYLON.UniversalCamera));
  104621. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  104622. })(BABYLON || (BABYLON = {}));
  104623. //# sourceMappingURL=anaglyphUniversalCamera.js.map
  104624. var BABYLON;
  104625. (function (BABYLON) {
  104626. /**
  104627. * StereoscopicInterlacePostProcess used to render stereo views from a rigged camera
  104628. */
  104629. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  104630. __extends(StereoscopicInterlacePostProcess, _super);
  104631. /**
  104632. * Initializes a StereoscopicInterlacePostProcess
  104633. * @param name The name of the effect.
  104634. * @param rigCameras The rig cameras to be appled to the post process
  104635. * @param isStereoscopicHoriz If the rendered results are horizontal or verticle
  104636. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  104637. * @param engine The engine which the post process will be applied. (default: current engine)
  104638. * @param reusable If the post process can be reused on the same frame. (default: false)
  104639. */
  104640. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  104641. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  104642. _this._passedProcess = rigCameras[0]._rigPostProcess;
  104643. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  104644. _this.onSizeChangedObservable.add(function () {
  104645. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  104646. });
  104647. _this.onApplyObservable.add(function (effect) {
  104648. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  104649. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  104650. });
  104651. return _this;
  104652. }
  104653. return StereoscopicInterlacePostProcess;
  104654. }(BABYLON.PostProcess));
  104655. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  104656. })(BABYLON || (BABYLON = {}));
  104657. //# sourceMappingURL=stereoscopicInterlacePostProcess.js.map
  104658. var BABYLON;
  104659. (function (BABYLON) {
  104660. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  104661. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  104662. });
  104663. /**
  104664. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  104665. * @see http://doc.babylonjs.com/features/cameras
  104666. */
  104667. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  104668. __extends(StereoscopicArcRotateCamera, _super);
  104669. /**
  104670. * Creates a new StereoscopicArcRotateCamera
  104671. * @param name defines camera name
  104672. * @param alpha defines alpha angle (in radians)
  104673. * @param beta defines beta angle (in radians)
  104674. * @param radius defines radius
  104675. * @param target defines camera target
  104676. * @param interaxialDistance defines distance between each color axis
  104677. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  104678. * @param scene defines the hosting scene
  104679. */
  104680. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  104681. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  104682. _this.interaxialDistance = interaxialDistance;
  104683. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  104684. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  104685. return _this;
  104686. }
  104687. /**
  104688. * Gets camera class name
  104689. * @returns StereoscopicArcRotateCamera
  104690. */
  104691. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  104692. return "StereoscopicArcRotateCamera";
  104693. };
  104694. return StereoscopicArcRotateCamera;
  104695. }(BABYLON.ArcRotateCamera));
  104696. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  104697. })(BABYLON || (BABYLON = {}));
  104698. //# sourceMappingURL=stereoscopicArcRotateCamera.js.map
  104699. var BABYLON;
  104700. (function (BABYLON) {
  104701. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  104702. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  104703. });
  104704. /**
  104705. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  104706. * @see http://doc.babylonjs.com/features/cameras
  104707. */
  104708. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  104709. __extends(StereoscopicFreeCamera, _super);
  104710. /**
  104711. * Creates a new StereoscopicFreeCamera
  104712. * @param name defines camera name
  104713. * @param position defines initial position
  104714. * @param interaxialDistance defines distance between each color axis
  104715. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  104716. * @param scene defines the hosting scene
  104717. */
  104718. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  104719. var _this = _super.call(this, name, position, scene) || this;
  104720. _this.interaxialDistance = interaxialDistance;
  104721. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  104722. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  104723. return _this;
  104724. }
  104725. /**
  104726. * Gets camera class name
  104727. * @returns StereoscopicFreeCamera
  104728. */
  104729. StereoscopicFreeCamera.prototype.getClassName = function () {
  104730. return "StereoscopicFreeCamera";
  104731. };
  104732. return StereoscopicFreeCamera;
  104733. }(BABYLON.FreeCamera));
  104734. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  104735. })(BABYLON || (BABYLON = {}));
  104736. //# sourceMappingURL=stereoscopicFreeCamera.js.map
  104737. var BABYLON;
  104738. (function (BABYLON) {
  104739. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  104740. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  104741. });
  104742. /**
  104743. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  104744. * @see http://doc.babylonjs.com/features/cameras
  104745. */
  104746. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  104747. __extends(StereoscopicGamepadCamera, _super);
  104748. /**
  104749. * Creates a new StereoscopicGamepadCamera
  104750. * @param name defines camera name
  104751. * @param position defines initial position
  104752. * @param interaxialDistance defines distance between each color axis
  104753. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  104754. * @param scene defines the hosting scene
  104755. */
  104756. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  104757. var _this = _super.call(this, name, position, scene) || this;
  104758. _this.interaxialDistance = interaxialDistance;
  104759. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  104760. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  104761. return _this;
  104762. }
  104763. /**
  104764. * Gets camera class name
  104765. * @returns StereoscopicGamepadCamera
  104766. */
  104767. StereoscopicGamepadCamera.prototype.getClassName = function () {
  104768. return "StereoscopicGamepadCamera";
  104769. };
  104770. return StereoscopicGamepadCamera;
  104771. }(BABYLON.GamepadCamera));
  104772. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  104773. })(BABYLON || (BABYLON = {}));
  104774. //# sourceMappingURL=stereoscopicGamepadCamera.js.map
  104775. var BABYLON;
  104776. (function (BABYLON) {
  104777. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  104778. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  104779. });
  104780. /**
  104781. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  104782. * @see http://doc.babylonjs.com/features/cameras
  104783. */
  104784. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  104785. __extends(StereoscopicUniversalCamera, _super);
  104786. /**
  104787. * Creates a new StereoscopicUniversalCamera
  104788. * @param name defines camera name
  104789. * @param position defines initial position
  104790. * @param interaxialDistance defines distance between each color axis
  104791. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  104792. * @param scene defines the hosting scene
  104793. */
  104794. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  104795. var _this = _super.call(this, name, position, scene) || this;
  104796. _this.interaxialDistance = interaxialDistance;
  104797. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  104798. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  104799. return _this;
  104800. }
  104801. /**
  104802. * Gets camera class name
  104803. * @returns StereoscopicUniversalCamera
  104804. */
  104805. StereoscopicUniversalCamera.prototype.getClassName = function () {
  104806. return "StereoscopicUniversalCamera";
  104807. };
  104808. return StereoscopicUniversalCamera;
  104809. }(BABYLON.UniversalCamera));
  104810. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  104811. })(BABYLON || (BABYLON = {}));
  104812. //# sourceMappingURL=stereoscopicUniversalCamera.js.map
  104813. var BABYLON;
  104814. (function (BABYLON) {
  104815. /**
  104816. * VRDistortionCorrectionPostProcess used for mobile VR
  104817. */
  104818. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  104819. __extends(VRDistortionCorrectionPostProcess, _super);
  104820. /**
  104821. * Initializes the VRDistortionCorrectionPostProcess
  104822. * @param name The name of the effect.
  104823. * @param camera The camera to apply the render pass to.
  104824. * @param isRightEye If this is for the right eye distortion
  104825. * @param vrMetrics All the required metrics for the VR camera
  104826. */
  104827. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  104828. var _this = _super.call(this, name, "vrDistortionCorrection", [
  104829. 'LensCenter',
  104830. 'Scale',
  104831. 'ScaleIn',
  104832. 'HmdWarpParam'
  104833. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  104834. _this._isRightEye = isRightEye;
  104835. _this._distortionFactors = vrMetrics.distortionK;
  104836. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  104837. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  104838. _this.adaptScaleToCurrentViewport = true;
  104839. _this.onSizeChangedObservable.add(function () {
  104840. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  104841. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  104842. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  104843. });
  104844. _this.onApplyObservable.add(function (effect) {
  104845. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  104846. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  104847. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  104848. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  104849. });
  104850. return _this;
  104851. }
  104852. return VRDistortionCorrectionPostProcess;
  104853. }(BABYLON.PostProcess));
  104854. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  104855. })(BABYLON || (BABYLON = {}));
  104856. //# sourceMappingURL=vrDistortionCorrectionPostProcess.js.map
  104857. var BABYLON;
  104858. (function (BABYLON) {
  104859. /**
  104860. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  104861. * Screen rotation is taken into account.
  104862. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  104863. */
  104864. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  104865. /**
  104866. * Instantiates a new input
  104867. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  104868. */
  104869. function FreeCameraDeviceOrientationInput() {
  104870. var _this = this;
  104871. this._screenOrientationAngle = 0;
  104872. this._screenQuaternion = new BABYLON.Quaternion();
  104873. this._alpha = 0;
  104874. this._beta = 0;
  104875. this._gamma = 0;
  104876. this._orientationChanged = function () {
  104877. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && (window.screen.orientation)['angle'] ? (window.screen.orientation).angle : 0));
  104878. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  104879. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  104880. };
  104881. this._deviceOrientation = function (evt) {
  104882. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  104883. _this._beta = evt.beta !== null ? evt.beta : 0;
  104884. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  104885. };
  104886. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  104887. this._orientationChanged();
  104888. }
  104889. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  104890. /**
  104891. * Define the camera controlled by the input.
  104892. */
  104893. get: function () {
  104894. return this._camera;
  104895. },
  104896. set: function (camera) {
  104897. this._camera = camera;
  104898. if (this._camera != null && !this._camera.rotationQuaternion) {
  104899. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  104900. }
  104901. },
  104902. enumerable: true,
  104903. configurable: true
  104904. });
  104905. /**
  104906. * Attach the input controls to a specific dom element to get the input from.
  104907. * @param element Defines the element the controls should be listened from
  104908. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  104909. */
  104910. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  104911. window.addEventListener("orientationchange", this._orientationChanged);
  104912. window.addEventListener("deviceorientation", this._deviceOrientation);
  104913. //In certain cases, the attach control is called AFTER orientation was changed,
  104914. //So this is needed.
  104915. this._orientationChanged();
  104916. };
  104917. /**
  104918. * Detach the current controls from the specified dom element.
  104919. * @param element Defines the element to stop listening the inputs from
  104920. */
  104921. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  104922. window.removeEventListener("orientationchange", this._orientationChanged);
  104923. window.removeEventListener("deviceorientation", this._deviceOrientation);
  104924. };
  104925. /**
  104926. * Update the current camera state depending on the inputs that have been used this frame.
  104927. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  104928. */
  104929. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  104930. //if no device orientation provided, don't update the rotation.
  104931. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  104932. if (!this._alpha) {
  104933. return;
  104934. }
  104935. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  104936. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  104937. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  104938. //Mirror on XY Plane
  104939. this._camera.rotationQuaternion.z *= -1;
  104940. this._camera.rotationQuaternion.w *= -1;
  104941. };
  104942. /**
  104943. * Gets the class name of the current intput.
  104944. * @returns the class name
  104945. */
  104946. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  104947. return "FreeCameraDeviceOrientationInput";
  104948. };
  104949. /**
  104950. * Get the friendly name associated with the input class.
  104951. * @returns the input friendly name
  104952. */
  104953. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  104954. return "deviceOrientation";
  104955. };
  104956. return FreeCameraDeviceOrientationInput;
  104957. }());
  104958. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  104959. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  104960. })(BABYLON || (BABYLON = {}));
  104961. //# sourceMappingURL=freeCameraDeviceOrientationInput.js.map
  104962. var BABYLON;
  104963. (function (BABYLON) {
  104964. /**
  104965. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  104966. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  104967. */
  104968. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  104969. /**
  104970. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  104971. */
  104972. function ArcRotateCameraVRDeviceOrientationInput() {
  104973. /**
  104974. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  104975. */
  104976. this.alphaCorrection = 1;
  104977. /**
  104978. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  104979. */
  104980. this.gammaCorrection = 1;
  104981. this._alpha = 0;
  104982. this._gamma = 0;
  104983. this._dirty = false;
  104984. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  104985. }
  104986. /**
  104987. * Attach the input controls to a specific dom element to get the input from.
  104988. * @param element Defines the element the controls should be listened from
  104989. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  104990. */
  104991. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  104992. this.camera.attachControl(element, noPreventDefault);
  104993. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  104994. };
  104995. /** @hidden */
  104996. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  104997. if (evt.alpha !== null) {
  104998. this._alpha = (+evt.alpha | 0) * this.alphaCorrection;
  104999. }
  105000. if (evt.gamma !== null) {
  105001. this._gamma = (+evt.gamma | 0) * this.gammaCorrection;
  105002. }
  105003. this._dirty = true;
  105004. };
  105005. /**
  105006. * Update the current camera state depending on the inputs that have been used this frame.
  105007. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  105008. */
  105009. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  105010. if (this._dirty) {
  105011. this._dirty = false;
  105012. if (this._gamma < 0) {
  105013. this._gamma = 180 + this._gamma;
  105014. }
  105015. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  105016. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  105017. }
  105018. };
  105019. /**
  105020. * Detach the current controls from the specified dom element.
  105021. * @param element Defines the element to stop listening the inputs from
  105022. */
  105023. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  105024. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  105025. };
  105026. /**
  105027. * Gets the class name of the current intput.
  105028. * @returns the class name
  105029. */
  105030. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  105031. return "ArcRotateCameraVRDeviceOrientationInput";
  105032. };
  105033. /**
  105034. * Get the friendly name associated with the input class.
  105035. * @returns the input friendly name
  105036. */
  105037. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  105038. return "VRDeviceOrientation";
  105039. };
  105040. return ArcRotateCameraVRDeviceOrientationInput;
  105041. }());
  105042. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  105043. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  105044. })(BABYLON || (BABYLON = {}));
  105045. //# sourceMappingURL=arcRotateCameraVRDeviceOrientationInput.js.map
  105046. var BABYLON;
  105047. (function (BABYLON) {
  105048. /**
  105049. * This represents all the required metrics to create a VR camera.
  105050. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  105051. */
  105052. var VRCameraMetrics = /** @class */ (function () {
  105053. function VRCameraMetrics() {
  105054. /**
  105055. * Define if the current vr camera should compensate the distortion of the lense or not.
  105056. */
  105057. this.compensateDistortion = true;
  105058. }
  105059. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  105060. /**
  105061. * Gets the rendering aspect ratio based on the provided resolutions.
  105062. */
  105063. get: function () {
  105064. return this.hResolution / (2 * this.vResolution);
  105065. },
  105066. enumerable: true,
  105067. configurable: true
  105068. });
  105069. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  105070. /**
  105071. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  105072. */
  105073. get: function () {
  105074. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  105075. },
  105076. enumerable: true,
  105077. configurable: true
  105078. });
  105079. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  105080. /**
  105081. * @hidden
  105082. */
  105083. get: function () {
  105084. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  105085. var h = (4 * meters) / this.hScreenSize;
  105086. return BABYLON.Matrix.Translation(h, 0, 0);
  105087. },
  105088. enumerable: true,
  105089. configurable: true
  105090. });
  105091. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  105092. /**
  105093. * @hidden
  105094. */
  105095. get: function () {
  105096. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  105097. var h = (4 * meters) / this.hScreenSize;
  105098. return BABYLON.Matrix.Translation(-h, 0, 0);
  105099. },
  105100. enumerable: true,
  105101. configurable: true
  105102. });
  105103. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  105104. /**
  105105. * @hidden
  105106. */
  105107. get: function () {
  105108. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  105109. },
  105110. enumerable: true,
  105111. configurable: true
  105112. });
  105113. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  105114. /**
  105115. * @hidden
  105116. */
  105117. get: function () {
  105118. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  105119. },
  105120. enumerable: true,
  105121. configurable: true
  105122. });
  105123. /**
  105124. * Get the default VRMetrics based on the most generic setup.
  105125. * @returns the default vr metrics
  105126. */
  105127. VRCameraMetrics.GetDefault = function () {
  105128. var result = new VRCameraMetrics();
  105129. result.hResolution = 1280;
  105130. result.vResolution = 800;
  105131. result.hScreenSize = 0.149759993;
  105132. result.vScreenSize = 0.0935999975;
  105133. result.vScreenCenter = 0.0467999987;
  105134. result.eyeToScreenDistance = 0.0410000011;
  105135. result.lensSeparationDistance = 0.0635000020;
  105136. result.interpupillaryDistance = 0.0640000030;
  105137. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  105138. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  105139. result.postProcessScaleFactor = 1.714605507808412;
  105140. result.lensCenterOffset = 0.151976421;
  105141. return result;
  105142. };
  105143. return VRCameraMetrics;
  105144. }());
  105145. BABYLON.VRCameraMetrics = VRCameraMetrics;
  105146. })(BABYLON || (BABYLON = {}));
  105147. //# sourceMappingURL=vrCameraMetrics.js.map
  105148. var BABYLON;
  105149. (function (BABYLON) {
  105150. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  105151. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  105152. });
  105153. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  105154. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  105155. });
  105156. /**
  105157. * This represents a WebVR camera.
  105158. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  105159. * @example http://doc.babylonjs.com/how_to/webvr_camera
  105160. */
  105161. var WebVRFreeCamera = /** @class */ (function (_super) {
  105162. __extends(WebVRFreeCamera, _super);
  105163. /**
  105164. * Instantiates a WebVRFreeCamera.
  105165. * @param name The name of the WebVRFreeCamera
  105166. * @param position The starting anchor position for the camera
  105167. * @param scene The scene the camera belongs to
  105168. * @param webVROptions a set of customizable options for the webVRCamera
  105169. */
  105170. function WebVRFreeCamera(name, position, scene, webVROptions) {
  105171. if (webVROptions === void 0) { webVROptions = {}; }
  105172. var _this = _super.call(this, name, position, scene) || this;
  105173. _this.webVROptions = webVROptions;
  105174. /**
  105175. * @hidden
  105176. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  105177. */
  105178. _this._vrDevice = null;
  105179. /**
  105180. * The rawPose of the vrDevice.
  105181. */
  105182. _this.rawPose = null;
  105183. _this._specsVersion = "1.1";
  105184. _this._attached = false;
  105185. _this._descendants = [];
  105186. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  105187. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  105188. /** @hidden */
  105189. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  105190. _this._standingMatrix = null;
  105191. /**
  105192. * Represents device position in babylon space.
  105193. */
  105194. _this.devicePosition = BABYLON.Vector3.Zero();
  105195. /**
  105196. * Represents device rotation in babylon space.
  105197. */
  105198. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  105199. /**
  105200. * The scale of the device to be used when translating from device space to babylon space.
  105201. */
  105202. _this.deviceScaleFactor = 1;
  105203. _this._deviceToWorld = BABYLON.Matrix.Identity();
  105204. _this._worldToDevice = BABYLON.Matrix.Identity();
  105205. /**
  105206. * References to the webVR controllers for the vrDevice.
  105207. */
  105208. _this.controllers = [];
  105209. /**
  105210. * Emits an event when a controller is attached.
  105211. */
  105212. _this.onControllersAttachedObservable = new BABYLON.Observable();
  105213. /**
  105214. * Emits an event when a controller's mesh has been loaded;
  105215. */
  105216. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  105217. /**
  105218. * Emits an event when the HMD's pose has been updated.
  105219. */
  105220. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  105221. _this._poseSet = false;
  105222. /**
  105223. * If the rig cameras be used as parent instead of this camera.
  105224. */
  105225. _this.rigParenting = true;
  105226. _this._defaultHeight = undefined;
  105227. _this._htmlElementAttached = null;
  105228. _this._detachIfAttached = function () {
  105229. var vrDisplay = _this.getEngine().getVRDevice();
  105230. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  105231. _this.detachControl(_this._htmlElementAttached);
  105232. }
  105233. };
  105234. _this._workingVector = BABYLON.Vector3.Zero();
  105235. _this._oneVector = BABYLON.Vector3.One();
  105236. _this._workingMatrix = BABYLON.Matrix.Identity();
  105237. _this._tmpMatrix = new BABYLON.Matrix();
  105238. _this._cache.position = BABYLON.Vector3.Zero();
  105239. if (webVROptions.defaultHeight) {
  105240. _this._defaultHeight = webVROptions.defaultHeight;
  105241. _this.position.y = _this._defaultHeight;
  105242. }
  105243. _this.minZ = 0.1;
  105244. //legacy support - the compensation boolean was removed.
  105245. if (arguments.length === 5) {
  105246. _this.webVROptions = arguments[4];
  105247. }
  105248. // default webVR options
  105249. if (_this.webVROptions.trackPosition == undefined) {
  105250. _this.webVROptions.trackPosition = true;
  105251. }
  105252. if (_this.webVROptions.controllerMeshes == undefined) {
  105253. _this.webVROptions.controllerMeshes = true;
  105254. }
  105255. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  105256. _this.webVROptions.defaultLightingOnControllers = true;
  105257. }
  105258. _this.rotationQuaternion = new BABYLON.Quaternion();
  105259. if (_this.webVROptions && _this.webVROptions.positionScale) {
  105260. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  105261. }
  105262. //enable VR
  105263. var engine = _this.getEngine();
  105264. _this._onVREnabled = function (success) { if (success) {
  105265. _this.initControllers();
  105266. } };
  105267. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  105268. engine.initWebVR().add(function (event) {
  105269. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  105270. return;
  105271. }
  105272. _this._vrDevice = event.vrDisplay;
  105273. //reset the rig parameters.
  105274. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  105275. if (_this._attached) {
  105276. _this.getEngine().enableVR();
  105277. }
  105278. });
  105279. if (typeof (VRFrameData) !== "undefined") {
  105280. _this._frameData = new VRFrameData();
  105281. }
  105282. /**
  105283. * The idea behind the following lines:
  105284. * objects that have the camera as parent should actually have the rig cameras as a parent.
  105285. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  105286. * the second will not show it correctly.
  105287. *
  105288. * To solve this - each object that has the camera as parent will be added to a protected array.
  105289. * When the rig camera renders, it will take this array and set all of those to be its children.
  105290. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  105291. * Amazing!
  105292. */
  105293. scene.onBeforeCameraRenderObservable.add(function (camera) {
  105294. if (camera.parent === _this && _this.rigParenting) {
  105295. _this._descendants = _this.getDescendants(true, function (n) {
  105296. // don't take the cameras or the controllers!
  105297. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  105298. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  105299. return !isController && !isRigCamera;
  105300. });
  105301. _this._descendants.forEach(function (node) {
  105302. node.parent = camera;
  105303. });
  105304. }
  105305. });
  105306. scene.onAfterCameraRenderObservable.add(function (camera) {
  105307. if (camera.parent === _this && _this.rigParenting) {
  105308. _this._descendants.forEach(function (node) {
  105309. node.parent = _this;
  105310. });
  105311. }
  105312. });
  105313. return _this;
  105314. }
  105315. /**
  105316. * Gets the device distance from the ground in meters.
  105317. * @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.
  105318. */
  105319. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  105320. if (this._standingMatrix) {
  105321. // Add standing matrix offset to get real offset from ground in room
  105322. this._standingMatrix.getTranslationToRef(this._workingVector);
  105323. return this._deviceRoomPosition.y + this._workingVector.y;
  105324. }
  105325. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  105326. return this._defaultHeight || 0;
  105327. };
  105328. /**
  105329. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  105330. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  105331. */
  105332. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  105333. var _this = this;
  105334. if (callback === void 0) { callback = function (bool) { }; }
  105335. // Use standing matrix if available
  105336. this.getEngine().initWebVRAsync().then(function (result) {
  105337. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  105338. callback(false);
  105339. }
  105340. else {
  105341. _this._standingMatrix = new BABYLON.Matrix();
  105342. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  105343. if (!_this.getScene().useRightHandedSystem) {
  105344. if (_this._standingMatrix) {
  105345. _this._standingMatrix.toggleModelMatrixHandInPlace();
  105346. }
  105347. }
  105348. callback(true);
  105349. }
  105350. });
  105351. };
  105352. /**
  105353. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  105354. * @returns A promise with a boolean set to if the standing matrix is supported.
  105355. */
  105356. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  105357. var _this = this;
  105358. return new Promise(function (res, rej) {
  105359. _this.useStandingMatrix(function (supported) {
  105360. res(supported);
  105361. });
  105362. });
  105363. };
  105364. /**
  105365. * Disposes the camera
  105366. */
  105367. WebVRFreeCamera.prototype.dispose = function () {
  105368. this._detachIfAttached();
  105369. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  105370. if (this._updateCacheWhenTrackingDisabledObserver) {
  105371. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  105372. }
  105373. _super.prototype.dispose.call(this);
  105374. };
  105375. /**
  105376. * Gets a vrController by name.
  105377. * @param name The name of the controller to retreive
  105378. * @returns the controller matching the name specified or null if not found
  105379. */
  105380. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  105381. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  105382. var gp = _a[_i];
  105383. if (gp.hand === name) {
  105384. return gp;
  105385. }
  105386. }
  105387. return null;
  105388. };
  105389. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  105390. /**
  105391. * The controller corrisponding to the users left hand.
  105392. */
  105393. get: function () {
  105394. if (!this._leftController) {
  105395. this._leftController = this.getControllerByName("left");
  105396. }
  105397. return this._leftController;
  105398. },
  105399. enumerable: true,
  105400. configurable: true
  105401. });
  105402. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  105403. /**
  105404. * The controller corrisponding to the users right hand.
  105405. */
  105406. get: function () {
  105407. if (!this._rightController) {
  105408. this._rightController = this.getControllerByName("right");
  105409. }
  105410. return this._rightController;
  105411. },
  105412. enumerable: true,
  105413. configurable: true
  105414. });
  105415. /**
  105416. * Casts a ray forward from the vrCamera's gaze.
  105417. * @param length Length of the ray (default: 100)
  105418. * @returns the ray corrisponding to the gaze
  105419. */
  105420. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  105421. if (length === void 0) { length = 100; }
  105422. if (this.leftCamera) {
  105423. // Use left eye to avoid computation to compute center on every call
  105424. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  105425. }
  105426. else {
  105427. return _super.prototype.getForwardRay.call(this, length);
  105428. }
  105429. };
  105430. /**
  105431. * @hidden
  105432. * Updates the camera based on device's frame data
  105433. */
  105434. WebVRFreeCamera.prototype._checkInputs = function () {
  105435. if (this._vrDevice && this._vrDevice.isPresenting) {
  105436. this._vrDevice.getFrameData(this._frameData);
  105437. this.updateFromDevice(this._frameData.pose);
  105438. }
  105439. _super.prototype._checkInputs.call(this);
  105440. };
  105441. /**
  105442. * Updates the poseControlled values based on the input device pose.
  105443. * @param poseData Pose coming from the device
  105444. */
  105445. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  105446. if (poseData && poseData.orientation) {
  105447. this.rawPose = poseData;
  105448. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  105449. if (this.getScene().useRightHandedSystem) {
  105450. this._deviceRoomRotationQuaternion.z *= -1;
  105451. this._deviceRoomRotationQuaternion.w *= -1;
  105452. }
  105453. if (this.webVROptions.trackPosition && this.rawPose.position) {
  105454. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  105455. if (this.getScene().useRightHandedSystem) {
  105456. this._deviceRoomPosition.z *= -1;
  105457. }
  105458. }
  105459. this._poseSet = true;
  105460. }
  105461. };
  105462. /**
  105463. * WebVR's attach control will start broadcasting frames to the device.
  105464. * Note that in certain browsers (chrome for example) this function must be called
  105465. * within a user-interaction callback. Example:
  105466. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  105467. *
  105468. * @param element html element to attach the vrDevice to
  105469. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  105470. */
  105471. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  105472. _super.prototype.attachControl.call(this, element, noPreventDefault);
  105473. this._attached = true;
  105474. this._htmlElementAttached = element;
  105475. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  105476. if (this._vrDevice) {
  105477. this.getEngine().enableVR();
  105478. }
  105479. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  105480. };
  105481. /**
  105482. * Detaches the camera from the html element and disables VR
  105483. *
  105484. * @param element html element to detach from
  105485. */
  105486. WebVRFreeCamera.prototype.detachControl = function (element) {
  105487. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  105488. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  105489. _super.prototype.detachControl.call(this, element);
  105490. this._attached = false;
  105491. this.getEngine().disableVR();
  105492. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  105493. };
  105494. /**
  105495. * @returns the name of this class
  105496. */
  105497. WebVRFreeCamera.prototype.getClassName = function () {
  105498. return "WebVRFreeCamera";
  105499. };
  105500. /**
  105501. * Calls resetPose on the vrDisplay
  105502. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  105503. */
  105504. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  105505. //uses the vrDisplay's "resetPose()".
  105506. //pitch and roll won't be affected.
  105507. this._vrDevice.resetPose();
  105508. };
  105509. /**
  105510. * @hidden
  105511. * Updates the rig cameras (left and right eye)
  105512. */
  105513. WebVRFreeCamera.prototype._updateRigCameras = function () {
  105514. var camLeft = this._rigCameras[0];
  105515. var camRight = this._rigCameras[1];
  105516. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  105517. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  105518. camLeft.position.copyFrom(this._deviceRoomPosition);
  105519. camRight.position.copyFrom(this._deviceRoomPosition);
  105520. };
  105521. // Remove translation from 6dof headset if trackposition is set to false
  105522. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  105523. if (isViewMatrix === void 0) { isViewMatrix = false; }
  105524. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  105525. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  105526. if (!isViewMatrix) {
  105527. this._tmpMatrix.invert();
  105528. }
  105529. this._tmpMatrix.multiplyToRef(matrix, matrix);
  105530. }
  105531. };
  105532. /**
  105533. * @hidden
  105534. * Updates the cached values of the camera
  105535. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  105536. */
  105537. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  105538. var _this = this;
  105539. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  105540. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  105541. if (!this.updateCacheCalled) {
  105542. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  105543. this.updateCacheCalled = true;
  105544. this.update();
  105545. }
  105546. // Set working vector to the device position in room space rotated by the new rotation
  105547. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  105548. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  105549. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  105550. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  105551. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  105552. // Add translation from anchor position
  105553. this._deviceToWorld.getTranslationToRef(this._workingVector);
  105554. this._workingVector.addInPlace(this.position);
  105555. this._workingVector.subtractInPlace(this._cache.position);
  105556. this._deviceToWorld.setTranslation(this._workingVector);
  105557. // Set an inverted matrix to be used when updating the camera
  105558. this._deviceToWorld.invertToRef(this._worldToDevice);
  105559. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  105560. this.controllers.forEach(function (controller) {
  105561. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  105562. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  105563. controller.update();
  105564. });
  105565. }
  105566. if (!ignoreParentClass) {
  105567. _super.prototype._updateCache.call(this);
  105568. }
  105569. this.updateCacheCalled = false;
  105570. };
  105571. /**
  105572. * @hidden
  105573. * Get current device position in babylon world
  105574. */
  105575. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  105576. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  105577. };
  105578. /**
  105579. * Updates the current device position and rotation in the babylon world
  105580. */
  105581. WebVRFreeCamera.prototype.update = function () {
  105582. this._computeDevicePosition();
  105583. // Get current device rotation in babylon world
  105584. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  105585. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  105586. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  105587. if (this._poseSet) {
  105588. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  105589. }
  105590. _super.prototype.update.call(this);
  105591. };
  105592. /**
  105593. * @hidden
  105594. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  105595. * @returns an identity matrix
  105596. */
  105597. WebVRFreeCamera.prototype._getViewMatrix = function () {
  105598. return BABYLON.Matrix.Identity();
  105599. };
  105600. /**
  105601. * This function is called by the two RIG cameras.
  105602. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  105603. */
  105604. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  105605. // Update the parent camera prior to using a child camera to avoid desynchronization
  105606. var parentCamera = this._cameraRigParams["parentCamera"];
  105607. parentCamera._updateCache();
  105608. //WebVR 1.1
  105609. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  105610. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  105611. if (!this.getScene().useRightHandedSystem) {
  105612. this._webvrViewMatrix.toggleModelMatrixHandInPlace();
  105613. }
  105614. // update the camera rotation matrix
  105615. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  105616. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  105617. // Computing target and final matrix
  105618. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  105619. // should the view matrix be updated with scale and position offset?
  105620. if (parentCamera.deviceScaleFactor !== 1) {
  105621. this._webvrViewMatrix.invert();
  105622. // scale the position, if set
  105623. if (parentCamera.deviceScaleFactor) {
  105624. this._webvrViewMatrix.multiplyAtIndex(12, parentCamera.deviceScaleFactor);
  105625. this._webvrViewMatrix.multiplyAtIndex(13, parentCamera.deviceScaleFactor);
  105626. this._webvrViewMatrix.multiplyAtIndex(14, parentCamera.deviceScaleFactor);
  105627. }
  105628. this._webvrViewMatrix.invert();
  105629. }
  105630. // Remove translation from 6dof headset if trackposition is set to false
  105631. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  105632. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  105633. // Compute global position
  105634. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  105635. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  105636. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  105637. this._workingMatrix.getTranslationToRef(this._globalPosition);
  105638. this._markSyncedWithParent();
  105639. return this._webvrViewMatrix;
  105640. };
  105641. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  105642. var parentCamera = this.parent;
  105643. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  105644. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  105645. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  105646. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  105647. //babylon compatible matrix
  105648. if (!this.getScene().useRightHandedSystem) {
  105649. this._projectionMatrix.toggleProjectionMatrixHandInPlace();
  105650. }
  105651. return this._projectionMatrix;
  105652. };
  105653. /**
  105654. * Initializes the controllers and their meshes
  105655. */
  105656. WebVRFreeCamera.prototype.initControllers = function () {
  105657. var _this = this;
  105658. this.controllers = [];
  105659. var manager = this.getScene().gamepadManager;
  105660. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  105661. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  105662. var webVrController = gamepad;
  105663. if (webVrController.defaultModel) {
  105664. webVrController.defaultModel.setEnabled(false);
  105665. }
  105666. if (webVrController.hand === "right") {
  105667. _this._rightController = null;
  105668. }
  105669. if (webVrController.hand === "left") {
  105670. _this._leftController = null;
  105671. }
  105672. var controllerIndex = _this.controllers.indexOf(webVrController);
  105673. if (controllerIndex !== -1) {
  105674. _this.controllers.splice(controllerIndex, 1);
  105675. }
  105676. }
  105677. });
  105678. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  105679. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  105680. var webVrController_1 = gamepad;
  105681. if (!_this.webVROptions.trackPosition) {
  105682. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  105683. // Cache must be updated before rendering controllers to avoid them being one frame behind
  105684. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  105685. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  105686. _this._updateCache();
  105687. });
  105688. }
  105689. }
  105690. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  105691. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  105692. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  105693. if (_this.webVROptions.controllerMeshes) {
  105694. if (webVrController_1.defaultModel) {
  105695. webVrController_1.defaultModel.setEnabled(true);
  105696. }
  105697. else {
  105698. // Load the meshes
  105699. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  105700. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  105701. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  105702. if (_this.webVROptions.defaultLightingOnControllers) {
  105703. if (!_this._lightOnControllers) {
  105704. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  105705. }
  105706. var activateLightOnSubMeshes_1 = function (mesh, light) {
  105707. var children = mesh.getChildren();
  105708. if (children && children.length !== 0) {
  105709. children.forEach(function (mesh) {
  105710. light.includedOnlyMeshes.push(mesh);
  105711. activateLightOnSubMeshes_1(mesh, light);
  105712. });
  105713. }
  105714. };
  105715. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  105716. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  105717. }
  105718. });
  105719. }
  105720. }
  105721. webVrController_1.attachToPoseControlledCamera(_this);
  105722. // since this is async - sanity check. Is the controller already stored?
  105723. if (_this.controllers.indexOf(webVrController_1) === -1) {
  105724. //add to the controllers array
  105725. _this.controllers.push(webVrController_1);
  105726. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  105727. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  105728. // So we're overriding setting left & right manually to be sure
  105729. var firstViveWandDetected = false;
  105730. for (var i = 0; i < _this.controllers.length; i++) {
  105731. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  105732. if (!firstViveWandDetected) {
  105733. firstViveWandDetected = true;
  105734. _this.controllers[i].hand = "left";
  105735. }
  105736. else {
  105737. _this.controllers[i].hand = "right";
  105738. }
  105739. }
  105740. }
  105741. //did we find enough controllers? Great! let the developer know.
  105742. if (_this.controllers.length >= 2) {
  105743. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  105744. }
  105745. }
  105746. }
  105747. });
  105748. };
  105749. return WebVRFreeCamera;
  105750. }(BABYLON.FreeCamera));
  105751. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  105752. })(BABYLON || (BABYLON = {}));
  105753. //# sourceMappingURL=webVRCamera.js.map
  105754. var BABYLON;
  105755. (function (BABYLON) {
  105756. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  105757. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  105758. });
  105759. // We're mainly based on the logic defined into the FreeCamera code
  105760. /**
  105761. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  105762. * being tilted forward or back and left or right.
  105763. */
  105764. var DeviceOrientationCamera = /** @class */ (function (_super) {
  105765. __extends(DeviceOrientationCamera, _super);
  105766. /**
  105767. * Creates a new device orientation camera
  105768. * @param name The name of the camera
  105769. * @param position The start position camera
  105770. * @param scene The scene the camera belongs to
  105771. */
  105772. function DeviceOrientationCamera(name, position, scene) {
  105773. var _this = _super.call(this, name, position, scene) || this;
  105774. _this._quaternionCache = new BABYLON.Quaternion();
  105775. _this.inputs.addDeviceOrientation();
  105776. return _this;
  105777. }
  105778. /**
  105779. * Gets the current instance class name ("DeviceOrientationCamera").
  105780. * This helps avoiding instanceof at run time.
  105781. * @returns the class name
  105782. */
  105783. DeviceOrientationCamera.prototype.getClassName = function () {
  105784. return "DeviceOrientationCamera";
  105785. };
  105786. /**
  105787. * @hidden
  105788. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  105789. */
  105790. DeviceOrientationCamera.prototype._checkInputs = function () {
  105791. _super.prototype._checkInputs.call(this);
  105792. this._quaternionCache.copyFrom(this.rotationQuaternion);
  105793. if (this._initialQuaternion) {
  105794. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  105795. }
  105796. };
  105797. /**
  105798. * Reset the camera to its default orientation on the specified axis only.
  105799. * @param axis The axis to reset
  105800. */
  105801. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  105802. var _this = this;
  105803. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  105804. //can only work if this camera has a rotation quaternion already.
  105805. if (!this.rotationQuaternion) {
  105806. return;
  105807. }
  105808. if (!this._initialQuaternion) {
  105809. this._initialQuaternion = new BABYLON.Quaternion();
  105810. }
  105811. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  105812. ['x', 'y', 'z'].forEach(function (axisName) {
  105813. if (!axis[axisName]) {
  105814. _this._initialQuaternion[axisName] = 0;
  105815. }
  105816. else {
  105817. _this._initialQuaternion[axisName] *= -1;
  105818. }
  105819. });
  105820. this._initialQuaternion.normalize();
  105821. //force rotation update
  105822. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  105823. };
  105824. return DeviceOrientationCamera;
  105825. }(BABYLON.FreeCamera));
  105826. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  105827. })(BABYLON || (BABYLON = {}));
  105828. //# sourceMappingURL=deviceOrientationCamera.js.map
  105829. var BABYLON;
  105830. (function (BABYLON) {
  105831. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  105832. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  105833. });
  105834. /**
  105835. * Camera used to simulate VR rendering (based on FreeCamera)
  105836. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  105837. */
  105838. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  105839. __extends(VRDeviceOrientationFreeCamera, _super);
  105840. /**
  105841. * Creates a new VRDeviceOrientationFreeCamera
  105842. * @param name defines camera name
  105843. * @param position defines the start position of the camera
  105844. * @param scene defines the scene the camera belongs to
  105845. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  105846. * @param vrCameraMetrics defines the vr metrics associated to the camera
  105847. */
  105848. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  105849. if (compensateDistortion === void 0) { compensateDistortion = true; }
  105850. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  105851. var _this = _super.call(this, name, position, scene) || this;
  105852. vrCameraMetrics.compensateDistortion = compensateDistortion;
  105853. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  105854. return _this;
  105855. }
  105856. /**
  105857. * Gets camera class name
  105858. * @returns VRDeviceOrientationFreeCamera
  105859. */
  105860. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  105861. return "VRDeviceOrientationFreeCamera";
  105862. };
  105863. return VRDeviceOrientationFreeCamera;
  105864. }(BABYLON.DeviceOrientationCamera));
  105865. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  105866. })(BABYLON || (BABYLON = {}));
  105867. //# sourceMappingURL=vrDeviceOrientationFreeCamera.js.map
  105868. var BABYLON;
  105869. (function (BABYLON) {
  105870. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  105871. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  105872. });
  105873. /**
  105874. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  105875. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  105876. */
  105877. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  105878. __extends(VRDeviceOrientationArcRotateCamera, _super);
  105879. /**
  105880. * Creates a new VRDeviceOrientationArcRotateCamera
  105881. * @param name defines camera name
  105882. * @param alpha defines the camera rotation along the logitudinal axis
  105883. * @param beta defines the camera rotation along the latitudinal axis
  105884. * @param radius defines the camera distance from its target
  105885. * @param target defines the camera target
  105886. * @param scene defines the scene the camera belongs to
  105887. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  105888. * @param vrCameraMetrics defines the vr metrics associated to the camera
  105889. */
  105890. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  105891. if (compensateDistortion === void 0) { compensateDistortion = true; }
  105892. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  105893. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  105894. vrCameraMetrics.compensateDistortion = compensateDistortion;
  105895. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  105896. _this.inputs.addVRDeviceOrientation();
  105897. return _this;
  105898. }
  105899. /**
  105900. * Gets camera class name
  105901. * @returns VRDeviceOrientationArcRotateCamera
  105902. */
  105903. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  105904. return "VRDeviceOrientationArcRotateCamera";
  105905. };
  105906. return VRDeviceOrientationArcRotateCamera;
  105907. }(BABYLON.ArcRotateCamera));
  105908. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  105909. })(BABYLON || (BABYLON = {}));
  105910. //# sourceMappingURL=vrDeviceOrientationArcRotateCamera.js.map
  105911. var BABYLON;
  105912. (function (BABYLON) {
  105913. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  105914. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  105915. });
  105916. /**
  105917. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  105918. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  105919. */
  105920. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  105921. __extends(VRDeviceOrientationGamepadCamera, _super);
  105922. /**
  105923. * Creates a new VRDeviceOrientationGamepadCamera
  105924. * @param name defines camera name
  105925. * @param position defines the start position of the camera
  105926. * @param scene defines the scene the camera belongs to
  105927. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  105928. * @param vrCameraMetrics defines the vr metrics associated to the camera
  105929. */
  105930. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  105931. if (compensateDistortion === void 0) { compensateDistortion = true; }
  105932. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  105933. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  105934. _this.inputs.addGamepad();
  105935. return _this;
  105936. }
  105937. /**
  105938. * Gets camera class name
  105939. * @returns VRDeviceOrientationGamepadCamera
  105940. */
  105941. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  105942. return "VRDeviceOrientationGamepadCamera";
  105943. };
  105944. return VRDeviceOrientationGamepadCamera;
  105945. }(BABYLON.VRDeviceOrientationFreeCamera));
  105946. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  105947. })(BABYLON || (BABYLON = {}));
  105948. //# sourceMappingURL=vrDeviceOrientationGamepadCamera.js.map
  105949. var BABYLON;
  105950. (function (BABYLON) {
  105951. var VRExperienceHelperGazer = /** @class */ (function () {
  105952. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  105953. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  105954. this.scene = scene;
  105955. /** @hidden */
  105956. this._pointerDownOnMeshAsked = false;
  105957. /** @hidden */
  105958. this._isActionableMesh = false;
  105959. /** @hidden */
  105960. this._teleportationRequestInitiated = false;
  105961. /** @hidden */
  105962. this._teleportationBackRequestInitiated = false;
  105963. /** @hidden */
  105964. this._rotationRightAsked = false;
  105965. /** @hidden */
  105966. this._rotationLeftAsked = false;
  105967. /** @hidden */
  105968. this._dpadPressed = true;
  105969. /** @hidden */
  105970. this._activePointer = false;
  105971. this._id = VRExperienceHelperGazer._idCounter++;
  105972. // Gaze tracker
  105973. if (!gazeTrackerToClone) {
  105974. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  105975. this._gazeTracker.bakeCurrentTransformIntoVertices();
  105976. this._gazeTracker.isPickable = false;
  105977. this._gazeTracker.isVisible = false;
  105978. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  105979. targetMat.specularColor = BABYLON.Color3.Black();
  105980. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  105981. targetMat.backFaceCulling = false;
  105982. this._gazeTracker.material = targetMat;
  105983. }
  105984. else {
  105985. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  105986. }
  105987. }
  105988. /** @hidden */
  105989. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  105990. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  105991. };
  105992. /** @hidden */
  105993. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  105994. this._pointerDownOnMeshAsked = true;
  105995. if (this._currentHit) {
  105996. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  105997. }
  105998. };
  105999. /** @hidden */
  106000. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  106001. if (this._currentHit) {
  106002. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  106003. }
  106004. this._pointerDownOnMeshAsked = false;
  106005. };
  106006. /** @hidden */
  106007. VRExperienceHelperGazer.prototype._activatePointer = function () {
  106008. this._activePointer = true;
  106009. };
  106010. /** @hidden */
  106011. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  106012. this._activePointer = false;
  106013. };
  106014. /** @hidden */
  106015. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  106016. if (distance === void 0) { distance = 100; }
  106017. };
  106018. VRExperienceHelperGazer.prototype.dispose = function () {
  106019. this._interactionsEnabled = false;
  106020. this._teleportationEnabled = false;
  106021. if (this._gazeTracker) {
  106022. this._gazeTracker.dispose();
  106023. }
  106024. };
  106025. VRExperienceHelperGazer._idCounter = 0;
  106026. return VRExperienceHelperGazer;
  106027. }());
  106028. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  106029. __extends(VRExperienceHelperControllerGazer, _super);
  106030. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  106031. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  106032. _this.webVRController = webVRController;
  106033. // Laser pointer
  106034. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  106035. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  106036. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  106037. laserPointerMaterial.alpha = 0.6;
  106038. _this._laserPointer.material = laserPointerMaterial;
  106039. _this._laserPointer.rotation.x = Math.PI / 2;
  106040. _this._laserPointer.position.z = -0.5;
  106041. _this._laserPointer.isVisible = false;
  106042. _this._laserPointer.isPickable = false;
  106043. if (!webVRController.mesh) {
  106044. // Create an empty mesh that is used prior to loading the high quality model
  106045. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  106046. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  106047. preloadPointerPose.rotation.x = -0.7;
  106048. preloadMesh.addChild(preloadPointerPose);
  106049. webVRController.attachToMesh(preloadMesh);
  106050. }
  106051. _this._setLaserPointerParent(webVRController.mesh);
  106052. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  106053. _this._setLaserPointerParent(mesh);
  106054. });
  106055. return _this;
  106056. }
  106057. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  106058. return this.webVRController.getForwardRay(length);
  106059. };
  106060. /** @hidden */
  106061. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  106062. _super.prototype._activatePointer.call(this);
  106063. this._laserPointer.isVisible = true;
  106064. };
  106065. /** @hidden */
  106066. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  106067. _super.prototype._deactivatePointer.call(this);
  106068. this._laserPointer.isVisible = false;
  106069. };
  106070. /** @hidden */
  106071. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  106072. this._laserPointer.material.emissiveColor = color;
  106073. };
  106074. /** @hidden */
  106075. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  106076. var makeNotPick = function (root) {
  106077. root.isPickable = false;
  106078. root.getChildMeshes().forEach(function (c) {
  106079. makeNotPick(c);
  106080. });
  106081. };
  106082. makeNotPick(mesh);
  106083. var childMeshes = mesh.getChildMeshes();
  106084. this.webVRController._pointingPoseNode = null;
  106085. for (var i = 0; i < childMeshes.length; i++) {
  106086. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  106087. mesh = childMeshes[i];
  106088. this.webVRController._pointingPoseNode = mesh;
  106089. break;
  106090. }
  106091. }
  106092. this._laserPointer.parent = mesh;
  106093. };
  106094. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  106095. if (distance === void 0) { distance = 100; }
  106096. this._laserPointer.scaling.y = distance;
  106097. this._laserPointer.position.z = -distance / 2;
  106098. };
  106099. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  106100. _super.prototype.dispose.call(this);
  106101. this._laserPointer.dispose();
  106102. if (this._meshAttachedObserver) {
  106103. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  106104. }
  106105. };
  106106. return VRExperienceHelperControllerGazer;
  106107. }(VRExperienceHelperGazer));
  106108. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  106109. __extends(VRExperienceHelperCameraGazer, _super);
  106110. function VRExperienceHelperCameraGazer(getCamera, scene) {
  106111. var _this = _super.call(this, scene) || this;
  106112. _this.getCamera = getCamera;
  106113. return _this;
  106114. }
  106115. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  106116. var camera = this.getCamera();
  106117. if (camera) {
  106118. return camera.getForwardRay(length);
  106119. }
  106120. else {
  106121. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  106122. }
  106123. };
  106124. return VRExperienceHelperCameraGazer;
  106125. }(VRExperienceHelperGazer));
  106126. /**
  106127. * Helps to quickly add VR support to an existing scene.
  106128. * See http://doc.babylonjs.com/how_to/webvr_helper
  106129. */
  106130. var VRExperienceHelper = /** @class */ (function () {
  106131. /**
  106132. * Instantiates a VRExperienceHelper.
  106133. * Helps to quickly add VR support to an existing scene.
  106134. * @param scene The scene the VRExperienceHelper belongs to.
  106135. * @param webVROptions Options to modify the vr experience helper's behavior.
  106136. */
  106137. function VRExperienceHelper(scene,
  106138. /** Options to modify the vr experience helper's behavior. */
  106139. webVROptions) {
  106140. if (webVROptions === void 0) { webVROptions = {}; }
  106141. var _this = this;
  106142. this.webVROptions = webVROptions;
  106143. // Can the system support WebVR, even if a headset isn't plugged in?
  106144. this._webVRsupported = false;
  106145. // If WebVR is supported, is a headset plugged in and are we ready to present?
  106146. this._webVRready = false;
  106147. // Are we waiting for the requestPresent callback to complete?
  106148. this._webVRrequesting = false;
  106149. // Are we presenting to the headset right now? (this is the vrDevice state)
  106150. this._webVRpresenting = false;
  106151. // Are we presenting in the fullscreen fallback?
  106152. this._fullscreenVRpresenting = false;
  106153. /**
  106154. * Observable raised when entering VR.
  106155. */
  106156. this.onEnteringVRObservable = new BABYLON.Observable();
  106157. /**
  106158. * Observable raised when exiting VR.
  106159. */
  106160. this.onExitingVRObservable = new BABYLON.Observable();
  106161. /**
  106162. * Observable raised when controller mesh is loaded.
  106163. */
  106164. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  106165. this._useCustomVRButton = false;
  106166. this._teleportationRequested = false;
  106167. this._teleportActive = false;
  106168. this._floorMeshesCollection = [];
  106169. this._rotationAllowed = true;
  106170. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  106171. this._isDefaultTeleportationTarget = true;
  106172. this._teleportationFillColor = "#444444";
  106173. this._teleportationBorderColor = "#FFFFFF";
  106174. this._rotationAngle = 0;
  106175. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  106176. this._padSensibilityUp = 0.65;
  106177. this._padSensibilityDown = 0.35;
  106178. this._leftController = null;
  106179. this._rightController = null;
  106180. /**
  106181. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  106182. */
  106183. this.onNewMeshSelected = new BABYLON.Observable();
  106184. /**
  106185. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  106186. */
  106187. this.onNewMeshPicked = new BABYLON.Observable();
  106188. /**
  106189. * Observable raised before camera teleportation
  106190. */
  106191. this.onBeforeCameraTeleport = new BABYLON.Observable();
  106192. /**
  106193. * Observable raised after camera teleportation
  106194. */
  106195. this.onAfterCameraTeleport = new BABYLON.Observable();
  106196. /**
  106197. * Observable raised when current selected mesh gets unselected
  106198. */
  106199. this.onSelectedMeshUnselected = new BABYLON.Observable();
  106200. /**
  106201. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  106202. */
  106203. this.teleportationEnabled = true;
  106204. this._teleportationInitialized = false;
  106205. this._interactionsEnabled = false;
  106206. this._interactionsRequested = false;
  106207. this._displayGaze = true;
  106208. this._displayLaserPointer = true;
  106209. /**
  106210. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  106211. */
  106212. this.updateGazeTrackerScale = true;
  106213. this._onResize = function () {
  106214. _this.moveButtonToBottomRight();
  106215. if (_this._fullscreenVRpresenting && _this._webVRready) {
  106216. _this.exitVR();
  106217. }
  106218. };
  106219. this._onFullscreenChange = function () {
  106220. if (document.fullscreen !== undefined) {
  106221. _this._fullscreenVRpresenting = document.fullscreen;
  106222. }
  106223. else if (document.mozFullScreen !== undefined) {
  106224. _this._fullscreenVRpresenting = document.mozFullScreen;
  106225. }
  106226. else if (document.webkitIsFullScreen !== undefined) {
  106227. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  106228. }
  106229. else if (document.msIsFullScreen !== undefined) {
  106230. _this._fullscreenVRpresenting = document.msIsFullScreen;
  106231. }
  106232. else if (document.msFullscreenElement !== undefined) {
  106233. _this._fullscreenVRpresenting = document.msFullscreenElement;
  106234. }
  106235. if (!_this._fullscreenVRpresenting && _this._canvas) {
  106236. _this.exitVR();
  106237. if (!_this._useCustomVRButton) {
  106238. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  106239. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  106240. }
  106241. }
  106242. };
  106243. this.beforeRender = function () {
  106244. if (_this._leftController && _this._leftController._activePointer) {
  106245. _this._castRayAndSelectObject(_this._leftController);
  106246. }
  106247. if (_this._rightController && _this._rightController._activePointer) {
  106248. _this._castRayAndSelectObject(_this._rightController);
  106249. }
  106250. if (_this._noControllerIsActive) {
  106251. _this._castRayAndSelectObject(_this._cameraGazer);
  106252. }
  106253. else {
  106254. _this._cameraGazer._gazeTracker.isVisible = false;
  106255. }
  106256. };
  106257. this._onNewGamepadConnected = function (gamepad) {
  106258. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  106259. if (gamepad.leftStick) {
  106260. gamepad.onleftstickchanged(function (stickValues) {
  106261. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  106262. // Listening to classic/xbox gamepad only if no VR controller is active
  106263. if ((!_this._leftController && !_this._rightController) ||
  106264. ((_this._leftController && !_this._leftController._activePointer) &&
  106265. (_this._rightController && !_this._rightController._activePointer))) {
  106266. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  106267. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  106268. }
  106269. }
  106270. });
  106271. }
  106272. if (gamepad.rightStick) {
  106273. gamepad.onrightstickchanged(function (stickValues) {
  106274. if (_this._teleportationInitialized) {
  106275. _this._checkRotate(stickValues, _this._cameraGazer);
  106276. }
  106277. });
  106278. }
  106279. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  106280. gamepad.onbuttondown(function (buttonPressed) {
  106281. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  106282. _this._cameraGazer._selectionPointerDown();
  106283. }
  106284. });
  106285. gamepad.onbuttonup(function (buttonPressed) {
  106286. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  106287. _this._cameraGazer._selectionPointerUp();
  106288. }
  106289. });
  106290. }
  106291. }
  106292. else {
  106293. var webVRController = gamepad;
  106294. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  106295. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  106296. _this._rightController = controller;
  106297. }
  106298. else {
  106299. _this._leftController = controller;
  106300. }
  106301. _this._tryEnableInteractionOnController(controller);
  106302. }
  106303. };
  106304. // 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
  106305. this._tryEnableInteractionOnController = function (controller) {
  106306. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  106307. _this._enableInteractionOnController(controller);
  106308. }
  106309. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  106310. _this._enableTeleportationOnController(controller);
  106311. }
  106312. };
  106313. this._onNewGamepadDisconnected = function (gamepad) {
  106314. if (gamepad instanceof BABYLON.WebVRController) {
  106315. if (gamepad.hand === "left" && _this._leftController != null) {
  106316. _this._leftController.dispose();
  106317. _this._leftController = null;
  106318. }
  106319. if (gamepad.hand === "right" && _this._rightController != null) {
  106320. _this._rightController.dispose();
  106321. _this._rightController = null;
  106322. }
  106323. }
  106324. };
  106325. this._workingVector = BABYLON.Vector3.Zero();
  106326. this._workingQuaternion = BABYLON.Quaternion.Identity();
  106327. this._workingMatrix = BABYLON.Matrix.Identity();
  106328. this._scene = scene;
  106329. this._canvas = scene.getEngine().getRenderingCanvas();
  106330. // Parse options
  106331. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  106332. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  106333. }
  106334. if (webVROptions.createDeviceOrientationCamera === undefined) {
  106335. webVROptions.createDeviceOrientationCamera = true;
  106336. }
  106337. if (webVROptions.laserToggle === undefined) {
  106338. webVROptions.laserToggle = true;
  106339. }
  106340. if (webVROptions.defaultHeight === undefined) {
  106341. webVROptions.defaultHeight = 1.7;
  106342. }
  106343. if (webVROptions.useCustomVRButton) {
  106344. this._useCustomVRButton = true;
  106345. if (webVROptions.customVRButton) {
  106346. this._btnVR = webVROptions.customVRButton;
  106347. }
  106348. }
  106349. if (webVROptions.rayLength) {
  106350. this._rayLength = webVROptions.rayLength;
  106351. }
  106352. this._defaultHeight = webVROptions.defaultHeight;
  106353. if (webVROptions.positionScale) {
  106354. this._rayLength *= webVROptions.positionScale;
  106355. this._defaultHeight *= webVROptions.positionScale;
  106356. }
  106357. this._hasEnteredVR = false;
  106358. // Set position
  106359. if (this._scene.activeCamera) {
  106360. this._position = this._scene.activeCamera.position.clone();
  106361. }
  106362. else {
  106363. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  106364. }
  106365. // Set non-vr camera
  106366. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  106367. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  106368. // Copy data from existing camera
  106369. if (this._scene.activeCamera) {
  106370. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  106371. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  106372. // Set rotation from previous camera
  106373. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  106374. var targetCamera = this._scene.activeCamera;
  106375. if (targetCamera.rotationQuaternion) {
  106376. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  106377. }
  106378. else {
  106379. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  106380. }
  106381. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  106382. }
  106383. }
  106384. this._scene.activeCamera = this._deviceOrientationCamera;
  106385. if (this._canvas) {
  106386. this._scene.activeCamera.attachControl(this._canvas);
  106387. }
  106388. }
  106389. else {
  106390. this._existingCamera = this._scene.activeCamera;
  106391. }
  106392. // Create VR cameras
  106393. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  106394. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  106395. }
  106396. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  106397. this._webVRCamera.useStandingMatrix();
  106398. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  106399. // Create default button
  106400. if (!this._useCustomVRButton) {
  106401. this._btnVR = document.createElement("BUTTON");
  106402. this._btnVR.className = "babylonVRicon";
  106403. this._btnVR.id = "babylonVRiconbtn";
  106404. this._btnVR.title = "Click to switch to VR";
  106405. 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) }";
  106406. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  106407. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  106408. // css += ".babylonVRicon.vrdisplaysupported { }";
  106409. // css += ".babylonVRicon.vrdisplayready { }";
  106410. // css += ".babylonVRicon.vrdisplayrequesting { }";
  106411. var style = document.createElement('style');
  106412. style.appendChild(document.createTextNode(css));
  106413. document.getElementsByTagName('head')[0].appendChild(style);
  106414. this.moveButtonToBottomRight();
  106415. }
  106416. // VR button click event
  106417. if (this._btnVR) {
  106418. this._btnVR.addEventListener("click", function () {
  106419. if (!_this.isInVRMode) {
  106420. _this.enterVR();
  106421. }
  106422. else {
  106423. _this.exitVR();
  106424. }
  106425. });
  106426. }
  106427. // Window events
  106428. window.addEventListener("resize", this._onResize);
  106429. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  106430. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  106431. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  106432. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  106433. document.onmsfullscreenchange = this._onFullscreenChange;
  106434. // Display vr button when headset is connected
  106435. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  106436. this.displayVRButton();
  106437. }
  106438. else {
  106439. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  106440. if (e.vrDisplay) {
  106441. _this.displayVRButton();
  106442. }
  106443. });
  106444. }
  106445. // Exiting VR mode using 'ESC' key on desktop
  106446. this._onKeyDown = function (event) {
  106447. if (event.keyCode === 27 && _this.isInVRMode) {
  106448. _this.exitVR();
  106449. }
  106450. };
  106451. document.addEventListener("keydown", this._onKeyDown);
  106452. // Exiting VR mode double tapping the touch screen
  106453. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  106454. if (_this.isInVRMode) {
  106455. _this.exitVR();
  106456. if (_this._fullscreenVRpresenting) {
  106457. _this._scene.getEngine().switchFullscreen(true);
  106458. }
  106459. }
  106460. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  106461. // Listen for WebVR display changes
  106462. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  106463. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  106464. this._onVRRequestPresentStart = function () {
  106465. _this._webVRrequesting = true;
  106466. _this.updateButtonVisibility();
  106467. };
  106468. this._onVRRequestPresentComplete = function (success) {
  106469. _this._webVRrequesting = false;
  106470. _this.updateButtonVisibility();
  106471. };
  106472. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  106473. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  106474. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  106475. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  106476. scene.onDisposeObservable.add(function () {
  106477. _this.dispose();
  106478. });
  106479. // Gamepad connection events
  106480. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  106481. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  106482. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  106483. this.updateButtonVisibility();
  106484. //create easing functions
  106485. this._circleEase = new BABYLON.CircleEase();
  106486. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  106487. if (this.webVROptions.floorMeshes) {
  106488. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  106489. }
  106490. }
  106491. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  106492. /** Return this.onEnteringVRObservable
  106493. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  106494. */
  106495. get: function () {
  106496. return this.onEnteringVRObservable;
  106497. },
  106498. enumerable: true,
  106499. configurable: true
  106500. });
  106501. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  106502. /** Return this.onExitingVRObservable
  106503. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  106504. */
  106505. get: function () {
  106506. return this.onExitingVRObservable;
  106507. },
  106508. enumerable: true,
  106509. configurable: true
  106510. });
  106511. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  106512. /** Return this.onControllerMeshLoadedObservable
  106513. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  106514. */
  106515. get: function () {
  106516. return this.onControllerMeshLoadedObservable;
  106517. },
  106518. enumerable: true,
  106519. configurable: true
  106520. });
  106521. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  106522. /**
  106523. * The mesh used to display where the user is going to teleport.
  106524. */
  106525. get: function () {
  106526. return this._teleportationTarget;
  106527. },
  106528. /**
  106529. * Sets the mesh to be used to display where the user is going to teleport.
  106530. */
  106531. set: function (value) {
  106532. if (value) {
  106533. value.name = "teleportationTarget";
  106534. this._isDefaultTeleportationTarget = false;
  106535. this._teleportationTarget = value;
  106536. }
  106537. },
  106538. enumerable: true,
  106539. configurable: true
  106540. });
  106541. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  106542. /**
  106543. * 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
  106544. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  106545. * See http://doc.babylonjs.com/resources/baking_transformations
  106546. */
  106547. get: function () {
  106548. return this._cameraGazer._gazeTracker;
  106549. },
  106550. set: function (value) {
  106551. if (value) {
  106552. // Dispose of existing meshes
  106553. if (this._cameraGazer._gazeTracker) {
  106554. this._cameraGazer._gazeTracker.dispose();
  106555. }
  106556. if (this._leftController && this._leftController._gazeTracker) {
  106557. this._leftController._gazeTracker.dispose();
  106558. }
  106559. if (this._rightController && this._rightController._gazeTracker) {
  106560. this._rightController._gazeTracker.dispose();
  106561. }
  106562. // Set and create gaze trackers on head and controllers
  106563. this._cameraGazer._gazeTracker = value;
  106564. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  106565. this._cameraGazer._gazeTracker.isPickable = false;
  106566. this._cameraGazer._gazeTracker.isVisible = false;
  106567. this._cameraGazer._gazeTracker.name = "gazeTracker";
  106568. if (this._leftController) {
  106569. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  106570. }
  106571. if (this._rightController) {
  106572. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  106573. }
  106574. }
  106575. },
  106576. enumerable: true,
  106577. configurable: true
  106578. });
  106579. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  106580. /**
  106581. * The gaze tracking mesh corresponding to the left controller
  106582. */
  106583. get: function () {
  106584. if (this._leftController) {
  106585. return this._leftController._gazeTracker;
  106586. }
  106587. return null;
  106588. },
  106589. enumerable: true,
  106590. configurable: true
  106591. });
  106592. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  106593. /**
  106594. * The gaze tracking mesh corresponding to the right controller
  106595. */
  106596. get: function () {
  106597. if (this._rightController) {
  106598. return this._rightController._gazeTracker;
  106599. }
  106600. return null;
  106601. },
  106602. enumerable: true,
  106603. configurable: true
  106604. });
  106605. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  106606. /**
  106607. * If the ray of the gaze should be displayed.
  106608. */
  106609. get: function () {
  106610. return this._displayGaze;
  106611. },
  106612. /**
  106613. * Sets if the ray of the gaze should be displayed.
  106614. */
  106615. set: function (value) {
  106616. this._displayGaze = value;
  106617. if (!value) {
  106618. this._cameraGazer._gazeTracker.isVisible = false;
  106619. if (this._leftController) {
  106620. this._leftController._gazeTracker.isVisible = false;
  106621. }
  106622. if (this._rightController) {
  106623. this._rightController._gazeTracker.isVisible = false;
  106624. }
  106625. }
  106626. },
  106627. enumerable: true,
  106628. configurable: true
  106629. });
  106630. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  106631. /**
  106632. * If the ray of the LaserPointer should be displayed.
  106633. */
  106634. get: function () {
  106635. return this._displayLaserPointer;
  106636. },
  106637. /**
  106638. * Sets if the ray of the LaserPointer should be displayed.
  106639. */
  106640. set: function (value) {
  106641. this._displayLaserPointer = value;
  106642. if (!value) {
  106643. if (this._rightController) {
  106644. this._rightController._deactivatePointer();
  106645. this._rightController._gazeTracker.isVisible = false;
  106646. }
  106647. if (this._leftController) {
  106648. this._leftController._deactivatePointer();
  106649. this._leftController._gazeTracker.isVisible = false;
  106650. }
  106651. }
  106652. else {
  106653. if (this._rightController) {
  106654. this._rightController._activatePointer();
  106655. }
  106656. if (this._leftController) {
  106657. this._leftController._activatePointer();
  106658. }
  106659. }
  106660. },
  106661. enumerable: true,
  106662. configurable: true
  106663. });
  106664. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  106665. /**
  106666. * The deviceOrientationCamera used as the camera when not in VR.
  106667. */
  106668. get: function () {
  106669. return this._deviceOrientationCamera;
  106670. },
  106671. enumerable: true,
  106672. configurable: true
  106673. });
  106674. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  106675. /**
  106676. * Based on the current WebVR support, returns the current VR camera used.
  106677. */
  106678. get: function () {
  106679. if (this._webVRready) {
  106680. return this._webVRCamera;
  106681. }
  106682. else {
  106683. return this._scene.activeCamera;
  106684. }
  106685. },
  106686. enumerable: true,
  106687. configurable: true
  106688. });
  106689. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  106690. /**
  106691. * The webVRCamera which is used when in VR.
  106692. */
  106693. get: function () {
  106694. return this._webVRCamera;
  106695. },
  106696. enumerable: true,
  106697. configurable: true
  106698. });
  106699. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  106700. /**
  106701. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  106702. */
  106703. get: function () {
  106704. return this._vrDeviceOrientationCamera;
  106705. },
  106706. enumerable: true,
  106707. configurable: true
  106708. });
  106709. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  106710. get: function () {
  106711. var result = this._cameraGazer._teleportationRequestInitiated
  106712. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  106713. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  106714. return result;
  106715. },
  106716. enumerable: true,
  106717. configurable: true
  106718. });
  106719. // Raised when one of the controller has loaded successfully its associated default mesh
  106720. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  106721. if (this._leftController && this._leftController.webVRController == webVRController) {
  106722. if (webVRController.mesh) {
  106723. this._leftController._setLaserPointerParent(webVRController.mesh);
  106724. }
  106725. }
  106726. if (this._rightController && this._rightController.webVRController == webVRController) {
  106727. if (webVRController.mesh) {
  106728. this._rightController._setLaserPointerParent(webVRController.mesh);
  106729. }
  106730. }
  106731. try {
  106732. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  106733. }
  106734. catch (err) {
  106735. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  106736. }
  106737. };
  106738. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  106739. /**
  106740. * Gets a value indicating if we are currently in VR mode.
  106741. */
  106742. get: function () {
  106743. return this._webVRpresenting || this._fullscreenVRpresenting;
  106744. },
  106745. enumerable: true,
  106746. configurable: true
  106747. });
  106748. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  106749. var vrDisplay = this._scene.getEngine().getVRDevice();
  106750. if (vrDisplay) {
  106751. var wasPresenting = this._webVRpresenting;
  106752. this._webVRpresenting = vrDisplay.isPresenting;
  106753. if (wasPresenting && !this._webVRpresenting) {
  106754. this.exitVR();
  106755. }
  106756. }
  106757. else {
  106758. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  106759. }
  106760. this.updateButtonVisibility();
  106761. };
  106762. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  106763. this._webVRsupported = eventArgs.vrSupported;
  106764. this._webVRready = !!eventArgs.vrDisplay;
  106765. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  106766. this.updateButtonVisibility();
  106767. };
  106768. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  106769. if (this._canvas && !this._useCustomVRButton) {
  106770. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  106771. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  106772. }
  106773. };
  106774. VRExperienceHelper.prototype.displayVRButton = function () {
  106775. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  106776. document.body.appendChild(this._btnVR);
  106777. this._btnVRDisplayed = true;
  106778. }
  106779. };
  106780. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  106781. if (!this._btnVR || this._useCustomVRButton) {
  106782. return;
  106783. }
  106784. this._btnVR.className = "babylonVRicon";
  106785. if (this.isInVRMode) {
  106786. this._btnVR.className += " vrdisplaypresenting";
  106787. }
  106788. else {
  106789. if (this._webVRready) {
  106790. this._btnVR.className += " vrdisplayready";
  106791. }
  106792. if (this._webVRsupported) {
  106793. this._btnVR.className += " vrdisplaysupported";
  106794. }
  106795. if (this._webVRrequesting) {
  106796. this._btnVR.className += " vrdisplayrequesting";
  106797. }
  106798. }
  106799. };
  106800. /**
  106801. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  106802. * Otherwise, will use the fullscreen API.
  106803. */
  106804. VRExperienceHelper.prototype.enterVR = function () {
  106805. if (this.onEnteringVRObservable) {
  106806. try {
  106807. this.onEnteringVRObservable.notifyObservers(this);
  106808. }
  106809. catch (err) {
  106810. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  106811. }
  106812. }
  106813. if (this._scene.activeCamera) {
  106814. this._position = this._scene.activeCamera.position.clone();
  106815. // make sure that we return to the last active camera
  106816. this._existingCamera = this._scene.activeCamera;
  106817. }
  106818. if (this._webVRrequesting) {
  106819. return;
  106820. }
  106821. // If WebVR is supported and a headset is connected
  106822. if (this._webVRready) {
  106823. if (!this._webVRpresenting) {
  106824. this._webVRCamera.position = this._position;
  106825. this._scene.activeCamera = this._webVRCamera;
  106826. }
  106827. }
  106828. else if (this._vrDeviceOrientationCamera) {
  106829. this._vrDeviceOrientationCamera.position = this._position;
  106830. if (this._scene.activeCamera) {
  106831. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  106832. }
  106833. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  106834. this._scene.getEngine().switchFullscreen(true);
  106835. this.updateButtonVisibility();
  106836. }
  106837. if (this._scene.activeCamera && this._canvas) {
  106838. this._scene.activeCamera.attachControl(this._canvas);
  106839. }
  106840. if (this._interactionsEnabled) {
  106841. this._scene.registerBeforeRender(this.beforeRender);
  106842. }
  106843. this._hasEnteredVR = true;
  106844. };
  106845. /**
  106846. * Attempt to exit VR, or fullscreen.
  106847. */
  106848. VRExperienceHelper.prototype.exitVR = function () {
  106849. if (this._hasEnteredVR) {
  106850. if (this.onExitingVRObservable) {
  106851. try {
  106852. this.onExitingVRObservable.notifyObservers(this);
  106853. }
  106854. catch (err) {
  106855. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  106856. }
  106857. }
  106858. if (this._webVRpresenting) {
  106859. this._scene.getEngine().disableVR();
  106860. }
  106861. if (this._scene.activeCamera) {
  106862. this._position = this._scene.activeCamera.position.clone();
  106863. }
  106864. if (this._deviceOrientationCamera) {
  106865. this._deviceOrientationCamera.position = this._position;
  106866. this._scene.activeCamera = this._deviceOrientationCamera;
  106867. if (this._canvas) {
  106868. this._scene.activeCamera.attachControl(this._canvas);
  106869. }
  106870. }
  106871. else if (this._existingCamera) {
  106872. this._existingCamera.position = this._position;
  106873. this._scene.activeCamera = this._existingCamera;
  106874. }
  106875. this.updateButtonVisibility();
  106876. if (this._interactionsEnabled) {
  106877. this._scene.unregisterBeforeRender(this.beforeRender);
  106878. this._cameraGazer._gazeTracker.isVisible = false;
  106879. if (this._leftController) {
  106880. this._leftController._gazeTracker.isVisible = false;
  106881. }
  106882. if (this._rightController) {
  106883. this._rightController._gazeTracker.isVisible = false;
  106884. }
  106885. }
  106886. // resize to update width and height when exiting vr exits fullscreen
  106887. this._scene.getEngine().resize();
  106888. this._hasEnteredVR = false;
  106889. }
  106890. };
  106891. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  106892. /**
  106893. * The position of the vr experience helper.
  106894. */
  106895. get: function () {
  106896. return this._position;
  106897. },
  106898. /**
  106899. * Sets the position of the vr experience helper.
  106900. */
  106901. set: function (value) {
  106902. this._position = value;
  106903. if (this._scene.activeCamera) {
  106904. this._scene.activeCamera.position = value;
  106905. }
  106906. },
  106907. enumerable: true,
  106908. configurable: true
  106909. });
  106910. /**
  106911. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  106912. */
  106913. VRExperienceHelper.prototype.enableInteractions = function () {
  106914. var _this = this;
  106915. if (!this._interactionsEnabled) {
  106916. this._interactionsRequested = true;
  106917. if (this._leftController) {
  106918. this._enableInteractionOnController(this._leftController);
  106919. }
  106920. if (this._rightController) {
  106921. this._enableInteractionOnController(this._rightController);
  106922. }
  106923. this.raySelectionPredicate = function (mesh) {
  106924. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  106925. };
  106926. this.meshSelectionPredicate = function (mesh) {
  106927. return true;
  106928. };
  106929. this._raySelectionPredicate = function (mesh) {
  106930. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  106931. && mesh.name.indexOf("teleportationTarget") === -1
  106932. && mesh.name.indexOf("torusTeleportation") === -1)) {
  106933. return _this.raySelectionPredicate(mesh);
  106934. }
  106935. return false;
  106936. };
  106937. this._interactionsEnabled = true;
  106938. }
  106939. };
  106940. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  106941. get: function () {
  106942. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  106943. },
  106944. enumerable: true,
  106945. configurable: true
  106946. });
  106947. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  106948. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  106949. if (this._floorMeshesCollection[i].id === mesh.id) {
  106950. return true;
  106951. }
  106952. }
  106953. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  106954. return true;
  106955. }
  106956. return false;
  106957. };
  106958. /**
  106959. * Adds a floor mesh to be used for teleportation.
  106960. * @param floorMesh the mesh to be used for teleportation.
  106961. */
  106962. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  106963. if (!this._floorMeshesCollection) {
  106964. return;
  106965. }
  106966. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  106967. return;
  106968. }
  106969. this._floorMeshesCollection.push(floorMesh);
  106970. };
  106971. /**
  106972. * Removes a floor mesh from being used for teleportation.
  106973. * @param floorMesh the mesh to be removed.
  106974. */
  106975. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  106976. if (!this._floorMeshesCollection) {
  106977. return;
  106978. }
  106979. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  106980. if (meshIndex !== -1) {
  106981. this._floorMeshesCollection.splice(meshIndex, 1);
  106982. }
  106983. };
  106984. /**
  106985. * Enables interactions and teleportation using the VR controllers and gaze.
  106986. * @param vrTeleportationOptions options to modify teleportation behavior.
  106987. */
  106988. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  106989. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  106990. if (!this._teleportationInitialized) {
  106991. this._teleportationRequested = true;
  106992. this.enableInteractions();
  106993. if (vrTeleportationOptions.floorMeshName) {
  106994. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  106995. }
  106996. if (vrTeleportationOptions.floorMeshes) {
  106997. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  106998. }
  106999. if (this._leftController != null) {
  107000. this._enableTeleportationOnController(this._leftController);
  107001. }
  107002. if (this._rightController != null) {
  107003. this._enableTeleportationOnController(this._rightController);
  107004. }
  107005. // Creates an image processing post process for the vignette not relying
  107006. // on the main scene configuration for image processing to reduce setup and spaces
  107007. // (gamma/linear) conflicts.
  107008. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  107009. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  107010. imageProcessingConfiguration.vignetteEnabled = true;
  107011. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  107012. this._webVRCamera.detachPostProcess(this._postProcessMove);
  107013. this._teleportationInitialized = true;
  107014. if (this._isDefaultTeleportationTarget) {
  107015. this._createTeleportationCircles();
  107016. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  107017. }
  107018. }
  107019. };
  107020. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  107021. var _this = this;
  107022. var controllerMesh = controller.webVRController.mesh;
  107023. if (controllerMesh) {
  107024. controller._interactionsEnabled = true;
  107025. controller._activatePointer();
  107026. if (this.webVROptions.laserToggle) {
  107027. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  107028. // Enabling / disabling laserPointer
  107029. if (_this._displayLaserPointer && stateObject.value === 1) {
  107030. if (controller._activePointer) {
  107031. controller._deactivatePointer();
  107032. }
  107033. else {
  107034. controller._activatePointer();
  107035. }
  107036. if (_this.displayGaze) {
  107037. controller._gazeTracker.isVisible = controller._activePointer;
  107038. }
  107039. }
  107040. });
  107041. }
  107042. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  107043. var gazer = controller;
  107044. if (_this._noControllerIsActive) {
  107045. gazer = _this._cameraGazer;
  107046. }
  107047. if (!gazer._pointerDownOnMeshAsked) {
  107048. if (stateObject.value > _this._padSensibilityUp) {
  107049. gazer._selectionPointerDown();
  107050. }
  107051. }
  107052. else if (stateObject.value < _this._padSensibilityDown) {
  107053. gazer._selectionPointerUp();
  107054. }
  107055. });
  107056. }
  107057. };
  107058. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  107059. // Dont teleport if another gaze already requested teleportation
  107060. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  107061. return;
  107062. }
  107063. if (!gazer._teleportationRequestInitiated) {
  107064. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  107065. gazer._activatePointer();
  107066. gazer._teleportationRequestInitiated = true;
  107067. }
  107068. }
  107069. else {
  107070. // Listening to the proper controller values changes to confirm teleportation
  107071. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  107072. if (this._teleportActive) {
  107073. this.teleportCamera(this._haloCenter);
  107074. }
  107075. gazer._teleportationRequestInitiated = false;
  107076. }
  107077. }
  107078. };
  107079. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  107080. // Only rotate when user is not currently selecting a teleportation location
  107081. if (gazer._teleportationRequestInitiated) {
  107082. return;
  107083. }
  107084. if (!gazer._rotationLeftAsked) {
  107085. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  107086. gazer._rotationLeftAsked = true;
  107087. if (this._rotationAllowed) {
  107088. this._rotateCamera(false);
  107089. }
  107090. }
  107091. }
  107092. else {
  107093. if (stateObject.x > -this._padSensibilityDown) {
  107094. gazer._rotationLeftAsked = false;
  107095. }
  107096. }
  107097. if (!gazer._rotationRightAsked) {
  107098. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  107099. gazer._rotationRightAsked = true;
  107100. if (this._rotationAllowed) {
  107101. this._rotateCamera(true);
  107102. }
  107103. }
  107104. }
  107105. else {
  107106. if (stateObject.x < this._padSensibilityDown) {
  107107. gazer._rotationRightAsked = false;
  107108. }
  107109. }
  107110. };
  107111. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  107112. // Only teleport backwards when user is not currently selecting a teleportation location
  107113. if (gazer._teleportationRequestInitiated) {
  107114. return;
  107115. }
  107116. // Teleport backwards
  107117. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  107118. if (!gazer._teleportationBackRequestInitiated) {
  107119. if (!this.currentVRCamera) {
  107120. return;
  107121. }
  107122. // Get rotation and position of the current camera
  107123. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  107124. var position = this.currentVRCamera.position;
  107125. // If the camera has device position, use that instead
  107126. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  107127. rotation = this.currentVRCamera.deviceRotationQuaternion;
  107128. position = this.currentVRCamera.devicePosition;
  107129. }
  107130. // Get matrix with only the y rotation of the device rotation
  107131. rotation.toEulerAnglesToRef(this._workingVector);
  107132. this._workingVector.z = 0;
  107133. this._workingVector.x = 0;
  107134. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  107135. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  107136. // Rotate backwards ray by device rotation to cast at the ground behind the user
  107137. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  107138. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  107139. var ray = new BABYLON.Ray(position, this._workingVector);
  107140. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  107141. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  107142. this.teleportCamera(hit.pickedPoint);
  107143. }
  107144. gazer._teleportationBackRequestInitiated = true;
  107145. }
  107146. }
  107147. else {
  107148. gazer._teleportationBackRequestInitiated = false;
  107149. }
  107150. };
  107151. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  107152. var _this = this;
  107153. var controllerMesh = controller.webVRController.mesh;
  107154. if (controllerMesh) {
  107155. if (!controller._interactionsEnabled) {
  107156. this._enableInteractionOnController(controller);
  107157. }
  107158. controller._interactionsEnabled = true;
  107159. controller._teleportationEnabled = true;
  107160. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  107161. controller._dpadPressed = false;
  107162. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  107163. controller._dpadPressed = stateObject.pressed;
  107164. if (!controller._dpadPressed) {
  107165. controller._rotationLeftAsked = false;
  107166. controller._rotationRightAsked = false;
  107167. controller._teleportationBackRequestInitiated = false;
  107168. }
  107169. });
  107170. }
  107171. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  107172. if (_this.teleportationEnabled) {
  107173. _this._checkTeleportBackwards(stateObject, controller);
  107174. _this._checkTeleportWithRay(stateObject, controller);
  107175. }
  107176. _this._checkRotate(stateObject, controller);
  107177. });
  107178. }
  107179. };
  107180. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  107181. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  107182. this._teleportationTarget.isPickable = false;
  107183. var length = 512;
  107184. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  107185. dynamicTexture.hasAlpha = true;
  107186. var context = dynamicTexture.getContext();
  107187. var centerX = length / 2;
  107188. var centerY = length / 2;
  107189. var radius = 200;
  107190. context.beginPath();
  107191. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  107192. context.fillStyle = this._teleportationFillColor;
  107193. context.fill();
  107194. context.lineWidth = 10;
  107195. context.strokeStyle = this._teleportationBorderColor;
  107196. context.stroke();
  107197. context.closePath();
  107198. dynamicTexture.update();
  107199. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  107200. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  107201. this._teleportationTarget.material = teleportationCircleMaterial;
  107202. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  107203. torus.isPickable = false;
  107204. torus.parent = this._teleportationTarget;
  107205. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  107206. var keys = [];
  107207. keys.push({
  107208. frame: 0,
  107209. value: 0
  107210. });
  107211. keys.push({
  107212. frame: 30,
  107213. value: 0.4
  107214. });
  107215. keys.push({
  107216. frame: 60,
  107217. value: 0
  107218. });
  107219. animationInnerCircle.setKeys(keys);
  107220. var easingFunction = new BABYLON.SineEase();
  107221. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  107222. animationInnerCircle.setEasingFunction(easingFunction);
  107223. torus.animations = [];
  107224. torus.animations.push(animationInnerCircle);
  107225. this._scene.beginAnimation(torus, 0, 60, true);
  107226. this._hideTeleportationTarget();
  107227. };
  107228. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  107229. this._teleportActive = true;
  107230. if (this._teleportationInitialized) {
  107231. this._teleportationTarget.isVisible = true;
  107232. if (this._isDefaultTeleportationTarget) {
  107233. this._teleportationTarget.getChildren()[0].isVisible = true;
  107234. }
  107235. }
  107236. };
  107237. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  107238. this._teleportActive = false;
  107239. if (this._teleportationInitialized) {
  107240. this._teleportationTarget.isVisible = false;
  107241. if (this._isDefaultTeleportationTarget) {
  107242. this._teleportationTarget.getChildren()[0].isVisible = false;
  107243. }
  107244. }
  107245. };
  107246. VRExperienceHelper.prototype._rotateCamera = function (right) {
  107247. var _this = this;
  107248. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  107249. return;
  107250. }
  107251. if (right) {
  107252. this._rotationAngle++;
  107253. }
  107254. else {
  107255. this._rotationAngle--;
  107256. }
  107257. this.currentVRCamera.animations = [];
  107258. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  107259. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107260. var animationRotationKeys = [];
  107261. animationRotationKeys.push({
  107262. frame: 0,
  107263. value: this.currentVRCamera.rotationQuaternion
  107264. });
  107265. animationRotationKeys.push({
  107266. frame: 6,
  107267. value: target
  107268. });
  107269. animationRotation.setKeys(animationRotationKeys);
  107270. animationRotation.setEasingFunction(this._circleEase);
  107271. this.currentVRCamera.animations.push(animationRotation);
  107272. this._postProcessMove.animations = [];
  107273. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107274. var vignetteWeightKeys = [];
  107275. vignetteWeightKeys.push({
  107276. frame: 0,
  107277. value: 0
  107278. });
  107279. vignetteWeightKeys.push({
  107280. frame: 3,
  107281. value: 4
  107282. });
  107283. vignetteWeightKeys.push({
  107284. frame: 6,
  107285. value: 0
  107286. });
  107287. animationPP.setKeys(vignetteWeightKeys);
  107288. animationPP.setEasingFunction(this._circleEase);
  107289. this._postProcessMove.animations.push(animationPP);
  107290. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107291. var vignetteStretchKeys = [];
  107292. vignetteStretchKeys.push({
  107293. frame: 0,
  107294. value: 0
  107295. });
  107296. vignetteStretchKeys.push({
  107297. frame: 3,
  107298. value: 10
  107299. });
  107300. vignetteStretchKeys.push({
  107301. frame: 6,
  107302. value: 0
  107303. });
  107304. animationPP2.setKeys(vignetteStretchKeys);
  107305. animationPP2.setEasingFunction(this._circleEase);
  107306. this._postProcessMove.animations.push(animationPP2);
  107307. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  107308. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  107309. this._postProcessMove.samples = 4;
  107310. this._webVRCamera.attachPostProcess(this._postProcessMove);
  107311. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  107312. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  107313. });
  107314. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  107315. };
  107316. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  107317. if (hit.pickedPoint) {
  107318. if (gazer._teleportationRequestInitiated) {
  107319. this._displayTeleportationTarget();
  107320. this._haloCenter.copyFrom(hit.pickedPoint);
  107321. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  107322. }
  107323. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  107324. if (pickNormal) {
  107325. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  107326. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  107327. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  107328. }
  107329. this._teleportationTarget.position.y += 0.1;
  107330. }
  107331. };
  107332. /**
  107333. * Teleports the users feet to the desired location
  107334. * @param location The location where the user's feet should be placed
  107335. */
  107336. VRExperienceHelper.prototype.teleportCamera = function (location) {
  107337. var _this = this;
  107338. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  107339. return;
  107340. }
  107341. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  107342. // offset of the headset from the anchor.
  107343. if (this.webVRCamera.leftCamera) {
  107344. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  107345. this._workingVector.subtractInPlace(this.webVRCamera.position);
  107346. location.subtractToRef(this._workingVector, this._workingVector);
  107347. }
  107348. else {
  107349. this._workingVector.copyFrom(location);
  107350. }
  107351. // Add height to account for user's height offset
  107352. if (this.isInVRMode) {
  107353. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  107354. }
  107355. else {
  107356. this._workingVector.y += this._defaultHeight;
  107357. }
  107358. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  107359. // Create animation from the camera's position to the new location
  107360. this.currentVRCamera.animations = [];
  107361. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107362. var animationCameraTeleportationKeys = [{
  107363. frame: 0,
  107364. value: this.currentVRCamera.position
  107365. },
  107366. {
  107367. frame: 11,
  107368. value: this._workingVector
  107369. }
  107370. ];
  107371. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  107372. animationCameraTeleportation.setEasingFunction(this._circleEase);
  107373. this.currentVRCamera.animations.push(animationCameraTeleportation);
  107374. this._postProcessMove.animations = [];
  107375. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107376. var vignetteWeightKeys = [];
  107377. vignetteWeightKeys.push({
  107378. frame: 0,
  107379. value: 0
  107380. });
  107381. vignetteWeightKeys.push({
  107382. frame: 5,
  107383. value: 8
  107384. });
  107385. vignetteWeightKeys.push({
  107386. frame: 11,
  107387. value: 0
  107388. });
  107389. animationPP.setKeys(vignetteWeightKeys);
  107390. this._postProcessMove.animations.push(animationPP);
  107391. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  107392. var vignetteStretchKeys = [];
  107393. vignetteStretchKeys.push({
  107394. frame: 0,
  107395. value: 0
  107396. });
  107397. vignetteStretchKeys.push({
  107398. frame: 5,
  107399. value: 10
  107400. });
  107401. vignetteStretchKeys.push({
  107402. frame: 11,
  107403. value: 0
  107404. });
  107405. animationPP2.setKeys(vignetteStretchKeys);
  107406. this._postProcessMove.animations.push(animationPP2);
  107407. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  107408. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  107409. this._webVRCamera.attachPostProcess(this._postProcessMove);
  107410. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  107411. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  107412. });
  107413. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  107414. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  107415. });
  107416. this._hideTeleportationTarget();
  107417. };
  107418. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  107419. if (normal) {
  107420. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  107421. if (angle < Math.PI / 2) {
  107422. normal.scaleInPlace(-1);
  107423. }
  107424. }
  107425. return normal;
  107426. };
  107427. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  107428. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  107429. return;
  107430. }
  107431. var ray = gazer._getForwardRay(this._rayLength);
  107432. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  107433. if (hit) {
  107434. // Populate the contrllers mesh that can be used for drag/drop
  107435. if (gazer._laserPointer) {
  107436. hit.originMesh = gazer._laserPointer.parent;
  107437. }
  107438. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  107439. }
  107440. gazer._currentHit = hit;
  107441. // Moving the gazeTracker on the mesh face targetted
  107442. if (hit && hit.pickedPoint) {
  107443. if (this._displayGaze) {
  107444. var multiplier = 1;
  107445. gazer._gazeTracker.isVisible = true;
  107446. if (gazer._isActionableMesh) {
  107447. multiplier = 3;
  107448. }
  107449. if (this.updateGazeTrackerScale) {
  107450. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  107451. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  107452. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  107453. }
  107454. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  107455. // To avoid z-fighting
  107456. var deltaFighting = 0.002;
  107457. if (pickNormal) {
  107458. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  107459. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  107460. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  107461. }
  107462. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  107463. if (gazer._gazeTracker.position.x < 0) {
  107464. gazer._gazeTracker.position.x += deltaFighting;
  107465. }
  107466. else {
  107467. gazer._gazeTracker.position.x -= deltaFighting;
  107468. }
  107469. if (gazer._gazeTracker.position.y < 0) {
  107470. gazer._gazeTracker.position.y += deltaFighting;
  107471. }
  107472. else {
  107473. gazer._gazeTracker.position.y -= deltaFighting;
  107474. }
  107475. if (gazer._gazeTracker.position.z < 0) {
  107476. gazer._gazeTracker.position.z += deltaFighting;
  107477. }
  107478. else {
  107479. gazer._gazeTracker.position.z -= deltaFighting;
  107480. }
  107481. }
  107482. // Changing the size of the laser pointer based on the distance from the targetted point
  107483. gazer._updatePointerDistance(hit.distance);
  107484. }
  107485. else {
  107486. gazer._updatePointerDistance();
  107487. gazer._gazeTracker.isVisible = false;
  107488. }
  107489. if (hit && hit.pickedMesh) {
  107490. // The object selected is the floor, we're in a teleportation scenario
  107491. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  107492. // Moving the teleportation area to this targetted point
  107493. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  107494. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  107495. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  107496. }
  107497. gazer._currentMeshSelected = null;
  107498. if (gazer._teleportationRequestInitiated) {
  107499. this._moveTeleportationSelectorTo(hit, gazer, ray);
  107500. }
  107501. return;
  107502. }
  107503. // If not, we're in a selection scenario
  107504. //this._teleportationAllowed = false;
  107505. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  107506. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  107507. this.onNewMeshPicked.notifyObservers(hit);
  107508. gazer._currentMeshSelected = hit.pickedMesh;
  107509. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  107510. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  107511. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  107512. gazer._isActionableMesh = true;
  107513. }
  107514. else {
  107515. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107516. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107517. gazer._isActionableMesh = false;
  107518. }
  107519. try {
  107520. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  107521. }
  107522. catch (err) {
  107523. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  107524. }
  107525. }
  107526. else {
  107527. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  107528. gazer._currentMeshSelected = null;
  107529. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107530. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107531. }
  107532. }
  107533. }
  107534. else {
  107535. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  107536. gazer._currentMeshSelected = null;
  107537. //this._teleportationAllowed = false;
  107538. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107539. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  107540. }
  107541. };
  107542. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  107543. if (mesh) {
  107544. this.onSelectedMeshUnselected.notifyObservers(mesh);
  107545. }
  107546. };
  107547. /**
  107548. * Sets the color of the laser ray from the vr controllers.
  107549. * @param color new color for the ray.
  107550. */
  107551. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  107552. if (this._leftController) {
  107553. this._leftController._setLaserPointerColor(color);
  107554. }
  107555. if (this._rightController) {
  107556. this._rightController._setLaserPointerColor(color);
  107557. }
  107558. };
  107559. /**
  107560. * Sets the color of the ray from the vr headsets gaze.
  107561. * @param color new color for the ray.
  107562. */
  107563. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  107564. if (!this._cameraGazer._gazeTracker.material) {
  107565. return;
  107566. }
  107567. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  107568. if (this._leftController) {
  107569. this._leftController._gazeTracker.material.emissiveColor = color;
  107570. }
  107571. if (this._rightController) {
  107572. this._rightController._gazeTracker.material.emissiveColor = color;
  107573. }
  107574. };
  107575. /**
  107576. * Exits VR and disposes of the vr experience helper
  107577. */
  107578. VRExperienceHelper.prototype.dispose = function () {
  107579. if (this.isInVRMode) {
  107580. this.exitVR();
  107581. }
  107582. if (this._postProcessMove) {
  107583. this._postProcessMove.dispose();
  107584. }
  107585. if (this._webVRCamera) {
  107586. this._webVRCamera.dispose();
  107587. }
  107588. if (this._vrDeviceOrientationCamera) {
  107589. this._vrDeviceOrientationCamera.dispose();
  107590. }
  107591. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  107592. document.body.removeChild(this._btnVR);
  107593. }
  107594. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  107595. this._deviceOrientationCamera.dispose();
  107596. }
  107597. if (this._cameraGazer) {
  107598. this._cameraGazer.dispose();
  107599. }
  107600. if (this._leftController) {
  107601. this._leftController.dispose();
  107602. }
  107603. if (this._rightController) {
  107604. this._rightController.dispose();
  107605. }
  107606. if (this._teleportationTarget) {
  107607. this._teleportationTarget.dispose();
  107608. }
  107609. this._floorMeshesCollection = [];
  107610. document.removeEventListener("keydown", this._onKeyDown);
  107611. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  107612. window.removeEventListener("resize", this._onResize);
  107613. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  107614. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  107615. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  107616. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  107617. document.onmsfullscreenchange = null;
  107618. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  107619. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  107620. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  107621. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  107622. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  107623. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  107624. this._scene.unregisterBeforeRender(this.beforeRender);
  107625. };
  107626. /**
  107627. * Gets the name of the VRExperienceHelper class
  107628. * @returns "VRExperienceHelper"
  107629. */
  107630. VRExperienceHelper.prototype.getClassName = function () {
  107631. return "VRExperienceHelper";
  107632. };
  107633. return VRExperienceHelper;
  107634. }());
  107635. BABYLON.VRExperienceHelper = VRExperienceHelper;
  107636. })(BABYLON || (BABYLON = {}));
  107637. //# sourceMappingURL=vrExperienceHelper.js.map
  107638. var BABYLON;
  107639. (function (BABYLON) {
  107640. /**
  107641. * WebXR Camera which holds the views for the xrSession
  107642. * @see https://doc.babylonjs.com/how_to/webxr
  107643. */
  107644. var WebXRCamera = /** @class */ (function (_super) {
  107645. __extends(WebXRCamera, _super);
  107646. /**
  107647. * Creates a new webXRCamera, this should only be set at the camera after it has been updated by the xrSessionManager
  107648. * @param name the name of the camera
  107649. * @param scene the scene to add the camera to
  107650. */
  107651. function WebXRCamera(name, scene) {
  107652. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  107653. // Initial camera configuration
  107654. _this.minZ = 0;
  107655. _this.rotationQuaternion = new BABYLON.Quaternion();
  107656. _this.cameraRigMode = BABYLON.Camera.RIG_MODE_CUSTOM;
  107657. _this._updateNumberOfRigCameras(1);
  107658. return _this;
  107659. }
  107660. WebXRCamera.prototype._updateNumberOfRigCameras = function (viewCount) {
  107661. if (viewCount === void 0) { viewCount = 1; }
  107662. while (this.rigCameras.length < viewCount) {
  107663. var newCamera = new BABYLON.TargetCamera("view: " + this.rigCameras.length, BABYLON.Vector3.Zero(), this.getScene());
  107664. newCamera.minZ = 0;
  107665. newCamera.parent = this;
  107666. newCamera.rotationQuaternion = new BABYLON.Quaternion();
  107667. this.rigCameras.push(newCamera);
  107668. }
  107669. while (this.rigCameras.length > viewCount) {
  107670. var removedCamera = this.rigCameras.pop();
  107671. if (removedCamera) {
  107672. removedCamera.dispose();
  107673. }
  107674. }
  107675. };
  107676. /** @hidden */
  107677. WebXRCamera.prototype._updateForDualEyeDebugging = function (pupilDistance) {
  107678. if (pupilDistance === void 0) { pupilDistance = 0.01; }
  107679. // Create initial camera rigs
  107680. this._updateNumberOfRigCameras(2);
  107681. this.rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  107682. this.rigCameras[0].position.x = -pupilDistance / 2;
  107683. this.rigCameras[0].outputRenderTarget = null;
  107684. this.rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  107685. this.rigCameras[1].position.x = pupilDistance / 2;
  107686. this.rigCameras[1].outputRenderTarget = null;
  107687. };
  107688. /**
  107689. * Updates the cameras position from the current pose information of the XR session
  107690. * @param xrSessionManager the session containing pose information
  107691. * @returns true if the camera has been updated, false if the session did not contain pose or frame data
  107692. */
  107693. WebXRCamera.prototype.updateFromXRSessionManager = function (xrSessionManager) {
  107694. var _this = this;
  107695. // Ensure all frame data is available
  107696. if (!xrSessionManager._currentXRFrame || !xrSessionManager._currentXRFrame.getDevicePose) {
  107697. return false;
  107698. }
  107699. var pose = xrSessionManager._currentXRFrame.getDevicePose(xrSessionManager._frameOfReference);
  107700. if (!pose || !pose.poseModelMatrix) {
  107701. return false;
  107702. }
  107703. // Update the parent cameras matrix
  107704. BABYLON.Matrix.FromFloat32ArrayToRefScaled(pose.poseModelMatrix, 0, 1, WebXRCamera._TmpMatrix);
  107705. if (!this._scene.useRightHandedSystem) {
  107706. WebXRCamera._TmpMatrix.toggleModelMatrixHandInPlace();
  107707. }
  107708. WebXRCamera._TmpMatrix.getTranslationToRef(this.position);
  107709. WebXRCamera._TmpMatrix.getRotationMatrixToRef(WebXRCamera._TmpMatrix);
  107710. BABYLON.Quaternion.FromRotationMatrixToRef(WebXRCamera._TmpMatrix, this.rotationQuaternion);
  107711. this.computeWorldMatrix();
  107712. // Update camera rigs
  107713. this._updateNumberOfRigCameras(xrSessionManager._currentXRFrame.views.length);
  107714. xrSessionManager._currentXRFrame.views.forEach(function (view, i) {
  107715. // Update view/projection matrix
  107716. BABYLON.Matrix.FromFloat32ArrayToRefScaled(pose.getViewMatrix(view), 0, 1, _this.rigCameras[i]._computedViewMatrix);
  107717. BABYLON.Matrix.FromFloat32ArrayToRefScaled(view.projectionMatrix, 0, 1, _this.rigCameras[i]._projectionMatrix);
  107718. if (!_this._scene.useRightHandedSystem) {
  107719. _this.rigCameras[i]._computedViewMatrix.toggleModelMatrixHandInPlace();
  107720. _this.rigCameras[i]._projectionMatrix.toggleProjectionMatrixHandInPlace();
  107721. }
  107722. // Update viewport
  107723. var viewport = xrSessionManager._xrSession.baseLayer.getViewport(view);
  107724. var width = xrSessionManager._xrSession.baseLayer.framebufferWidth;
  107725. var height = xrSessionManager._xrSession.baseLayer.framebufferHeight;
  107726. _this.rigCameras[i].viewport.width = viewport.width / width;
  107727. _this.rigCameras[i].viewport.height = viewport.height / height;
  107728. _this.rigCameras[i].viewport.x = viewport.x / width;
  107729. _this.rigCameras[i].viewport.y = viewport.y / height;
  107730. // Set cameras to render to the session's render target
  107731. _this.rigCameras[i].outputRenderTarget = xrSessionManager._sessionRenderTargetTexture;
  107732. });
  107733. return true;
  107734. };
  107735. WebXRCamera._TmpMatrix = new BABYLON.Matrix();
  107736. return WebXRCamera;
  107737. }(BABYLON.FreeCamera));
  107738. BABYLON.WebXRCamera = WebXRCamera;
  107739. })(BABYLON || (BABYLON = {}));
  107740. //# sourceMappingURL=webXRCamera.js.map
  107741. var BABYLON;
  107742. (function (BABYLON) {
  107743. /**
  107744. * Manages an XRSession
  107745. * @see https://doc.babylonjs.com/how_to/webxr
  107746. */
  107747. var WebXRSessionManager = /** @class */ (function () {
  107748. /**
  107749. * Constructs a WebXRSessionManager, this must be initialized within a user action before usage
  107750. * @param scene The scene which the session should be created for
  107751. */
  107752. function WebXRSessionManager(scene) {
  107753. this.scene = scene;
  107754. /**
  107755. * Fires every time a new xrFrame arrives which can be used to update the camera
  107756. */
  107757. this.onXRFrameObservable = new BABYLON.Observable();
  107758. /**
  107759. * Fires when the xr session is ended either by the device or manually done
  107760. */
  107761. this.onXRSessionEnded = new BABYLON.Observable();
  107762. /** @hidden */
  107763. this._sessionRenderTargetTexture = null;
  107764. this._tmpMatrix = new BABYLON.Matrix();
  107765. }
  107766. /**
  107767. * Initializes the manager
  107768. * After initialization enterXR can be called to start an XR session
  107769. * @returns Promise which resolves after it is initialized
  107770. */
  107771. WebXRSessionManager.prototype.initializeAsync = function () {
  107772. var _this = this;
  107773. // Check if the browser supports webXR
  107774. this._xrNavigator = navigator;
  107775. if (!this._xrNavigator.xr) {
  107776. return Promise.reject("webXR not supported by this browser");
  107777. }
  107778. // Request the webXR device
  107779. return this._xrNavigator.xr.requestDevice().then(function (device) {
  107780. _this._xrDevice = device;
  107781. return _this.scene.getEngine()._gl.setCompatibleXRDevice(_this._xrDevice);
  107782. });
  107783. };
  107784. /**
  107785. * Enters XR with the desired XR session options, this must be done with a user action (eg. button click event)
  107786. * @param sessionCreationOptions xr options to create the session with
  107787. * @param frameOfReferenceType option to configure how the xr pose is expressed
  107788. * @returns Promise which resolves after it enters XR
  107789. */
  107790. WebXRSessionManager.prototype.enterXRAsync = function (sessionCreationOptions, frameOfReferenceType) {
  107791. var _this = this;
  107792. // initialize session
  107793. return this._xrDevice.requestSession(sessionCreationOptions).then(function (session) {
  107794. _this._xrSession = session;
  107795. // handle when the session is ended (By calling session.end or device ends its own session eg. pressing home button on phone)
  107796. _this._xrSession.addEventListener("end", function () {
  107797. // Remove render target texture and notify frame obervers
  107798. _this._sessionRenderTargetTexture = null;
  107799. // Restore frame buffer to avoid clear on xr framebuffer after session end
  107800. _this.scene.getEngine().restoreDefaultFramebuffer();
  107801. // Need to restart render loop as after the session is ended the last request for new frame will never call callback
  107802. _this.scene.getEngine().customAnimationFrameRequester = null;
  107803. _this.onXRSessionEnded.notifyObservers(null);
  107804. _this.scene.getEngine()._renderLoop();
  107805. }, { once: true });
  107806. _this._xrSession.baseLayer = new XRWebGLLayer(_this._xrSession, _this.scene.getEngine()._gl);
  107807. return _this._xrSession.requestFrameOfReference(frameOfReferenceType);
  107808. }).then(function (frameOfRef) {
  107809. _this._frameOfReference = frameOfRef;
  107810. // Tell the engine's render loop to be driven by the xr session's refresh rate and provide xr pose information
  107811. _this.scene.getEngine().customAnimationFrameRequester = {
  107812. requestAnimationFrame: _this._xrSession.requestAnimationFrame.bind(_this._xrSession),
  107813. renderFunction: function (timestamp, xrFrame) {
  107814. // Store the XR frame in the manager to be consumed by the XR camera to update pose
  107815. _this._currentXRFrame = xrFrame;
  107816. _this.onXRFrameObservable.notifyObservers(null);
  107817. _this.scene.getEngine()._renderLoop();
  107818. }
  107819. };
  107820. // Create render target texture from xr's webgl render target
  107821. _this._sessionRenderTargetTexture = WebXRSessionManager._CreateRenderTargetTextureFromSession(_this._xrSession, _this.scene);
  107822. // Stop window's animation frame and trigger sessions animation frame
  107823. window.cancelAnimationFrame(_this.scene.getEngine()._frameHandler);
  107824. _this.scene.getEngine()._renderLoop();
  107825. });
  107826. };
  107827. /**
  107828. * Stops the xrSession and restores the renderloop
  107829. * @returns Promise which resolves after it exits XR
  107830. */
  107831. WebXRSessionManager.prototype.exitXRAsync = function () {
  107832. return this._xrSession.end();
  107833. };
  107834. /**
  107835. * Fires a ray and returns the closest hit in the xr sessions enviornment, useful to place objects in AR
  107836. * @param ray ray to cast into the environment
  107837. * @returns Promise which resolves with a collision point in the environment if it exists
  107838. */
  107839. WebXRSessionManager.prototype.environmentPointHitTestAsync = function (ray) {
  107840. var _this = this;
  107841. return new Promise(function (res, rej) {
  107842. // Compute left handed inputs to request hit test
  107843. var origin = new Float32Array([ray.origin.x, ray.origin.y, ray.origin.z]);
  107844. var direction = new Float32Array([ray.direction.x, ray.direction.y, ray.direction.z]);
  107845. if (!_this.scene.useRightHandedSystem) {
  107846. origin[2] *= -1;
  107847. direction[2] *= -1;
  107848. }
  107849. // Fire hittest
  107850. _this._xrSession.requestHitTest(origin, direction, _this._frameOfReference)
  107851. .then(function (hits) {
  107852. if (hits.length > 0) {
  107853. BABYLON.Matrix.FromFloat32ArrayToRefScaled(hits[0].hitMatrix, 0, 1.0, _this._tmpMatrix);
  107854. var hitPoint = _this._tmpMatrix.getTranslation();
  107855. if (!_this.scene.useRightHandedSystem) {
  107856. hitPoint.z *= -1;
  107857. }
  107858. res(hitPoint);
  107859. }
  107860. else {
  107861. res(null);
  107862. }
  107863. }).catch(function (e) {
  107864. res(null);
  107865. });
  107866. });
  107867. };
  107868. /**
  107869. * Checks if a session would be supported for the creation options specified
  107870. * @param options creation options to check if they are supported
  107871. * @returns true if supported
  107872. */
  107873. WebXRSessionManager.prototype.supportsSessionAsync = function (options) {
  107874. return this._xrDevice.supportsSession(options).then(function () {
  107875. return true;
  107876. }).catch(function (e) {
  107877. return false;
  107878. });
  107879. };
  107880. /**
  107881. * @hidden
  107882. * Converts the render layer of xrSession to a render target
  107883. * @param session session to create render target for
  107884. * @param scene scene the new render target should be created for
  107885. */
  107886. WebXRSessionManager._CreateRenderTargetTextureFromSession = function (session, scene) {
  107887. // Create internal texture
  107888. var internalTexture = new BABYLON.InternalTexture(scene.getEngine(), BABYLON.InternalTexture.DATASOURCE_UNKNOWN, true);
  107889. internalTexture.width = session.baseLayer.framebufferWidth;
  107890. internalTexture.height = session.baseLayer.framebufferHeight;
  107891. internalTexture._framebuffer = session.baseLayer.framebuffer;
  107892. // Create render target texture from the internal texture
  107893. var renderTargetTexture = new BABYLON.RenderTargetTexture("XR renderTargetTexture", { width: internalTexture.width, height: internalTexture.height }, scene, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, true);
  107894. renderTargetTexture._texture = internalTexture;
  107895. return renderTargetTexture;
  107896. };
  107897. /**
  107898. * Disposes of the session manager
  107899. */
  107900. WebXRSessionManager.prototype.dispose = function () {
  107901. this.onXRFrameObservable.clear();
  107902. this.onXRSessionEnded.clear();
  107903. };
  107904. return WebXRSessionManager;
  107905. }());
  107906. BABYLON.WebXRSessionManager = WebXRSessionManager;
  107907. })(BABYLON || (BABYLON = {}));
  107908. //# sourceMappingURL=webXRSessionManager.js.map
  107909. var BABYLON;
  107910. (function (BABYLON) {
  107911. /**
  107912. * States of the webXR experience
  107913. */
  107914. var WebXRState;
  107915. (function (WebXRState) {
  107916. /**
  107917. * Transitioning to being in XR mode
  107918. */
  107919. WebXRState[WebXRState["ENTERING_XR"] = 0] = "ENTERING_XR";
  107920. /**
  107921. * Transitioning to non XR mode
  107922. */
  107923. WebXRState[WebXRState["EXITING_XR"] = 1] = "EXITING_XR";
  107924. /**
  107925. * In XR mode and presenting
  107926. */
  107927. WebXRState[WebXRState["IN_XR"] = 2] = "IN_XR";
  107928. /**
  107929. * Not entered XR mode
  107930. */
  107931. WebXRState[WebXRState["NOT_IN_XR"] = 3] = "NOT_IN_XR";
  107932. })(WebXRState = BABYLON.WebXRState || (BABYLON.WebXRState = {}));
  107933. /**
  107934. * Helper class used to enable XR
  107935. * @see https://doc.babylonjs.com/how_to/webxr
  107936. */
  107937. var WebXRExperienceHelper = /** @class */ (function () {
  107938. /**
  107939. * Creates a WebXRExperienceHelper
  107940. * @param scene The scene the helper should be created in
  107941. */
  107942. function WebXRExperienceHelper(scene) {
  107943. this.scene = scene;
  107944. /**
  107945. * The current state of the XR experience (eg. transitioning, in XR or not in XR)
  107946. */
  107947. this.state = WebXRState.NOT_IN_XR;
  107948. /**
  107949. * Fires when the state of the experience helper has changed
  107950. */
  107951. this.onStateChangedObservable = new BABYLON.Observable();
  107952. this._nonVRCamera = null;
  107953. this._originalSceneAutoClear = true;
  107954. this._supported = false;
  107955. this.camera = new BABYLON.WebXRCamera("", scene);
  107956. this._sessionManager = new BABYLON.WebXRSessionManager(scene);
  107957. this.container = new BABYLON.AbstractMesh("", scene);
  107958. this.camera.parent = this.container;
  107959. }
  107960. WebXRExperienceHelper.prototype._setState = function (val) {
  107961. this.state = val;
  107962. this.onStateChangedObservable.notifyObservers(this.state);
  107963. };
  107964. /**
  107965. * Creates the experience helper
  107966. * @param scene the scene to attach the experience helper to
  107967. * @returns a promise for the experience helper
  107968. */
  107969. WebXRExperienceHelper.CreateAsync = function (scene) {
  107970. var helper = new WebXRExperienceHelper(scene);
  107971. return helper._sessionManager.initializeAsync().then(function () {
  107972. helper._supported = true;
  107973. return helper;
  107974. }).catch(function () {
  107975. return helper;
  107976. });
  107977. };
  107978. /**
  107979. * Exits XR mode and returns the scene to its original state
  107980. * @returns promise that resolves after xr mode has exited
  107981. */
  107982. WebXRExperienceHelper.prototype.exitXRAsync = function () {
  107983. this._setState(WebXRState.EXITING_XR);
  107984. return this._sessionManager.exitXRAsync();
  107985. };
  107986. /**
  107987. * Enters XR mode (This must be done within a user interaction in most browsers eg. button click)
  107988. * @param sessionCreationOptions options for the XR session
  107989. * @param frameOfReference frame of reference of the XR session
  107990. * @returns promise that resolves after xr mode has entered
  107991. */
  107992. WebXRExperienceHelper.prototype.enterXRAsync = function (sessionCreationOptions, frameOfReference) {
  107993. var _this = this;
  107994. this._setState(WebXRState.ENTERING_XR);
  107995. return this._sessionManager.enterXRAsync(sessionCreationOptions, frameOfReference).then(function () {
  107996. // Cache pre xr scene settings
  107997. _this._originalSceneAutoClear = _this.scene.autoClear;
  107998. _this._nonVRCamera = _this.scene.activeCamera;
  107999. // Overwrite current scene settings
  108000. _this.scene.autoClear = false;
  108001. _this.scene.activeCamera = _this.camera;
  108002. _this._sessionManager.onXRFrameObservable.add(function () {
  108003. _this.camera.updateFromXRSessionManager(_this._sessionManager);
  108004. });
  108005. _this._sessionManager.onXRSessionEnded.addOnce(function () {
  108006. // Reset camera rigs output render target to ensure sessions render target is not drawn after it ends
  108007. _this.camera.rigCameras.forEach(function (c) {
  108008. c.outputRenderTarget = null;
  108009. });
  108010. // Restore scene settings
  108011. _this.scene.autoClear = _this._originalSceneAutoClear;
  108012. _this.scene.activeCamera = _this._nonVRCamera;
  108013. _this._sessionManager.onXRFrameObservable.clear();
  108014. _this._setState(WebXRState.NOT_IN_XR);
  108015. });
  108016. _this._setState(WebXRState.IN_XR);
  108017. });
  108018. };
  108019. /**
  108020. * Fires a ray and returns the closest hit in the xr sessions enviornment, useful to place objects in AR
  108021. * @param ray ray to cast into the environment
  108022. * @returns Promise which resolves with a collision point in the environment if it exists
  108023. */
  108024. WebXRExperienceHelper.prototype.environmentPointHitTestAsync = function (ray) {
  108025. return this._sessionManager.environmentPointHitTestAsync(ray);
  108026. };
  108027. /**
  108028. * Updates the global position of the camera by moving the camera's container
  108029. * This should be used instead of modifying the camera's position as it will be overwritten by an xrSessions's update frame
  108030. * @param position The desired global position of the camera
  108031. */
  108032. WebXRExperienceHelper.prototype.setPositionOfCameraUsingContainer = function (position) {
  108033. this.camera.globalPosition.subtractToRef(position, WebXRExperienceHelper._TmpVector);
  108034. this.container.position.subtractInPlace(WebXRExperienceHelper._TmpVector);
  108035. };
  108036. /**
  108037. * Rotates the xr camera by rotating the camera's container around the camera's position
  108038. * This should be used instead of modifying the camera's rotation as it will be overwritten by an xrSessions's update frame
  108039. * @param rotation the desired quaternion rotation to apply to the camera
  108040. */
  108041. WebXRExperienceHelper.prototype.rotateCameraByQuaternionUsingContainer = function (rotation) {
  108042. if (!this.container.rotationQuaternion) {
  108043. this.container.rotationQuaternion = BABYLON.Quaternion.FromEulerVector(this.container.rotation);
  108044. }
  108045. this.container.rotationQuaternion.multiplyInPlace(rotation);
  108046. this.container.position.rotateByQuaternionAroundPointToRef(rotation, this.camera.globalPosition, this.container.position);
  108047. };
  108048. /**
  108049. * Checks if the creation options are supported by the xr session
  108050. * @param options creation options
  108051. * @returns true if supported
  108052. */
  108053. WebXRExperienceHelper.prototype.supportsSessionAsync = function (options) {
  108054. if (!this._supported) {
  108055. return Promise.resolve(false);
  108056. }
  108057. return this._sessionManager.supportsSessionAsync(options);
  108058. };
  108059. /**
  108060. * Disposes of the experience helper
  108061. */
  108062. WebXRExperienceHelper.prototype.dispose = function () {
  108063. this.camera.dispose();
  108064. this.container.dispose();
  108065. this.onStateChangedObservable.clear();
  108066. this._sessionManager.dispose();
  108067. };
  108068. WebXRExperienceHelper._TmpVector = new BABYLON.Vector3();
  108069. return WebXRExperienceHelper;
  108070. }());
  108071. BABYLON.WebXRExperienceHelper = WebXRExperienceHelper;
  108072. })(BABYLON || (BABYLON = {}));
  108073. //# sourceMappingURL=webXRExperienceHelper.js.map
  108074. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  108075. return new (P || (P = Promise))(function (resolve, reject) {
  108076. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  108077. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  108078. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  108079. step((generator = generator.apply(thisArg, _arguments || [])).next());
  108080. });
  108081. };
  108082. var __generator = (this && this.__generator) || function (thisArg, body) {
  108083. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  108084. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  108085. function verb(n) { return function (v) { return step([n, v]); }; }
  108086. function step(op) {
  108087. if (f) throw new TypeError("Generator is already executing.");
  108088. while (_) try {
  108089. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  108090. if (y = 0, t) op = [op[0] & 2, t.value];
  108091. switch (op[0]) {
  108092. case 0: case 1: t = op; break;
  108093. case 4: _.label++; return { value: op[1], done: false };
  108094. case 5: _.label++; y = op[1]; op = [0]; continue;
  108095. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  108096. default:
  108097. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  108098. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  108099. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  108100. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  108101. if (t[2]) _.ops.pop();
  108102. _.trys.pop(); continue;
  108103. }
  108104. op = body.call(thisArg, _);
  108105. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  108106. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  108107. }
  108108. };
  108109. var BABYLON;
  108110. (function (BABYLON) {
  108111. /**
  108112. * Button which can be used to enter a different mode of XR
  108113. */
  108114. var WebXREnterExitUIButton = /** @class */ (function () {
  108115. /**
  108116. * Creates a WebXREnterExitUIButton
  108117. * @param element button element
  108118. * @param initializationOptions XR initialization options for the button
  108119. */
  108120. function WebXREnterExitUIButton(
  108121. /** button element */
  108122. element,
  108123. /** XR initialization options for the button */
  108124. initializationOptions) {
  108125. this.element = element;
  108126. this.initializationOptions = initializationOptions;
  108127. }
  108128. /**
  108129. * Overwritable function which can be used to update the button's visuals when the state changes
  108130. * @param activeButton the current active button in the UI
  108131. */
  108132. WebXREnterExitUIButton.prototype.update = function (activeButton) {
  108133. };
  108134. return WebXREnterExitUIButton;
  108135. }());
  108136. BABYLON.WebXREnterExitUIButton = WebXREnterExitUIButton;
  108137. /**
  108138. * Options to create the webXR UI
  108139. */
  108140. var WebXREnterExitUIOptions = /** @class */ (function () {
  108141. function WebXREnterExitUIOptions() {
  108142. }
  108143. return WebXREnterExitUIOptions;
  108144. }());
  108145. BABYLON.WebXREnterExitUIOptions = WebXREnterExitUIOptions;
  108146. /**
  108147. * UI to allow the user to enter/exit XR mode
  108148. */
  108149. var WebXREnterExitUI = /** @class */ (function () {
  108150. function WebXREnterExitUI(scene, options) {
  108151. var _this = this;
  108152. this.scene = scene;
  108153. this._buttons = [];
  108154. this._activeButton = null;
  108155. /**
  108156. * Fired every time the active button is changed.
  108157. *
  108158. * When xr is entered via a button that launches xr that button will be the callback parameter
  108159. *
  108160. * When exiting xr the callback parameter will be null)
  108161. */
  108162. this.activeButtonChangedObservable = new BABYLON.Observable();
  108163. this._overlay = document.createElement("div");
  108164. this._overlay.style.cssText = "z-index:11;position: absolute; right: 20px;bottom: 50px;";
  108165. if (options.customButtons) {
  108166. this._buttons = options.customButtons;
  108167. }
  108168. else {
  108169. var hmdBtn = document.createElement("button");
  108170. hmdBtn.style.cssText = "color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-repeat:no-repeat; background-position: center; outline: none;";
  108171. hmdBtn.innerText = "HMD";
  108172. this._buttons.push(new WebXREnterExitUIButton(hmdBtn, { immersive: true, outputContext: options.outputCanvasContext }));
  108173. this._buttons[this._buttons.length - 1].update = function (activeButton) {
  108174. this.element.style.display = (activeButton === null || activeButton === this) ? "" : "none";
  108175. this.element.innerText = activeButton === this ? "EXIT" : "HMD";
  108176. };
  108177. var windowBtn = document.createElement("button");
  108178. windowBtn.style.cssText = hmdBtn.style.cssText;
  108179. windowBtn.innerText = "Window";
  108180. this._buttons.push(new WebXREnterExitUIButton(windowBtn, { immersive: false, environmentIntegration: true, outputContext: options.outputCanvasContext }));
  108181. this._buttons[this._buttons.length - 1].update = function (activeButton) {
  108182. this.element.style.display = (activeButton === null || activeButton === this) ? "" : "none";
  108183. this.element.innerText = activeButton === this ? "EXIT" : "Window";
  108184. };
  108185. this._updateButtons(null);
  108186. }
  108187. var renderCanvas = scene.getEngine().getRenderingCanvas();
  108188. if (renderCanvas && renderCanvas.parentNode) {
  108189. renderCanvas.parentNode.appendChild(this._overlay);
  108190. scene.onDisposeObservable.addOnce(function () {
  108191. _this.dispose();
  108192. });
  108193. }
  108194. }
  108195. /**
  108196. * Creates UI to allow the user to enter/exit XR mode
  108197. * @param scene the scene to add the ui to
  108198. * @param helper the xr experience helper to enter/exit xr with
  108199. * @param options options to configure the UI
  108200. * @returns the created ui
  108201. */
  108202. WebXREnterExitUI.CreateAsync = function (scene, helper, options) {
  108203. var _this = this;
  108204. var ui = new WebXREnterExitUI(scene, options);
  108205. var supportedPromises = ui._buttons.map(function (btn) {
  108206. return helper.supportsSessionAsync(btn.initializationOptions);
  108207. });
  108208. helper.onStateChangedObservable.add(function (state) {
  108209. if (state == BABYLON.WebXRState.NOT_IN_XR) {
  108210. ui._updateButtons(null);
  108211. }
  108212. });
  108213. return Promise.all(supportedPromises).then(function (results) {
  108214. results.forEach(function (supported, i) {
  108215. if (supported) {
  108216. ui._overlay.appendChild(ui._buttons[i].element);
  108217. ui._buttons[i].element.onclick = function () { return __awaiter(_this, void 0, void 0, function () {
  108218. return __generator(this, function (_a) {
  108219. switch (_a.label) {
  108220. case 0:
  108221. if (!(helper.state == BABYLON.WebXRState.IN_XR)) return [3 /*break*/, 2];
  108222. ui._updateButtons(null);
  108223. return [4 /*yield*/, helper.exitXRAsync()];
  108224. case 1:
  108225. _a.sent();
  108226. return [2 /*return*/];
  108227. case 2:
  108228. if (!(helper.state == BABYLON.WebXRState.NOT_IN_XR)) return [3 /*break*/, 4];
  108229. ui._updateButtons(ui._buttons[i]);
  108230. return [4 /*yield*/, helper.enterXRAsync(ui._buttons[i].initializationOptions, "eye-level")];
  108231. case 3:
  108232. _a.sent();
  108233. _a.label = 4;
  108234. case 4: return [2 /*return*/];
  108235. }
  108236. });
  108237. }); };
  108238. }
  108239. });
  108240. return ui;
  108241. });
  108242. };
  108243. WebXREnterExitUI.prototype._updateButtons = function (activeButton) {
  108244. var _this = this;
  108245. this._activeButton = activeButton;
  108246. this._buttons.forEach(function (b) {
  108247. b.update(_this._activeButton);
  108248. });
  108249. this.activeButtonChangedObservable.notifyObservers(this._activeButton);
  108250. };
  108251. /**
  108252. * Disposes of the object
  108253. */
  108254. WebXREnterExitUI.prototype.dispose = function () {
  108255. var renderCanvas = this.scene.getEngine().getRenderingCanvas();
  108256. if (renderCanvas && renderCanvas.parentNode && renderCanvas.parentNode.contains(this._overlay)) {
  108257. renderCanvas.parentNode.removeChild(this._overlay);
  108258. }
  108259. this.activeButtonChangedObservable.clear();
  108260. };
  108261. return WebXREnterExitUI;
  108262. }());
  108263. BABYLON.WebXREnterExitUI = WebXREnterExitUI;
  108264. })(BABYLON || (BABYLON = {}));
  108265. //# sourceMappingURL=webXREnterExitUI.js.map
  108266. var BABYLON;
  108267. (function (BABYLON) {
  108268. /**
  108269. * Creates a canvas that is added/removed from the webpage when entering/exiting XR
  108270. */
  108271. var WebXRManagedOutputCanvas = /** @class */ (function () {
  108272. /**
  108273. * Initializes the canvas to be added/removed upon entering/exiting xr
  108274. * @param helper the xr experience helper used to trigger adding/removing of the canvas
  108275. * @param canvas The canvas to be added/removed (If not specified a full screen canvas will be created)
  108276. */
  108277. function WebXRManagedOutputCanvas(helper, canvas) {
  108278. var _this = this;
  108279. this._canvas = null;
  108280. /**
  108281. * xrpresent context of the canvas which can be used to display/mirror xr content
  108282. */
  108283. this.canvasContext = null;
  108284. if (!canvas) {
  108285. canvas = document.createElement('canvas');
  108286. canvas.style.cssText = "position:absolute; bottom:0px;right:0px;z-index:10;width:100%;height:100%;background-color: #000000;";
  108287. }
  108288. this._setManagedOutputCanvas(canvas);
  108289. helper.onStateChangedObservable.add(function (stateInfo) {
  108290. if (stateInfo == BABYLON.WebXRState.ENTERING_XR) {
  108291. // The canvas is added to the screen before entering XR because currently the xr session must be initialized while the canvas is added render properly
  108292. _this._addCanvas();
  108293. }
  108294. else if (helper.state == BABYLON.WebXRState.NOT_IN_XR) {
  108295. _this._removeCanvas();
  108296. }
  108297. });
  108298. }
  108299. /**
  108300. * Disposes of the object
  108301. */
  108302. WebXRManagedOutputCanvas.prototype.dispose = function () {
  108303. this._removeCanvas();
  108304. this._setManagedOutputCanvas(null);
  108305. };
  108306. WebXRManagedOutputCanvas.prototype._setManagedOutputCanvas = function (canvas) {
  108307. this._removeCanvas();
  108308. if (!canvas) {
  108309. this._canvas = null;
  108310. this.canvasContext = null;
  108311. }
  108312. else {
  108313. this._canvas = canvas;
  108314. this.canvasContext = this._canvas.getContext('xrpresent');
  108315. }
  108316. };
  108317. WebXRManagedOutputCanvas.prototype._addCanvas = function () {
  108318. if (this._canvas) {
  108319. document.body.appendChild(this._canvas);
  108320. }
  108321. };
  108322. WebXRManagedOutputCanvas.prototype._removeCanvas = function () {
  108323. if (this._canvas && document.body.contains(this._canvas)) {
  108324. document.body.removeChild(this._canvas);
  108325. }
  108326. };
  108327. return WebXRManagedOutputCanvas;
  108328. }());
  108329. BABYLON.WebXRManagedOutputCanvas = WebXRManagedOutputCanvas;
  108330. })(BABYLON || (BABYLON = {}));
  108331. //# sourceMappingURL=webXRManagedOutputCanvas.js.map
  108332. var BABYLON;
  108333. (function (BABYLON) {
  108334. /**
  108335. * Represents an XR input
  108336. */
  108337. var WebXRController = /** @class */ (function () {
  108338. /**
  108339. * Creates the controller
  108340. * @see https://doc.babylonjs.com/how_to/webxr
  108341. * @param scene the scene which the controller should be associated to
  108342. */
  108343. function WebXRController(scene) {
  108344. this.pointer = new BABYLON.AbstractMesh("controllerPointer", scene);
  108345. }
  108346. /**
  108347. * Disposes of the object
  108348. */
  108349. WebXRController.prototype.dispose = function () {
  108350. if (this.grip) {
  108351. this.grip.dispose();
  108352. }
  108353. this.pointer.dispose();
  108354. };
  108355. return WebXRController;
  108356. }());
  108357. BABYLON.WebXRController = WebXRController;
  108358. /**
  108359. * XR input used to track XR inputs such as controllers/rays
  108360. */
  108361. var WebXRInput = /** @class */ (function () {
  108362. /**
  108363. * Initializes the WebXRInput
  108364. * @param helper experience helper which the input should be created for
  108365. */
  108366. function WebXRInput(helper) {
  108367. var _this = this;
  108368. this.helper = helper;
  108369. /**
  108370. * XR controllers being tracked
  108371. */
  108372. this.controllers = [];
  108373. this._tmpMatrix = new BABYLON.Matrix();
  108374. this._frameObserver = helper._sessionManager.onXRFrameObservable.add(function () {
  108375. if (!helper._sessionManager._currentXRFrame || !helper._sessionManager._currentXRFrame.getDevicePose) {
  108376. return;
  108377. }
  108378. var xrFrame = helper._sessionManager._currentXRFrame;
  108379. var inputSources = helper._sessionManager._xrSession.getInputSources();
  108380. inputSources.forEach(function (input, i) {
  108381. var inputPose = xrFrame.getInputPose(input, helper._sessionManager._frameOfReference);
  108382. if (inputPose) {
  108383. if (_this.controllers.length <= i) {
  108384. _this.controllers.push(new WebXRController(helper.container.getScene()));
  108385. }
  108386. var controller = _this.controllers[i];
  108387. // Manage the grip if it exists
  108388. if (inputPose.gripMatrix) {
  108389. if (!controller.grip) {
  108390. controller.grip = new BABYLON.AbstractMesh("controllerGrip", helper.container.getScene());
  108391. }
  108392. BABYLON.Matrix.FromFloat32ArrayToRefScaled(inputPose.gripMatrix, 0, 1, _this._tmpMatrix);
  108393. if (!controller.grip.getScene().useRightHandedSystem) {
  108394. _this._tmpMatrix.toggleModelMatrixHandInPlace();
  108395. }
  108396. if (!controller.grip.rotationQuaternion) {
  108397. controller.grip.rotationQuaternion = new BABYLON.Quaternion();
  108398. }
  108399. _this._tmpMatrix.decompose(controller.grip.scaling, controller.grip.rotationQuaternion, controller.grip.position);
  108400. }
  108401. // Manager pointer of controller
  108402. BABYLON.Matrix.FromFloat32ArrayToRefScaled(inputPose.targetRay.transformMatrix, 0, 1, _this._tmpMatrix);
  108403. if (!controller.pointer.getScene().useRightHandedSystem) {
  108404. _this._tmpMatrix.toggleModelMatrixHandInPlace();
  108405. }
  108406. if (!controller.pointer.rotationQuaternion) {
  108407. controller.pointer.rotationQuaternion = new BABYLON.Quaternion();
  108408. }
  108409. _this._tmpMatrix.decompose(controller.pointer.scaling, controller.pointer.rotationQuaternion, controller.pointer.position);
  108410. }
  108411. });
  108412. });
  108413. }
  108414. /**
  108415. * Disposes of the object
  108416. */
  108417. WebXRInput.prototype.dispose = function () {
  108418. this.controllers.forEach(function (c) {
  108419. c.dispose();
  108420. });
  108421. this.helper._sessionManager.onXRFrameObservable.remove(this._frameObserver);
  108422. };
  108423. return WebXRInput;
  108424. }());
  108425. BABYLON.WebXRInput = WebXRInput;
  108426. })(BABYLON || (BABYLON = {}));
  108427. //# sourceMappingURL=webXRInput.js.map
  108428. // Mainly based on these 2 articles :
  108429. // 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
  108430. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  108431. var BABYLON;
  108432. (function (BABYLON) {
  108433. /**
  108434. * Defines the potential axis of a Joystick
  108435. */
  108436. var JoystickAxis;
  108437. (function (JoystickAxis) {
  108438. /** X axis */
  108439. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  108440. /** Y axis */
  108441. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  108442. /** Z axis */
  108443. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  108444. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  108445. /**
  108446. * Class used to define virtual joystick (used in touch mode)
  108447. */
  108448. var VirtualJoystick = /** @class */ (function () {
  108449. /**
  108450. * Creates a new virtual joystick
  108451. * @param leftJoystick defines that the joystick is for left hand (false by default)
  108452. */
  108453. function VirtualJoystick(leftJoystick) {
  108454. var _this = this;
  108455. if (leftJoystick) {
  108456. this._leftJoystick = true;
  108457. }
  108458. else {
  108459. this._leftJoystick = false;
  108460. }
  108461. VirtualJoystick._globalJoystickIndex++;
  108462. // By default left & right arrow keys are moving the X
  108463. // and up & down keys are moving the Y
  108464. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  108465. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  108466. this.reverseLeftRight = false;
  108467. this.reverseUpDown = false;
  108468. // collections of pointers
  108469. this._touches = new BABYLON.StringDictionary();
  108470. this.deltaPosition = BABYLON.Vector3.Zero();
  108471. this._joystickSensibility = 25;
  108472. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  108473. this._onResize = function (evt) {
  108474. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  108475. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  108476. if (VirtualJoystick.vjCanvas) {
  108477. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  108478. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  108479. }
  108480. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  108481. };
  108482. // injecting a canvas element on top of the canvas 3D game
  108483. if (!VirtualJoystick.vjCanvas) {
  108484. window.addEventListener("resize", this._onResize, false);
  108485. VirtualJoystick.vjCanvas = document.createElement("canvas");
  108486. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  108487. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  108488. VirtualJoystick.vjCanvas.width = window.innerWidth;
  108489. VirtualJoystick.vjCanvas.height = window.innerHeight;
  108490. VirtualJoystick.vjCanvas.style.width = "100%";
  108491. VirtualJoystick.vjCanvas.style.height = "100%";
  108492. VirtualJoystick.vjCanvas.style.position = "absolute";
  108493. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  108494. VirtualJoystick.vjCanvas.style.top = "0px";
  108495. VirtualJoystick.vjCanvas.style.left = "0px";
  108496. VirtualJoystick.vjCanvas.style.zIndex = "5";
  108497. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  108498. // Support for jQuery PEP polyfill
  108499. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  108500. var context = VirtualJoystick.vjCanvas.getContext('2d');
  108501. if (!context) {
  108502. throw new Error("Unable to create canvas for virtual joystick");
  108503. }
  108504. VirtualJoystick.vjCanvasContext = context;
  108505. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  108506. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  108507. document.body.appendChild(VirtualJoystick.vjCanvas);
  108508. }
  108509. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  108510. this.pressed = false;
  108511. // default joystick color
  108512. this._joystickColor = "cyan";
  108513. this._joystickPointerID = -1;
  108514. // current joystick position
  108515. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  108516. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  108517. // origin joystick position
  108518. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  108519. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  108520. this._onPointerDownHandlerRef = function (evt) {
  108521. _this._onPointerDown(evt);
  108522. };
  108523. this._onPointerMoveHandlerRef = function (evt) {
  108524. _this._onPointerMove(evt);
  108525. };
  108526. this._onPointerUpHandlerRef = function (evt) {
  108527. _this._onPointerUp(evt);
  108528. };
  108529. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  108530. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  108531. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  108532. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  108533. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  108534. evt.preventDefault(); // Disables system menu
  108535. }, false);
  108536. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  108537. }
  108538. /**
  108539. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  108540. * @param newJoystickSensibility defines the new sensibility
  108541. */
  108542. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  108543. this._joystickSensibility = newJoystickSensibility;
  108544. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  108545. };
  108546. VirtualJoystick.prototype._onPointerDown = function (e) {
  108547. var positionOnScreenCondition;
  108548. e.preventDefault();
  108549. if (this._leftJoystick === true) {
  108550. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  108551. }
  108552. else {
  108553. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  108554. }
  108555. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  108556. // First contact will be dedicated to the virtual joystick
  108557. this._joystickPointerID = e.pointerId;
  108558. this._joystickPointerStartPos.x = e.clientX;
  108559. this._joystickPointerStartPos.y = e.clientY;
  108560. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  108561. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  108562. this._deltaJoystickVector.x = 0;
  108563. this._deltaJoystickVector.y = 0;
  108564. this.pressed = true;
  108565. this._touches.add(e.pointerId.toString(), e);
  108566. }
  108567. else {
  108568. // You can only trigger the action buttons with a joystick declared
  108569. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  108570. this._action();
  108571. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  108572. }
  108573. }
  108574. };
  108575. VirtualJoystick.prototype._onPointerMove = function (e) {
  108576. // If the current pointer is the one associated to the joystick (first touch contact)
  108577. if (this._joystickPointerID == e.pointerId) {
  108578. this._joystickPointerPos.x = e.clientX;
  108579. this._joystickPointerPos.y = e.clientY;
  108580. this._deltaJoystickVector = this._joystickPointerPos.clone();
  108581. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  108582. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  108583. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  108584. switch (this._axisTargetedByLeftAndRight) {
  108585. case JoystickAxis.X:
  108586. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  108587. break;
  108588. case JoystickAxis.Y:
  108589. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  108590. break;
  108591. case JoystickAxis.Z:
  108592. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  108593. break;
  108594. }
  108595. var directionUpDown = this.reverseUpDown ? 1 : -1;
  108596. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  108597. switch (this._axisTargetedByUpAndDown) {
  108598. case JoystickAxis.X:
  108599. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  108600. break;
  108601. case JoystickAxis.Y:
  108602. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  108603. break;
  108604. case JoystickAxis.Z:
  108605. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  108606. break;
  108607. }
  108608. }
  108609. else {
  108610. var data = this._touches.get(e.pointerId.toString());
  108611. if (data) {
  108612. data.x = e.clientX;
  108613. data.y = e.clientY;
  108614. }
  108615. }
  108616. };
  108617. VirtualJoystick.prototype._onPointerUp = function (e) {
  108618. if (this._joystickPointerID == e.pointerId) {
  108619. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  108620. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  108621. this._joystickPointerID = -1;
  108622. this.pressed = false;
  108623. }
  108624. else {
  108625. var touch = this._touches.get(e.pointerId.toString());
  108626. if (touch) {
  108627. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  108628. }
  108629. }
  108630. this._deltaJoystickVector.x = 0;
  108631. this._deltaJoystickVector.y = 0;
  108632. this._touches.remove(e.pointerId.toString());
  108633. };
  108634. /**
  108635. * Change the color of the virtual joystick
  108636. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  108637. */
  108638. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  108639. this._joystickColor = newColor;
  108640. };
  108641. /**
  108642. * Defines a callback to call when the joystick is touched
  108643. * @param action defines the callback
  108644. */
  108645. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  108646. this._action = action;
  108647. };
  108648. /**
  108649. * Defines which axis you'd like to control for left & right
  108650. * @param axis defines the axis to use
  108651. */
  108652. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  108653. switch (axis) {
  108654. case JoystickAxis.X:
  108655. case JoystickAxis.Y:
  108656. case JoystickAxis.Z:
  108657. this._axisTargetedByLeftAndRight = axis;
  108658. break;
  108659. default:
  108660. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  108661. break;
  108662. }
  108663. };
  108664. /**
  108665. * Defines which axis you'd like to control for up & down
  108666. * @param axis defines the axis to use
  108667. */
  108668. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  108669. switch (axis) {
  108670. case JoystickAxis.X:
  108671. case JoystickAxis.Y:
  108672. case JoystickAxis.Z:
  108673. this._axisTargetedByUpAndDown = axis;
  108674. break;
  108675. default:
  108676. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  108677. break;
  108678. }
  108679. };
  108680. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  108681. var _this = this;
  108682. if (this.pressed) {
  108683. this._touches.forEach(function (key, touch) {
  108684. if (touch.pointerId === _this._joystickPointerID) {
  108685. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  108686. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  108687. VirtualJoystick.vjCanvasContext.beginPath();
  108688. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  108689. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  108690. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  108691. VirtualJoystick.vjCanvasContext.stroke();
  108692. VirtualJoystick.vjCanvasContext.closePath();
  108693. VirtualJoystick.vjCanvasContext.beginPath();
  108694. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  108695. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  108696. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  108697. VirtualJoystick.vjCanvasContext.stroke();
  108698. VirtualJoystick.vjCanvasContext.closePath();
  108699. VirtualJoystick.vjCanvasContext.beginPath();
  108700. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  108701. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  108702. VirtualJoystick.vjCanvasContext.stroke();
  108703. VirtualJoystick.vjCanvasContext.closePath();
  108704. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  108705. }
  108706. else {
  108707. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  108708. VirtualJoystick.vjCanvasContext.beginPath();
  108709. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  108710. VirtualJoystick.vjCanvasContext.beginPath();
  108711. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  108712. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  108713. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  108714. VirtualJoystick.vjCanvasContext.stroke();
  108715. VirtualJoystick.vjCanvasContext.closePath();
  108716. touch.prevX = touch.x;
  108717. touch.prevY = touch.y;
  108718. }
  108719. });
  108720. }
  108721. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  108722. };
  108723. /**
  108724. * Release internal HTML canvas
  108725. */
  108726. VirtualJoystick.prototype.releaseCanvas = function () {
  108727. if (VirtualJoystick.vjCanvas) {
  108728. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  108729. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  108730. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  108731. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  108732. window.removeEventListener("resize", this._onResize);
  108733. document.body.removeChild(VirtualJoystick.vjCanvas);
  108734. VirtualJoystick.vjCanvas = null;
  108735. }
  108736. };
  108737. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  108738. VirtualJoystick._globalJoystickIndex = 0;
  108739. return VirtualJoystick;
  108740. }());
  108741. BABYLON.VirtualJoystick = VirtualJoystick;
  108742. })(BABYLON || (BABYLON = {}));
  108743. //# sourceMappingURL=virtualJoystick.js.map
  108744. var BABYLON;
  108745. (function (BABYLON) {
  108746. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  108747. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  108748. });
  108749. /**
  108750. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  108751. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  108752. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  108753. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  108754. */
  108755. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  108756. __extends(VirtualJoysticksCamera, _super);
  108757. /**
  108758. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  108759. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  108760. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  108761. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  108762. * @param name Define the name of the camera in the scene
  108763. * @param position Define the start position of the camera in the scene
  108764. * @param scene Define the scene the camera belongs to
  108765. */
  108766. function VirtualJoysticksCamera(name, position, scene) {
  108767. var _this = _super.call(this, name, position, scene) || this;
  108768. _this.inputs.addVirtualJoystick();
  108769. return _this;
  108770. }
  108771. /**
  108772. * Gets the current object class name.
  108773. * @return the class name
  108774. */
  108775. VirtualJoysticksCamera.prototype.getClassName = function () {
  108776. return "VirtualJoysticksCamera";
  108777. };
  108778. return VirtualJoysticksCamera;
  108779. }(BABYLON.FreeCamera));
  108780. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  108781. })(BABYLON || (BABYLON = {}));
  108782. //# sourceMappingURL=virtualJoysticksCamera.js.map
  108783. var BABYLON;
  108784. (function (BABYLON) {
  108785. /**
  108786. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  108787. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  108788. */
  108789. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  108790. function FreeCameraVirtualJoystickInput() {
  108791. }
  108792. /**
  108793. * Gets the left stick of the virtual joystick.
  108794. * @returns The virtual Joystick
  108795. */
  108796. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  108797. return this._leftjoystick;
  108798. };
  108799. /**
  108800. * Gets the right stick of the virtual joystick.
  108801. * @returns The virtual Joystick
  108802. */
  108803. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  108804. return this._rightjoystick;
  108805. };
  108806. /**
  108807. * Update the current camera state depending on the inputs that have been used this frame.
  108808. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  108809. */
  108810. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  108811. if (this._leftjoystick) {
  108812. var camera = this.camera;
  108813. var speed = camera._computeLocalCameraSpeed() * 50;
  108814. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  108815. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  108816. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  108817. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  108818. if (!this._leftjoystick.pressed) {
  108819. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  108820. }
  108821. if (!this._rightjoystick.pressed) {
  108822. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  108823. }
  108824. }
  108825. };
  108826. /**
  108827. * Attach the input controls to a specific dom element to get the input from.
  108828. * @param element Defines the element the controls should be listened from
  108829. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  108830. */
  108831. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  108832. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  108833. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  108834. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  108835. this._leftjoystick.setJoystickSensibility(0.15);
  108836. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  108837. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  108838. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  108839. this._rightjoystick.reverseUpDown = true;
  108840. this._rightjoystick.setJoystickSensibility(0.05);
  108841. this._rightjoystick.setJoystickColor("yellow");
  108842. };
  108843. /**
  108844. * Detach the current controls from the specified dom element.
  108845. * @param element Defines the element to stop listening the inputs from
  108846. */
  108847. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  108848. this._leftjoystick.releaseCanvas();
  108849. this._rightjoystick.releaseCanvas();
  108850. };
  108851. /**
  108852. * Gets the class name of the current intput.
  108853. * @returns the class name
  108854. */
  108855. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  108856. return "FreeCameraVirtualJoystickInput";
  108857. };
  108858. /**
  108859. * Get the friendly name associated with the input class.
  108860. * @returns the input friendly name
  108861. */
  108862. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  108863. return "virtualJoystick";
  108864. };
  108865. return FreeCameraVirtualJoystickInput;
  108866. }());
  108867. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  108868. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  108869. })(BABYLON || (BABYLON = {}));
  108870. //# sourceMappingURL=freeCameraVirtualJoystickInput.js.map
  108871. var BABYLON;
  108872. (function (BABYLON) {
  108873. /**
  108874. * Class used to specify simplification options
  108875. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  108876. */
  108877. var SimplificationSettings = /** @class */ (function () {
  108878. /**
  108879. * Creates a SimplificationSettings
  108880. * @param quality expected quality
  108881. * @param distance distance when this optimized version should be used
  108882. * @param optimizeMesh already optimized mesh
  108883. */
  108884. function SimplificationSettings(
  108885. /** expected quality */
  108886. quality,
  108887. /** distance when this optimized version should be used */
  108888. distance,
  108889. /** already optimized mesh */
  108890. optimizeMesh) {
  108891. this.quality = quality;
  108892. this.distance = distance;
  108893. this.optimizeMesh = optimizeMesh;
  108894. }
  108895. return SimplificationSettings;
  108896. }());
  108897. BABYLON.SimplificationSettings = SimplificationSettings;
  108898. /**
  108899. * Queue used to order the simplification tasks
  108900. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  108901. */
  108902. var SimplificationQueue = /** @class */ (function () {
  108903. /**
  108904. * Creates a new queue
  108905. */
  108906. function SimplificationQueue() {
  108907. this.running = false;
  108908. this._simplificationArray = [];
  108909. }
  108910. /**
  108911. * Adds a new simplification task
  108912. * @param task defines a task to add
  108913. */
  108914. SimplificationQueue.prototype.addTask = function (task) {
  108915. this._simplificationArray.push(task);
  108916. };
  108917. /**
  108918. * Execute next task
  108919. */
  108920. SimplificationQueue.prototype.executeNext = function () {
  108921. var task = this._simplificationArray.pop();
  108922. if (task) {
  108923. this.running = true;
  108924. this.runSimplification(task);
  108925. }
  108926. else {
  108927. this.running = false;
  108928. }
  108929. };
  108930. /**
  108931. * Execute a simplification task
  108932. * @param task defines the task to run
  108933. */
  108934. SimplificationQueue.prototype.runSimplification = function (task) {
  108935. var _this = this;
  108936. if (task.parallelProcessing) {
  108937. //parallel simplifier
  108938. task.settings.forEach(function (setting) {
  108939. var simplifier = _this.getSimplifier(task);
  108940. simplifier.simplify(setting, function (newMesh) {
  108941. task.mesh.addLODLevel(setting.distance, newMesh);
  108942. newMesh.isVisible = true;
  108943. //check if it is the last
  108944. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  108945. //all done, run the success callback.
  108946. task.successCallback();
  108947. }
  108948. _this.executeNext();
  108949. });
  108950. });
  108951. }
  108952. else {
  108953. //single simplifier.
  108954. var simplifier = this.getSimplifier(task);
  108955. var runDecimation = function (setting, callback) {
  108956. simplifier.simplify(setting, function (newMesh) {
  108957. task.mesh.addLODLevel(setting.distance, newMesh);
  108958. newMesh.isVisible = true;
  108959. //run the next quality level
  108960. callback();
  108961. });
  108962. };
  108963. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  108964. runDecimation(task.settings[loop.index], function () {
  108965. loop.executeNext();
  108966. });
  108967. }, function () {
  108968. //execution ended, run the success callback.
  108969. if (task.successCallback) {
  108970. task.successCallback();
  108971. }
  108972. _this.executeNext();
  108973. });
  108974. }
  108975. };
  108976. SimplificationQueue.prototype.getSimplifier = function (task) {
  108977. switch (task.simplificationType) {
  108978. case SimplificationType.QUADRATIC:
  108979. default:
  108980. return new QuadraticErrorSimplification(task.mesh);
  108981. }
  108982. };
  108983. return SimplificationQueue;
  108984. }());
  108985. BABYLON.SimplificationQueue = SimplificationQueue;
  108986. /**
  108987. * The implemented types of simplification
  108988. * At the moment only Quadratic Error Decimation is implemented
  108989. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  108990. */
  108991. var SimplificationType;
  108992. (function (SimplificationType) {
  108993. /** Quadratic error decimation */
  108994. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  108995. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  108996. var DecimationTriangle = /** @class */ (function () {
  108997. function DecimationTriangle(vertices) {
  108998. this.vertices = vertices;
  108999. this.error = new Array(4);
  109000. this.deleted = false;
  109001. this.isDirty = false;
  109002. this.deletePending = false;
  109003. this.borderFactor = 0;
  109004. }
  109005. return DecimationTriangle;
  109006. }());
  109007. var DecimationVertex = /** @class */ (function () {
  109008. function DecimationVertex(position, id) {
  109009. this.position = position;
  109010. this.id = id;
  109011. this.isBorder = true;
  109012. this.q = new QuadraticMatrix();
  109013. this.triangleCount = 0;
  109014. this.triangleStart = 0;
  109015. this.originalOffsets = [];
  109016. }
  109017. DecimationVertex.prototype.updatePosition = function (newPosition) {
  109018. this.position.copyFrom(newPosition);
  109019. };
  109020. return DecimationVertex;
  109021. }());
  109022. var QuadraticMatrix = /** @class */ (function () {
  109023. function QuadraticMatrix(data) {
  109024. this.data = new Array(10);
  109025. for (var i = 0; i < 10; ++i) {
  109026. if (data && data[i]) {
  109027. this.data[i] = data[i];
  109028. }
  109029. else {
  109030. this.data[i] = 0;
  109031. }
  109032. }
  109033. }
  109034. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  109035. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  109036. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  109037. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  109038. return det;
  109039. };
  109040. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  109041. for (var i = 0; i < 10; ++i) {
  109042. this.data[i] += matrix.data[i];
  109043. }
  109044. };
  109045. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  109046. for (var i = 0; i < 10; ++i) {
  109047. this.data[i] += data[i];
  109048. }
  109049. };
  109050. QuadraticMatrix.prototype.add = function (matrix) {
  109051. var m = new QuadraticMatrix();
  109052. for (var i = 0; i < 10; ++i) {
  109053. m.data[i] = this.data[i] + matrix.data[i];
  109054. }
  109055. return m;
  109056. };
  109057. QuadraticMatrix.FromData = function (a, b, c, d) {
  109058. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  109059. };
  109060. //returning an array to avoid garbage collection
  109061. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  109062. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  109063. };
  109064. return QuadraticMatrix;
  109065. }());
  109066. var Reference = /** @class */ (function () {
  109067. function Reference(vertexId, triangleId) {
  109068. this.vertexId = vertexId;
  109069. this.triangleId = triangleId;
  109070. }
  109071. return Reference;
  109072. }());
  109073. /**
  109074. * An implementation of the Quadratic Error simplification algorithm.
  109075. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  109076. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  109077. * @author RaananW
  109078. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  109079. */
  109080. var QuadraticErrorSimplification = /** @class */ (function () {
  109081. function QuadraticErrorSimplification(_mesh) {
  109082. this._mesh = _mesh;
  109083. this.syncIterations = 5000;
  109084. this.aggressiveness = 7;
  109085. this.decimationIterations = 100;
  109086. this.boundingBoxEpsilon = BABYLON.Epsilon;
  109087. }
  109088. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  109089. var _this = this;
  109090. this.initDecimatedMesh();
  109091. //iterating through the submeshes array, one after the other.
  109092. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  109093. _this.initWithMesh(loop.index, function () {
  109094. _this.runDecimation(settings, loop.index, function () {
  109095. loop.executeNext();
  109096. });
  109097. }, settings.optimizeMesh);
  109098. }, function () {
  109099. setTimeout(function () {
  109100. successCallback(_this._reconstructedMesh);
  109101. }, 0);
  109102. });
  109103. };
  109104. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  109105. var _this = this;
  109106. var targetCount = ~~(this.triangles.length * settings.quality);
  109107. var deletedTriangles = 0;
  109108. var triangleCount = this.triangles.length;
  109109. var iterationFunction = function (iteration, callback) {
  109110. setTimeout(function () {
  109111. if (iteration % 5 === 0) {
  109112. _this.updateMesh(iteration === 0);
  109113. }
  109114. for (var i = 0; i < _this.triangles.length; ++i) {
  109115. _this.triangles[i].isDirty = false;
  109116. }
  109117. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  109118. var trianglesIterator = function (i) {
  109119. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  109120. var t = _this.triangles[tIdx];
  109121. if (!t) {
  109122. return;
  109123. }
  109124. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  109125. return;
  109126. }
  109127. for (var j = 0; j < 3; ++j) {
  109128. if (t.error[j] < threshold) {
  109129. var deleted0 = [];
  109130. var deleted1 = [];
  109131. var v0 = t.vertices[j];
  109132. var v1 = t.vertices[(j + 1) % 3];
  109133. if (v0.isBorder || v1.isBorder) {
  109134. continue;
  109135. }
  109136. var p = BABYLON.Vector3.Zero();
  109137. var n = BABYLON.Vector3.Zero();
  109138. var uv = BABYLON.Vector2.Zero();
  109139. var color = new BABYLON.Color4(0, 0, 0, 1);
  109140. _this.calculateError(v0, v1, p, n, uv, color);
  109141. var delTr = new Array();
  109142. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr)) {
  109143. continue;
  109144. }
  109145. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr)) {
  109146. continue;
  109147. }
  109148. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0) {
  109149. continue;
  109150. }
  109151. var uniqueArray = new Array();
  109152. delTr.forEach(function (deletedT) {
  109153. if (uniqueArray.indexOf(deletedT) === -1) {
  109154. deletedT.deletePending = true;
  109155. uniqueArray.push(deletedT);
  109156. }
  109157. });
  109158. if (uniqueArray.length % 2 !== 0) {
  109159. continue;
  109160. }
  109161. v0.q = v1.q.add(v0.q);
  109162. v0.updatePosition(p);
  109163. var tStart = _this.references.length;
  109164. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  109165. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  109166. var tCount = _this.references.length - tStart;
  109167. if (tCount <= v0.triangleCount) {
  109168. if (tCount) {
  109169. for (var c = 0; c < tCount; c++) {
  109170. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  109171. }
  109172. }
  109173. }
  109174. else {
  109175. v0.triangleStart = tStart;
  109176. }
  109177. v0.triangleCount = tCount;
  109178. break;
  109179. }
  109180. }
  109181. };
  109182. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  109183. }, 0);
  109184. };
  109185. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  109186. if (triangleCount - deletedTriangles <= targetCount) {
  109187. loop.breakLoop();
  109188. }
  109189. else {
  109190. iterationFunction(loop.index, function () {
  109191. loop.executeNext();
  109192. });
  109193. }
  109194. }, function () {
  109195. setTimeout(function () {
  109196. //reconstruct this part of the mesh
  109197. _this.reconstructMesh(submeshIndex);
  109198. successCallback();
  109199. }, 0);
  109200. });
  109201. };
  109202. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  109203. var _this = this;
  109204. this.vertices = [];
  109205. this.triangles = [];
  109206. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  109207. var indices = this._mesh.getIndices();
  109208. var submesh = this._mesh.subMeshes[submeshIndex];
  109209. var findInVertices = function (positionToSearch) {
  109210. if (optimizeMesh) {
  109211. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  109212. if (_this.vertices[ii].position.equals(positionToSearch)) {
  109213. return _this.vertices[ii];
  109214. }
  109215. }
  109216. }
  109217. return null;
  109218. };
  109219. var vertexReferences = [];
  109220. var vertexInit = function (i) {
  109221. if (!positionData) {
  109222. return;
  109223. }
  109224. var offset = i + submesh.verticesStart;
  109225. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  109226. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  109227. vertex.originalOffsets.push(offset);
  109228. if (vertex.id === _this.vertices.length) {
  109229. _this.vertices.push(vertex);
  109230. }
  109231. vertexReferences.push(vertex.id);
  109232. };
  109233. //var totalVertices = mesh.getTotalVertices();
  109234. var totalVertices = submesh.verticesCount;
  109235. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  109236. var indicesInit = function (i) {
  109237. if (!indices) {
  109238. return;
  109239. }
  109240. var offset = (submesh.indexStart / 3) + i;
  109241. var pos = (offset * 3);
  109242. var i0 = indices[pos + 0];
  109243. var i1 = indices[pos + 1];
  109244. var i2 = indices[pos + 2];
  109245. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  109246. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  109247. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  109248. var triangle = new DecimationTriangle([v0, v1, v2]);
  109249. triangle.originalOffset = pos;
  109250. _this.triangles.push(triangle);
  109251. };
  109252. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  109253. _this.init(callback);
  109254. });
  109255. });
  109256. };
  109257. QuadraticErrorSimplification.prototype.init = function (callback) {
  109258. var _this = this;
  109259. var triangleInit1 = function (i) {
  109260. var t = _this.triangles[i];
  109261. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  109262. for (var j = 0; j < 3; j++) {
  109263. 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))));
  109264. }
  109265. };
  109266. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  109267. var triangleInit2 = function (i) {
  109268. var t = _this.triangles[i];
  109269. for (var j = 0; j < 3; ++j) {
  109270. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  109271. }
  109272. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  109273. };
  109274. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  109275. callback();
  109276. });
  109277. });
  109278. };
  109279. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  109280. var newTriangles = [];
  109281. var i;
  109282. for (i = 0; i < this.vertices.length; ++i) {
  109283. this.vertices[i].triangleCount = 0;
  109284. }
  109285. var t;
  109286. var j;
  109287. for (i = 0; i < this.triangles.length; ++i) {
  109288. if (!this.triangles[i].deleted) {
  109289. t = this.triangles[i];
  109290. for (j = 0; j < 3; ++j) {
  109291. t.vertices[j].triangleCount = 1;
  109292. }
  109293. newTriangles.push(t);
  109294. }
  109295. }
  109296. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  109297. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  109298. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  109299. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  109300. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  109301. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  109302. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  109303. var vertexCount = 0;
  109304. for (i = 0; i < this.vertices.length; ++i) {
  109305. var vertex = this.vertices[i];
  109306. vertex.id = vertexCount;
  109307. if (vertex.triangleCount) {
  109308. vertex.originalOffsets.forEach(function (originalOffset) {
  109309. if (!normalData) {
  109310. return;
  109311. }
  109312. newPositionData.push(vertex.position.x);
  109313. newPositionData.push(vertex.position.y);
  109314. newPositionData.push(vertex.position.z);
  109315. newNormalData.push(normalData[originalOffset * 3]);
  109316. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  109317. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  109318. if (uvs && uvs.length) {
  109319. newUVsData.push(uvs[(originalOffset * 2)]);
  109320. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  109321. }
  109322. else if (colorsData && colorsData.length) {
  109323. newColorsData.push(colorsData[(originalOffset * 4)]);
  109324. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  109325. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  109326. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  109327. }
  109328. ++vertexCount;
  109329. });
  109330. }
  109331. }
  109332. var startingIndex = this._reconstructedMesh.getTotalIndices();
  109333. var startingVertex = this._reconstructedMesh.getTotalVertices();
  109334. var submeshesArray = this._reconstructedMesh.subMeshes;
  109335. this._reconstructedMesh.subMeshes = [];
  109336. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  109337. var originalIndices = this._mesh.getIndices();
  109338. for (i = 0; i < newTriangles.length; ++i) {
  109339. t = newTriangles[i]; //now get the new referencing point for each vertex
  109340. [0, 1, 2].forEach(function (idx) {
  109341. var id = originalIndices[t.originalOffset + idx];
  109342. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  109343. if (offset < 0) {
  109344. offset = 0;
  109345. }
  109346. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  109347. });
  109348. }
  109349. //overwriting the old vertex buffers and indices.
  109350. this._reconstructedMesh.setIndices(newIndicesArray);
  109351. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  109352. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  109353. if (newUVsData.length > 0) {
  109354. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  109355. }
  109356. if (newColorsData.length > 0) {
  109357. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  109358. }
  109359. //create submesh
  109360. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  109361. if (submeshIndex > 0) {
  109362. this._reconstructedMesh.subMeshes = [];
  109363. submeshesArray.forEach(function (submesh) {
  109364. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  109365. });
  109366. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  109367. }
  109368. };
  109369. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  109370. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  109371. this._reconstructedMesh.material = this._mesh.material;
  109372. this._reconstructedMesh.parent = this._mesh.parent;
  109373. this._reconstructedMesh.isVisible = false;
  109374. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  109375. };
  109376. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  109377. for (var i = 0; i < vertex1.triangleCount; ++i) {
  109378. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  109379. if (t.deleted) {
  109380. continue;
  109381. }
  109382. var s = this.references[vertex1.triangleStart + i].vertexId;
  109383. var v1 = t.vertices[(s + 1) % 3];
  109384. var v2 = t.vertices[(s + 2) % 3];
  109385. if ((v1 === vertex2 || v2 === vertex2)) {
  109386. deletedArray[i] = true;
  109387. delTr.push(t);
  109388. continue;
  109389. }
  109390. var d1 = v1.position.subtract(point);
  109391. d1 = d1.normalize();
  109392. var d2 = v2.position.subtract(point);
  109393. d2 = d2.normalize();
  109394. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999) {
  109395. return true;
  109396. }
  109397. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  109398. deletedArray[i] = false;
  109399. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2) {
  109400. return true;
  109401. }
  109402. }
  109403. return false;
  109404. };
  109405. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  109406. var newDeleted = deletedTriangles;
  109407. for (var i = 0; i < vertex.triangleCount; ++i) {
  109408. var ref = this.references[vertex.triangleStart + i];
  109409. var t = this.triangles[ref.triangleId];
  109410. if (t.deleted) {
  109411. continue;
  109412. }
  109413. if (deletedArray[i] && t.deletePending) {
  109414. t.deleted = true;
  109415. newDeleted++;
  109416. continue;
  109417. }
  109418. t.vertices[ref.vertexId] = origVertex;
  109419. t.isDirty = true;
  109420. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  109421. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  109422. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  109423. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  109424. this.references.push(ref);
  109425. }
  109426. return newDeleted;
  109427. };
  109428. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  109429. for (var i = 0; i < this.vertices.length; ++i) {
  109430. var vCount = [];
  109431. var vId = [];
  109432. var v = this.vertices[i];
  109433. var j;
  109434. for (j = 0; j < v.triangleCount; ++j) {
  109435. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  109436. for (var ii = 0; ii < 3; ii++) {
  109437. var ofs = 0;
  109438. var vv = triangle.vertices[ii];
  109439. while (ofs < vCount.length) {
  109440. if (vId[ofs] === vv.id) {
  109441. break;
  109442. }
  109443. ++ofs;
  109444. }
  109445. if (ofs === vCount.length) {
  109446. vCount.push(1);
  109447. vId.push(vv.id);
  109448. }
  109449. else {
  109450. vCount[ofs]++;
  109451. }
  109452. }
  109453. }
  109454. for (j = 0; j < vCount.length; ++j) {
  109455. if (vCount[j] === 1) {
  109456. this.vertices[vId[j]].isBorder = true;
  109457. }
  109458. else {
  109459. this.vertices[vId[j]].isBorder = false;
  109460. }
  109461. }
  109462. }
  109463. };
  109464. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  109465. if (identifyBorders === void 0) { identifyBorders = false; }
  109466. var i;
  109467. if (!identifyBorders) {
  109468. var newTrianglesVector = [];
  109469. for (i = 0; i < this.triangles.length; ++i) {
  109470. if (!this.triangles[i].deleted) {
  109471. newTrianglesVector.push(this.triangles[i]);
  109472. }
  109473. }
  109474. this.triangles = newTrianglesVector;
  109475. }
  109476. for (i = 0; i < this.vertices.length; ++i) {
  109477. this.vertices[i].triangleCount = 0;
  109478. this.vertices[i].triangleStart = 0;
  109479. }
  109480. var t;
  109481. var j;
  109482. var v;
  109483. for (i = 0; i < this.triangles.length; ++i) {
  109484. t = this.triangles[i];
  109485. for (j = 0; j < 3; ++j) {
  109486. v = t.vertices[j];
  109487. v.triangleCount++;
  109488. }
  109489. }
  109490. var tStart = 0;
  109491. for (i = 0; i < this.vertices.length; ++i) {
  109492. this.vertices[i].triangleStart = tStart;
  109493. tStart += this.vertices[i].triangleCount;
  109494. this.vertices[i].triangleCount = 0;
  109495. }
  109496. var newReferences = new Array(this.triangles.length * 3);
  109497. for (i = 0; i < this.triangles.length; ++i) {
  109498. t = this.triangles[i];
  109499. for (j = 0; j < 3; ++j) {
  109500. v = t.vertices[j];
  109501. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  109502. v.triangleCount++;
  109503. }
  109504. }
  109505. this.references = newReferences;
  109506. if (identifyBorders) {
  109507. this.identifyBorder();
  109508. }
  109509. };
  109510. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  109511. var x = point.x;
  109512. var y = point.y;
  109513. var z = point.z;
  109514. 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
  109515. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  109516. };
  109517. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  109518. var q = vertex1.q.add(vertex2.q);
  109519. var border = vertex1.isBorder && vertex2.isBorder;
  109520. var error = 0;
  109521. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  109522. if (qDet !== 0 && !border) {
  109523. if (!pointResult) {
  109524. pointResult = BABYLON.Vector3.Zero();
  109525. }
  109526. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  109527. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  109528. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  109529. error = this.vertexError(q, pointResult);
  109530. }
  109531. else {
  109532. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  109533. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  109534. var error1 = this.vertexError(q, vertex1.position);
  109535. var error2 = this.vertexError(q, vertex2.position);
  109536. var error3 = this.vertexError(q, p3);
  109537. error = Math.min(error1, error2, error3);
  109538. if (error === error1) {
  109539. if (pointResult) {
  109540. pointResult.copyFrom(vertex1.position);
  109541. }
  109542. }
  109543. else if (error === error2) {
  109544. if (pointResult) {
  109545. pointResult.copyFrom(vertex2.position);
  109546. }
  109547. }
  109548. else {
  109549. if (pointResult) {
  109550. pointResult.copyFrom(p3);
  109551. }
  109552. }
  109553. }
  109554. return error;
  109555. };
  109556. return QuadraticErrorSimplification;
  109557. }());
  109558. })(BABYLON || (BABYLON = {}));
  109559. //# sourceMappingURL=meshSimplification.js.map
  109560. var BABYLON;
  109561. (function (BABYLON) {
  109562. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  109563. get: function () {
  109564. if (!this._simplificationQueue) {
  109565. this._simplificationQueue = new BABYLON.SimplificationQueue();
  109566. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  109567. if (!component) {
  109568. component = new SimplicationQueueSceneComponent(this);
  109569. this._addComponent(component);
  109570. }
  109571. }
  109572. return this._simplificationQueue;
  109573. },
  109574. set: function (value) {
  109575. this._simplificationQueue = value;
  109576. },
  109577. enumerable: true,
  109578. configurable: true
  109579. });
  109580. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  109581. if (parallelProcessing === void 0) { parallelProcessing = true; }
  109582. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  109583. this.getScene().simplificationQueue.addTask({
  109584. settings: settings,
  109585. parallelProcessing: parallelProcessing,
  109586. mesh: this,
  109587. simplificationType: simplificationType,
  109588. successCallback: successCallback
  109589. });
  109590. return this;
  109591. };
  109592. /**
  109593. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  109594. * created in a scene
  109595. */
  109596. var SimplicationQueueSceneComponent = /** @class */ (function () {
  109597. /**
  109598. * Creates a new instance of the component for the given scene
  109599. * @param scene Defines the scene to register the component in
  109600. */
  109601. function SimplicationQueueSceneComponent(scene) {
  109602. /**
  109603. * The component name helpfull to identify the component in the list of scene components.
  109604. */
  109605. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  109606. this.scene = scene;
  109607. }
  109608. /**
  109609. * Registers the component in a given scene
  109610. */
  109611. SimplicationQueueSceneComponent.prototype.register = function () {
  109612. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  109613. };
  109614. /**
  109615. * Rebuilds the elements related to this component in case of
  109616. * context lost for instance.
  109617. */
  109618. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  109619. // Nothing to do for this component
  109620. };
  109621. /**
  109622. * Disposes the component and the associated ressources
  109623. */
  109624. SimplicationQueueSceneComponent.prototype.dispose = function () {
  109625. // Nothing to do for this component
  109626. };
  109627. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  109628. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  109629. this.scene._simplificationQueue.executeNext();
  109630. }
  109631. };
  109632. return SimplicationQueueSceneComponent;
  109633. }());
  109634. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  109635. })(BABYLON || (BABYLON = {}));
  109636. //# sourceMappingURL=meshSimplificationSceneComponent.js.map
  109637. var BABYLON;
  109638. (function (BABYLON) {
  109639. /**
  109640. * Class used to represent a specific level of detail of a mesh
  109641. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  109642. */
  109643. var MeshLODLevel = /** @class */ (function () {
  109644. /**
  109645. * Creates a new LOD level
  109646. * @param distance defines the distance where this level should star being displayed
  109647. * @param mesh defines the mesh to use to render this level
  109648. */
  109649. function MeshLODLevel(
  109650. /** Defines the distance where this level should star being displayed */
  109651. distance,
  109652. /** Defines the mesh to use to render this level */
  109653. mesh) {
  109654. this.distance = distance;
  109655. this.mesh = mesh;
  109656. }
  109657. return MeshLODLevel;
  109658. }());
  109659. BABYLON.MeshLODLevel = MeshLODLevel;
  109660. })(BABYLON || (BABYLON = {}));
  109661. //# sourceMappingURL=meshLODLevel.js.map
  109662. var BABYLON;
  109663. (function (BABYLON) {
  109664. /**
  109665. * Defines the root class used to create scene optimization to use with SceneOptimizer
  109666. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109667. */
  109668. var SceneOptimization = /** @class */ (function () {
  109669. /**
  109670. * Creates the SceneOptimization object
  109671. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  109672. * @param desc defines the description associated with the optimization
  109673. */
  109674. function SceneOptimization(
  109675. /**
  109676. * Defines the priority of this optimization (0 by default which means first in the list)
  109677. */
  109678. priority) {
  109679. if (priority === void 0) { priority = 0; }
  109680. this.priority = priority;
  109681. }
  109682. /**
  109683. * Gets a string describing the action executed by the current optimization
  109684. * @returns description string
  109685. */
  109686. SceneOptimization.prototype.getDescription = function () {
  109687. return "";
  109688. };
  109689. /**
  109690. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109691. * @param scene defines the current scene where to apply this optimization
  109692. * @param optimizer defines the current optimizer
  109693. * @returns true if everything that can be done was applied
  109694. */
  109695. SceneOptimization.prototype.apply = function (scene, optimizer) {
  109696. return true;
  109697. };
  109698. return SceneOptimization;
  109699. }());
  109700. BABYLON.SceneOptimization = SceneOptimization;
  109701. /**
  109702. * Defines an optimization used to reduce the size of render target textures
  109703. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109704. */
  109705. var TextureOptimization = /** @class */ (function (_super) {
  109706. __extends(TextureOptimization, _super);
  109707. /**
  109708. * Creates the TextureOptimization object
  109709. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  109710. * @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
  109711. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  109712. */
  109713. function TextureOptimization(
  109714. /**
  109715. * Defines the priority of this optimization (0 by default which means first in the list)
  109716. */
  109717. priority,
  109718. /**
  109719. * 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
  109720. */
  109721. maximumSize,
  109722. /**
  109723. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  109724. */
  109725. step) {
  109726. if (priority === void 0) { priority = 0; }
  109727. if (maximumSize === void 0) { maximumSize = 1024; }
  109728. if (step === void 0) { step = 0.5; }
  109729. var _this = _super.call(this, priority) || this;
  109730. _this.priority = priority;
  109731. _this.maximumSize = maximumSize;
  109732. _this.step = step;
  109733. return _this;
  109734. }
  109735. /**
  109736. * Gets a string describing the action executed by the current optimization
  109737. * @returns description string
  109738. */
  109739. TextureOptimization.prototype.getDescription = function () {
  109740. return "Reducing render target texture size to " + this.maximumSize;
  109741. };
  109742. /**
  109743. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109744. * @param scene defines the current scene where to apply this optimization
  109745. * @param optimizer defines the current optimizer
  109746. * @returns true if everything that can be done was applied
  109747. */
  109748. TextureOptimization.prototype.apply = function (scene, optimizer) {
  109749. var allDone = true;
  109750. for (var index = 0; index < scene.textures.length; index++) {
  109751. var texture = scene.textures[index];
  109752. if (!texture.canRescale || texture.getContext) {
  109753. continue;
  109754. }
  109755. var currentSize = texture.getSize();
  109756. var maxDimension = Math.max(currentSize.width, currentSize.height);
  109757. if (maxDimension > this.maximumSize) {
  109758. texture.scale(this.step);
  109759. allDone = false;
  109760. }
  109761. }
  109762. return allDone;
  109763. };
  109764. return TextureOptimization;
  109765. }(SceneOptimization));
  109766. BABYLON.TextureOptimization = TextureOptimization;
  109767. /**
  109768. * Defines an optimization used to increase or decrease the rendering resolution
  109769. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109770. */
  109771. var HardwareScalingOptimization = /** @class */ (function (_super) {
  109772. __extends(HardwareScalingOptimization, _super);
  109773. /**
  109774. * Creates the HardwareScalingOptimization object
  109775. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  109776. * @param maximumScale defines the maximum scale to use (2 by default)
  109777. * @param step defines the step to use between two passes (0.5 by default)
  109778. */
  109779. function HardwareScalingOptimization(
  109780. /**
  109781. * Defines the priority of this optimization (0 by default which means first in the list)
  109782. */
  109783. priority,
  109784. /**
  109785. * Defines the maximum scale to use (2 by default)
  109786. */
  109787. maximumScale,
  109788. /**
  109789. * Defines the step to use between two passes (0.5 by default)
  109790. */
  109791. step) {
  109792. if (priority === void 0) { priority = 0; }
  109793. if (maximumScale === void 0) { maximumScale = 2; }
  109794. if (step === void 0) { step = 0.25; }
  109795. var _this = _super.call(this, priority) || this;
  109796. _this.priority = priority;
  109797. _this.maximumScale = maximumScale;
  109798. _this.step = step;
  109799. _this._currentScale = -1;
  109800. _this._directionOffset = 1;
  109801. return _this;
  109802. }
  109803. /**
  109804. * Gets a string describing the action executed by the current optimization
  109805. * @return description string
  109806. */
  109807. HardwareScalingOptimization.prototype.getDescription = function () {
  109808. return "Setting hardware scaling level to " + this._currentScale;
  109809. };
  109810. /**
  109811. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109812. * @param scene defines the current scene where to apply this optimization
  109813. * @param optimizer defines the current optimizer
  109814. * @returns true if everything that can be done was applied
  109815. */
  109816. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  109817. if (this._currentScale === -1) {
  109818. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  109819. if (this._currentScale > this.maximumScale) {
  109820. this._directionOffset = -1;
  109821. }
  109822. }
  109823. this._currentScale += this._directionOffset * this.step;
  109824. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  109825. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  109826. };
  109827. return HardwareScalingOptimization;
  109828. }(SceneOptimization));
  109829. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  109830. /**
  109831. * Defines an optimization used to remove shadows
  109832. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109833. */
  109834. var ShadowsOptimization = /** @class */ (function (_super) {
  109835. __extends(ShadowsOptimization, _super);
  109836. function ShadowsOptimization() {
  109837. return _super !== null && _super.apply(this, arguments) || this;
  109838. }
  109839. /**
  109840. * Gets a string describing the action executed by the current optimization
  109841. * @return description string
  109842. */
  109843. ShadowsOptimization.prototype.getDescription = function () {
  109844. return "Turning shadows on/off";
  109845. };
  109846. /**
  109847. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109848. * @param scene defines the current scene where to apply this optimization
  109849. * @param optimizer defines the current optimizer
  109850. * @returns true if everything that can be done was applied
  109851. */
  109852. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  109853. scene.shadowsEnabled = optimizer.isInImprovementMode;
  109854. return true;
  109855. };
  109856. return ShadowsOptimization;
  109857. }(SceneOptimization));
  109858. BABYLON.ShadowsOptimization = ShadowsOptimization;
  109859. /**
  109860. * Defines an optimization used to turn post-processes off
  109861. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109862. */
  109863. var PostProcessesOptimization = /** @class */ (function (_super) {
  109864. __extends(PostProcessesOptimization, _super);
  109865. function PostProcessesOptimization() {
  109866. return _super !== null && _super.apply(this, arguments) || this;
  109867. }
  109868. /**
  109869. * Gets a string describing the action executed by the current optimization
  109870. * @return description string
  109871. */
  109872. PostProcessesOptimization.prototype.getDescription = function () {
  109873. return "Turning post-processes on/off";
  109874. };
  109875. /**
  109876. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109877. * @param scene defines the current scene where to apply this optimization
  109878. * @param optimizer defines the current optimizer
  109879. * @returns true if everything that can be done was applied
  109880. */
  109881. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  109882. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  109883. return true;
  109884. };
  109885. return PostProcessesOptimization;
  109886. }(SceneOptimization));
  109887. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  109888. /**
  109889. * Defines an optimization used to turn lens flares off
  109890. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109891. */
  109892. var LensFlaresOptimization = /** @class */ (function (_super) {
  109893. __extends(LensFlaresOptimization, _super);
  109894. function LensFlaresOptimization() {
  109895. return _super !== null && _super.apply(this, arguments) || this;
  109896. }
  109897. /**
  109898. * Gets a string describing the action executed by the current optimization
  109899. * @return description string
  109900. */
  109901. LensFlaresOptimization.prototype.getDescription = function () {
  109902. return "Turning lens flares on/off";
  109903. };
  109904. /**
  109905. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109906. * @param scene defines the current scene where to apply this optimization
  109907. * @param optimizer defines the current optimizer
  109908. * @returns true if everything that can be done was applied
  109909. */
  109910. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  109911. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  109912. return true;
  109913. };
  109914. return LensFlaresOptimization;
  109915. }(SceneOptimization));
  109916. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  109917. /**
  109918. * Defines an optimization based on user defined callback.
  109919. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109920. */
  109921. var CustomOptimization = /** @class */ (function (_super) {
  109922. __extends(CustomOptimization, _super);
  109923. function CustomOptimization() {
  109924. return _super !== null && _super.apply(this, arguments) || this;
  109925. }
  109926. /**
  109927. * Gets a string describing the action executed by the current optimization
  109928. * @returns description string
  109929. */
  109930. CustomOptimization.prototype.getDescription = function () {
  109931. if (this.onGetDescription) {
  109932. return this.onGetDescription();
  109933. }
  109934. return "Running user defined callback";
  109935. };
  109936. /**
  109937. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109938. * @param scene defines the current scene where to apply this optimization
  109939. * @param optimizer defines the current optimizer
  109940. * @returns true if everything that can be done was applied
  109941. */
  109942. CustomOptimization.prototype.apply = function (scene, optimizer) {
  109943. if (this.onApply) {
  109944. return this.onApply(scene, optimizer);
  109945. }
  109946. return true;
  109947. };
  109948. return CustomOptimization;
  109949. }(SceneOptimization));
  109950. BABYLON.CustomOptimization = CustomOptimization;
  109951. /**
  109952. * Defines an optimization used to turn particles off
  109953. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109954. */
  109955. var ParticlesOptimization = /** @class */ (function (_super) {
  109956. __extends(ParticlesOptimization, _super);
  109957. function ParticlesOptimization() {
  109958. return _super !== null && _super.apply(this, arguments) || this;
  109959. }
  109960. /**
  109961. * Gets a string describing the action executed by the current optimization
  109962. * @return description string
  109963. */
  109964. ParticlesOptimization.prototype.getDescription = function () {
  109965. return "Turning particles on/off";
  109966. };
  109967. /**
  109968. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109969. * @param scene defines the current scene where to apply this optimization
  109970. * @param optimizer defines the current optimizer
  109971. * @returns true if everything that can be done was applied
  109972. */
  109973. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  109974. scene.particlesEnabled = optimizer.isInImprovementMode;
  109975. return true;
  109976. };
  109977. return ParticlesOptimization;
  109978. }(SceneOptimization));
  109979. BABYLON.ParticlesOptimization = ParticlesOptimization;
  109980. /**
  109981. * Defines an optimization used to turn render targets off
  109982. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  109983. */
  109984. var RenderTargetsOptimization = /** @class */ (function (_super) {
  109985. __extends(RenderTargetsOptimization, _super);
  109986. function RenderTargetsOptimization() {
  109987. return _super !== null && _super.apply(this, arguments) || this;
  109988. }
  109989. /**
  109990. * Gets a string describing the action executed by the current optimization
  109991. * @return description string
  109992. */
  109993. RenderTargetsOptimization.prototype.getDescription = function () {
  109994. return "Turning render targets off";
  109995. };
  109996. /**
  109997. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  109998. * @param scene defines the current scene where to apply this optimization
  109999. * @param optimizer defines the current optimizer
  110000. * @returns true if everything that can be done was applied
  110001. */
  110002. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  110003. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  110004. return true;
  110005. };
  110006. return RenderTargetsOptimization;
  110007. }(SceneOptimization));
  110008. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  110009. /**
  110010. * Defines an optimization used to merge meshes with compatible materials
  110011. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  110012. */
  110013. var MergeMeshesOptimization = /** @class */ (function (_super) {
  110014. __extends(MergeMeshesOptimization, _super);
  110015. function MergeMeshesOptimization() {
  110016. var _this = _super !== null && _super.apply(this, arguments) || this;
  110017. _this._canBeMerged = function (abstractMesh) {
  110018. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  110019. return false;
  110020. }
  110021. var mesh = abstractMesh;
  110022. if (mesh.isDisposed()) {
  110023. return false;
  110024. }
  110025. if (!mesh.isVisible || !mesh.isEnabled()) {
  110026. return false;
  110027. }
  110028. if (mesh.instances.length > 0) {
  110029. return false;
  110030. }
  110031. if (mesh.skeleton || mesh.hasLODLevels) {
  110032. return false;
  110033. }
  110034. return true;
  110035. };
  110036. return _this;
  110037. }
  110038. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  110039. /**
  110040. * Gets or sets a boolean which defines if optimization octree has to be updated
  110041. */
  110042. get: function () {
  110043. return MergeMeshesOptimization._UpdateSelectionTree;
  110044. },
  110045. /**
  110046. * Gets or sets a boolean which defines if optimization octree has to be updated
  110047. */
  110048. set: function (value) {
  110049. MergeMeshesOptimization._UpdateSelectionTree = value;
  110050. },
  110051. enumerable: true,
  110052. configurable: true
  110053. });
  110054. /**
  110055. * Gets a string describing the action executed by the current optimization
  110056. * @return description string
  110057. */
  110058. MergeMeshesOptimization.prototype.getDescription = function () {
  110059. return "Merging similar meshes together";
  110060. };
  110061. /**
  110062. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  110063. * @param scene defines the current scene where to apply this optimization
  110064. * @param optimizer defines the current optimizer
  110065. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  110066. * @returns true if everything that can be done was applied
  110067. */
  110068. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  110069. var globalPool = scene.meshes.slice(0);
  110070. var globalLength = globalPool.length;
  110071. for (var index = 0; index < globalLength; index++) {
  110072. var currentPool = new Array();
  110073. var current = globalPool[index];
  110074. // Checks
  110075. if (!this._canBeMerged(current)) {
  110076. continue;
  110077. }
  110078. currentPool.push(current);
  110079. // Find compatible meshes
  110080. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  110081. var otherMesh = globalPool[subIndex];
  110082. if (!this._canBeMerged(otherMesh)) {
  110083. continue;
  110084. }
  110085. if (otherMesh.material !== current.material) {
  110086. continue;
  110087. }
  110088. if (otherMesh.checkCollisions !== current.checkCollisions) {
  110089. continue;
  110090. }
  110091. currentPool.push(otherMesh);
  110092. globalLength--;
  110093. globalPool.splice(subIndex, 1);
  110094. subIndex--;
  110095. }
  110096. if (currentPool.length < 2) {
  110097. continue;
  110098. }
  110099. // Merge meshes
  110100. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  110101. }
  110102. // Call the octree system optimization if it is defined.
  110103. var sceneAsAny = scene;
  110104. if (sceneAsAny.createOrUpdateSelectionOctree) {
  110105. if (updateSelectionTree != undefined) {
  110106. if (updateSelectionTree) {
  110107. sceneAsAny.createOrUpdateSelectionOctree();
  110108. }
  110109. }
  110110. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  110111. sceneAsAny.createOrUpdateSelectionOctree();
  110112. }
  110113. }
  110114. return true;
  110115. };
  110116. MergeMeshesOptimization._UpdateSelectionTree = false;
  110117. return MergeMeshesOptimization;
  110118. }(SceneOptimization));
  110119. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  110120. /**
  110121. * Defines a list of options used by SceneOptimizer
  110122. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  110123. */
  110124. var SceneOptimizerOptions = /** @class */ (function () {
  110125. /**
  110126. * Creates a new list of options used by SceneOptimizer
  110127. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  110128. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  110129. */
  110130. function SceneOptimizerOptions(
  110131. /**
  110132. * Defines the target frame rate to reach (60 by default)
  110133. */
  110134. targetFrameRate,
  110135. /**
  110136. * Defines the interval between two checkes (2000ms by default)
  110137. */
  110138. trackerDuration) {
  110139. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  110140. if (trackerDuration === void 0) { trackerDuration = 2000; }
  110141. this.targetFrameRate = targetFrameRate;
  110142. this.trackerDuration = trackerDuration;
  110143. /**
  110144. * Gets the list of optimizations to apply
  110145. */
  110146. this.optimizations = new Array();
  110147. }
  110148. /**
  110149. * Add a new optimization
  110150. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  110151. * @returns the current SceneOptimizerOptions
  110152. */
  110153. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  110154. this.optimizations.push(optimization);
  110155. return this;
  110156. };
  110157. /**
  110158. * Add a new custom optimization
  110159. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  110160. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  110161. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  110162. * @returns the current SceneOptimizerOptions
  110163. */
  110164. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  110165. if (priority === void 0) { priority = 0; }
  110166. var optimization = new CustomOptimization(priority);
  110167. optimization.onApply = onApply;
  110168. optimization.onGetDescription = onGetDescription;
  110169. this.optimizations.push(optimization);
  110170. return this;
  110171. };
  110172. /**
  110173. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  110174. * @param targetFrameRate defines the target frame rate (60 by default)
  110175. * @returns a SceneOptimizerOptions object
  110176. */
  110177. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  110178. var result = new SceneOptimizerOptions(targetFrameRate);
  110179. var priority = 0;
  110180. result.addOptimization(new MergeMeshesOptimization(priority));
  110181. result.addOptimization(new ShadowsOptimization(priority));
  110182. result.addOptimization(new LensFlaresOptimization(priority));
  110183. // Next priority
  110184. priority++;
  110185. result.addOptimization(new PostProcessesOptimization(priority));
  110186. result.addOptimization(new ParticlesOptimization(priority));
  110187. // Next priority
  110188. priority++;
  110189. result.addOptimization(new TextureOptimization(priority, 1024));
  110190. return result;
  110191. };
  110192. /**
  110193. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  110194. * @param targetFrameRate defines the target frame rate (60 by default)
  110195. * @returns a SceneOptimizerOptions object
  110196. */
  110197. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  110198. var result = new SceneOptimizerOptions(targetFrameRate);
  110199. var priority = 0;
  110200. result.addOptimization(new MergeMeshesOptimization(priority));
  110201. result.addOptimization(new ShadowsOptimization(priority));
  110202. result.addOptimization(new LensFlaresOptimization(priority));
  110203. // Next priority
  110204. priority++;
  110205. result.addOptimization(new PostProcessesOptimization(priority));
  110206. result.addOptimization(new ParticlesOptimization(priority));
  110207. // Next priority
  110208. priority++;
  110209. result.addOptimization(new TextureOptimization(priority, 512));
  110210. // Next priority
  110211. priority++;
  110212. result.addOptimization(new RenderTargetsOptimization(priority));
  110213. // Next priority
  110214. priority++;
  110215. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  110216. return result;
  110217. };
  110218. /**
  110219. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  110220. * @param targetFrameRate defines the target frame rate (60 by default)
  110221. * @returns a SceneOptimizerOptions object
  110222. */
  110223. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  110224. var result = new SceneOptimizerOptions(targetFrameRate);
  110225. var priority = 0;
  110226. result.addOptimization(new MergeMeshesOptimization(priority));
  110227. result.addOptimization(new ShadowsOptimization(priority));
  110228. result.addOptimization(new LensFlaresOptimization(priority));
  110229. // Next priority
  110230. priority++;
  110231. result.addOptimization(new PostProcessesOptimization(priority));
  110232. result.addOptimization(new ParticlesOptimization(priority));
  110233. // Next priority
  110234. priority++;
  110235. result.addOptimization(new TextureOptimization(priority, 256));
  110236. // Next priority
  110237. priority++;
  110238. result.addOptimization(new RenderTargetsOptimization(priority));
  110239. // Next priority
  110240. priority++;
  110241. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  110242. return result;
  110243. };
  110244. return SceneOptimizerOptions;
  110245. }());
  110246. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  110247. /**
  110248. * Class used to run optimizations in order to reach a target frame rate
  110249. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  110250. */
  110251. var SceneOptimizer = /** @class */ (function () {
  110252. /**
  110253. * Creates a new SceneOptimizer
  110254. * @param scene defines the scene to work on
  110255. * @param options defines the options to use with the SceneOptimizer
  110256. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  110257. * @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)
  110258. */
  110259. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  110260. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  110261. if (improvementMode === void 0) { improvementMode = false; }
  110262. var _this = this;
  110263. this._isRunning = false;
  110264. this._currentPriorityLevel = 0;
  110265. this._targetFrameRate = 60;
  110266. this._trackerDuration = 2000;
  110267. this._currentFrameRate = 0;
  110268. this._improvementMode = false;
  110269. /**
  110270. * Defines an observable called when the optimizer reaches the target frame rate
  110271. */
  110272. this.onSuccessObservable = new BABYLON.Observable();
  110273. /**
  110274. * Defines an observable called when the optimizer enables an optimization
  110275. */
  110276. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  110277. /**
  110278. * Defines an observable called when the optimizer is not able to reach the target frame rate
  110279. */
  110280. this.onFailureObservable = new BABYLON.Observable();
  110281. if (!options) {
  110282. this._options = new SceneOptimizerOptions();
  110283. }
  110284. else {
  110285. this._options = options;
  110286. }
  110287. if (this._options.targetFrameRate) {
  110288. this._targetFrameRate = this._options.targetFrameRate;
  110289. }
  110290. if (this._options.trackerDuration) {
  110291. this._trackerDuration = this._options.trackerDuration;
  110292. }
  110293. if (autoGeneratePriorities) {
  110294. var priority = 0;
  110295. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  110296. var optim = _a[_i];
  110297. optim.priority = priority++;
  110298. }
  110299. }
  110300. this._improvementMode = improvementMode;
  110301. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  110302. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  110303. _this._sceneDisposeObserver = null;
  110304. _this.dispose();
  110305. });
  110306. }
  110307. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  110308. /**
  110309. * Gets a boolean indicating if the optimizer is in improvement mode
  110310. */
  110311. get: function () {
  110312. return this._improvementMode;
  110313. },
  110314. enumerable: true,
  110315. configurable: true
  110316. });
  110317. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  110318. /**
  110319. * Gets the current priority level (0 at start)
  110320. */
  110321. get: function () {
  110322. return this._currentPriorityLevel;
  110323. },
  110324. enumerable: true,
  110325. configurable: true
  110326. });
  110327. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  110328. /**
  110329. * Gets the current frame rate checked by the SceneOptimizer
  110330. */
  110331. get: function () {
  110332. return this._currentFrameRate;
  110333. },
  110334. enumerable: true,
  110335. configurable: true
  110336. });
  110337. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  110338. /**
  110339. * Gets or sets the current target frame rate (60 by default)
  110340. */
  110341. get: function () {
  110342. return this._targetFrameRate;
  110343. },
  110344. /**
  110345. * Gets or sets the current target frame rate (60 by default)
  110346. */
  110347. set: function (value) {
  110348. this._targetFrameRate = value;
  110349. },
  110350. enumerable: true,
  110351. configurable: true
  110352. });
  110353. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  110354. /**
  110355. * Gets or sets the current interval between two checks (every 2000ms by default)
  110356. */
  110357. get: function () {
  110358. return this._trackerDuration;
  110359. },
  110360. /**
  110361. * Gets or sets the current interval between two checks (every 2000ms by default)
  110362. */
  110363. set: function (value) {
  110364. this._trackerDuration = value;
  110365. },
  110366. enumerable: true,
  110367. configurable: true
  110368. });
  110369. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  110370. /**
  110371. * Gets the list of active optimizations
  110372. */
  110373. get: function () {
  110374. return this._options.optimizations;
  110375. },
  110376. enumerable: true,
  110377. configurable: true
  110378. });
  110379. /**
  110380. * Stops the current optimizer
  110381. */
  110382. SceneOptimizer.prototype.stop = function () {
  110383. this._isRunning = false;
  110384. };
  110385. /**
  110386. * Reset the optimizer to initial step (current priority level = 0)
  110387. */
  110388. SceneOptimizer.prototype.reset = function () {
  110389. this._currentPriorityLevel = 0;
  110390. };
  110391. /**
  110392. * Start the optimizer. By default it will try to reach a specific framerate
  110393. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  110394. */
  110395. SceneOptimizer.prototype.start = function () {
  110396. var _this = this;
  110397. if (this._isRunning) {
  110398. return;
  110399. }
  110400. this._isRunning = true;
  110401. // Let's wait for the scene to be ready before running our check
  110402. this._scene.executeWhenReady(function () {
  110403. setTimeout(function () {
  110404. _this._checkCurrentState();
  110405. }, _this._trackerDuration);
  110406. });
  110407. };
  110408. SceneOptimizer.prototype._checkCurrentState = function () {
  110409. var _this = this;
  110410. if (!this._isRunning) {
  110411. return;
  110412. }
  110413. var scene = this._scene;
  110414. var options = this._options;
  110415. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  110416. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  110417. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  110418. this._isRunning = false;
  110419. this.onSuccessObservable.notifyObservers(this);
  110420. return;
  110421. }
  110422. // Apply current level of optimizations
  110423. var allDone = true;
  110424. var noOptimizationApplied = true;
  110425. for (var index = 0; index < options.optimizations.length; index++) {
  110426. var optimization = options.optimizations[index];
  110427. if (optimization.priority === this._currentPriorityLevel) {
  110428. noOptimizationApplied = false;
  110429. allDone = allDone && optimization.apply(scene, this);
  110430. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  110431. }
  110432. }
  110433. // If no optimization was applied, this is a failure :(
  110434. if (noOptimizationApplied) {
  110435. this._isRunning = false;
  110436. this.onFailureObservable.notifyObservers(this);
  110437. return;
  110438. }
  110439. // If all optimizations were done, move to next level
  110440. if (allDone) {
  110441. this._currentPriorityLevel++;
  110442. }
  110443. // Let's the system running for a specific amount of time before checking FPS
  110444. scene.executeWhenReady(function () {
  110445. setTimeout(function () {
  110446. _this._checkCurrentState();
  110447. }, _this._trackerDuration);
  110448. });
  110449. };
  110450. /**
  110451. * Release all resources
  110452. */
  110453. SceneOptimizer.prototype.dispose = function () {
  110454. this.stop();
  110455. this.onSuccessObservable.clear();
  110456. this.onFailureObservable.clear();
  110457. this.onNewOptimizationAppliedObservable.clear();
  110458. if (this._sceneDisposeObserver) {
  110459. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  110460. }
  110461. };
  110462. /**
  110463. * Helper function to create a SceneOptimizer with one single line of code
  110464. * @param scene defines the scene to work on
  110465. * @param options defines the options to use with the SceneOptimizer
  110466. * @param onSuccess defines a callback to call on success
  110467. * @param onFailure defines a callback to call on failure
  110468. * @returns the new SceneOptimizer object
  110469. */
  110470. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  110471. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  110472. if (onSuccess) {
  110473. optimizer.onSuccessObservable.add(function () {
  110474. onSuccess();
  110475. });
  110476. }
  110477. if (onFailure) {
  110478. optimizer.onFailureObservable.add(function () {
  110479. onFailure();
  110480. });
  110481. }
  110482. optimizer.start();
  110483. return optimizer;
  110484. };
  110485. return SceneOptimizer;
  110486. }());
  110487. BABYLON.SceneOptimizer = SceneOptimizer;
  110488. })(BABYLON || (BABYLON = {}));
  110489. //# sourceMappingURL=sceneOptimizer.js.map
  110490. var BABYLON;
  110491. (function (BABYLON) {
  110492. /**
  110493. * Gets the outline renderer associated with the scene
  110494. * @returns a OutlineRenderer
  110495. */
  110496. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  110497. if (!this._outlineRenderer) {
  110498. this._outlineRenderer = new OutlineRenderer(this);
  110499. }
  110500. return this._outlineRenderer;
  110501. };
  110502. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  110503. get: function () {
  110504. return this._renderOutline;
  110505. },
  110506. set: function (value) {
  110507. if (value) {
  110508. // Lazy Load the component.
  110509. this.getScene().getOutlineRenderer();
  110510. }
  110511. this._renderOutline = value;
  110512. },
  110513. enumerable: true,
  110514. configurable: true
  110515. });
  110516. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  110517. get: function () {
  110518. return this._renderOverlay;
  110519. },
  110520. set: function (value) {
  110521. if (value) {
  110522. // Lazy Load the component.
  110523. this.getScene().getOutlineRenderer();
  110524. }
  110525. this._renderOverlay = value;
  110526. },
  110527. enumerable: true,
  110528. configurable: true
  110529. });
  110530. /**
  110531. * This class is responsible to draw bothe outline/overlay of meshes.
  110532. * It should not be used directly but through the available method on mesh.
  110533. */
  110534. var OutlineRenderer = /** @class */ (function () {
  110535. /**
  110536. * Instantiates a new outline renderer. (There could be only one per scene).
  110537. * @param scene Defines the scene it belongs to
  110538. */
  110539. function OutlineRenderer(scene) {
  110540. /**
  110541. * The name of the component. Each component must have a unique name.
  110542. */
  110543. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  110544. /**
  110545. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  110546. */
  110547. this.zOffset = 1;
  110548. this.scene = scene;
  110549. this._engine = scene.getEngine();
  110550. this.scene._addComponent(this);
  110551. }
  110552. /**
  110553. * Register the component to one instance of a scene.
  110554. */
  110555. OutlineRenderer.prototype.register = function () {
  110556. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  110557. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  110558. };
  110559. /**
  110560. * Rebuilds the elements related to this component in case of
  110561. * context lost for instance.
  110562. */
  110563. OutlineRenderer.prototype.rebuild = function () {
  110564. // Nothing to do here.
  110565. };
  110566. /**
  110567. * Disposes the component and the associated ressources.
  110568. */
  110569. OutlineRenderer.prototype.dispose = function () {
  110570. // Nothing to do here.
  110571. };
  110572. /**
  110573. * Renders the outline in the canvas.
  110574. * @param subMesh Defines the sumesh to render
  110575. * @param batch Defines the batch of meshes in case of instances
  110576. * @param useOverlay Defines if the rendering is for the overlay or the outline
  110577. */
  110578. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  110579. var _this = this;
  110580. if (useOverlay === void 0) { useOverlay = false; }
  110581. var scene = this.scene;
  110582. var engine = scene.getEngine();
  110583. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  110584. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  110585. return;
  110586. }
  110587. var mesh = subMesh.getRenderingMesh();
  110588. var material = subMesh.getMaterial();
  110589. if (!material || !scene.activeCamera) {
  110590. return;
  110591. }
  110592. engine.enableEffect(this._effect);
  110593. // Logarithmic depth
  110594. if (material.useLogarithmicDepth) {
  110595. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  110596. }
  110597. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  110598. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  110599. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  110600. // Bones
  110601. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  110602. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  110603. }
  110604. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  110605. // Alpha test
  110606. if (material && material.needAlphaTesting()) {
  110607. var alphaTexture = material.getAlphaTestTexture();
  110608. if (alphaTexture) {
  110609. this._effect.setTexture("diffuseSampler", alphaTexture);
  110610. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  110611. }
  110612. }
  110613. engine.setZOffset(-this.zOffset);
  110614. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  110615. engine.setZOffset(0);
  110616. };
  110617. /**
  110618. * Returns whether or not the outline renderer is ready for a given submesh.
  110619. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  110620. * @param subMesh Defines the submesh to check readyness for
  110621. * @param useInstances Defines wheter wee are trying to render instances or not
  110622. * @returns true if ready otherwise false
  110623. */
  110624. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  110625. var defines = [];
  110626. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  110627. var mesh = subMesh.getMesh();
  110628. var material = subMesh.getMaterial();
  110629. if (material) {
  110630. // Alpha test
  110631. if (material.needAlphaTesting()) {
  110632. defines.push("#define ALPHATEST");
  110633. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  110634. attribs.push(BABYLON.VertexBuffer.UVKind);
  110635. defines.push("#define UV1");
  110636. }
  110637. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  110638. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  110639. defines.push("#define UV2");
  110640. }
  110641. }
  110642. //Logarithmic depth
  110643. if (material.useLogarithmicDepth) {
  110644. defines.push("#define LOGARITHMICDEPTH");
  110645. }
  110646. }
  110647. // Bones
  110648. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  110649. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  110650. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  110651. if (mesh.numBoneInfluencers > 4) {
  110652. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  110653. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  110654. }
  110655. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  110656. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  110657. }
  110658. else {
  110659. defines.push("#define NUM_BONE_INFLUENCERS 0");
  110660. }
  110661. // Instances
  110662. if (useInstances) {
  110663. defines.push("#define INSTANCES");
  110664. attribs.push("world0");
  110665. attribs.push("world1");
  110666. attribs.push("world2");
  110667. attribs.push("world3");
  110668. }
  110669. // Get correct effect
  110670. var join = defines.join("\n");
  110671. if (this._cachedDefines !== join) {
  110672. this._cachedDefines = join;
  110673. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  110674. }
  110675. return this._effect.isReady();
  110676. };
  110677. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  110678. // Outline - step 1
  110679. this._savedDepthWrite = this._engine.getDepthWrite();
  110680. if (mesh.renderOutline) {
  110681. this._engine.setDepthWrite(false);
  110682. this.render(subMesh, batch);
  110683. this._engine.setDepthWrite(this._savedDepthWrite);
  110684. }
  110685. };
  110686. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  110687. // Outline - step 2
  110688. if (mesh.renderOutline && this._savedDepthWrite) {
  110689. this._engine.setDepthWrite(true);
  110690. this._engine.setColorWrite(false);
  110691. this.render(subMesh, batch);
  110692. this._engine.setColorWrite(true);
  110693. }
  110694. // Overlay
  110695. if (mesh.renderOverlay) {
  110696. var currentMode = this._engine.getAlphaMode();
  110697. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  110698. this.render(subMesh, batch, true);
  110699. this._engine.setAlphaMode(currentMode);
  110700. }
  110701. };
  110702. return OutlineRenderer;
  110703. }());
  110704. BABYLON.OutlineRenderer = OutlineRenderer;
  110705. })(BABYLON || (BABYLON = {}));
  110706. //# sourceMappingURL=outlineRenderer.js.map
  110707. var BABYLON;
  110708. (function (BABYLON) {
  110709. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  110710. if (this._edgesRenderer) {
  110711. this._edgesRenderer.dispose();
  110712. this._edgesRenderer = null;
  110713. }
  110714. return this;
  110715. };
  110716. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  110717. if (epsilon === void 0) { epsilon = 0.95; }
  110718. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  110719. this.disableEdgesRendering();
  110720. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  110721. return this;
  110722. };
  110723. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  110724. get: function () {
  110725. return this._edgesRenderer;
  110726. },
  110727. enumerable: true,
  110728. configurable: true
  110729. });
  110730. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  110731. if (epsilon === void 0) { epsilon = 0.95; }
  110732. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  110733. this.disableEdgesRendering();
  110734. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  110735. return this;
  110736. };
  110737. BABYLON.InstancedMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  110738. if (epsilon === void 0) { epsilon = 0.95; }
  110739. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  110740. if (this.sourceMesh.getClassName() === 'LinesMesh') {
  110741. BABYLON.LinesMesh.prototype.enableEdgesRendering.apply(this, arguments);
  110742. }
  110743. else {
  110744. BABYLON.AbstractMesh.prototype.enableEdgesRendering.apply(this, arguments);
  110745. }
  110746. return this;
  110747. };
  110748. /**
  110749. * FaceAdjacencies Helper class to generate edges
  110750. */
  110751. var FaceAdjacencies = /** @class */ (function () {
  110752. function FaceAdjacencies() {
  110753. this.edges = new Array();
  110754. this.edgesConnectedCount = 0;
  110755. }
  110756. return FaceAdjacencies;
  110757. }());
  110758. /**
  110759. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  110760. */
  110761. var EdgesRenderer = /** @class */ (function () {
  110762. /**
  110763. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  110764. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  110765. * @param source Mesh used to create edges
  110766. * @param epsilon sum of angles in adjacency to check for edge
  110767. * @param checkVerticesInsteadOfIndices
  110768. * @param generateEdgesLines - should generate Lines or only prepare resources.
  110769. */
  110770. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  110771. if (epsilon === void 0) { epsilon = 0.95; }
  110772. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  110773. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  110774. var _this = this;
  110775. /**
  110776. * Define the size of the edges with an orthographic camera
  110777. */
  110778. this.edgesWidthScalerForOrthographic = 1000.0;
  110779. /**
  110780. * Define the size of the edges with a perspective camera
  110781. */
  110782. this.edgesWidthScalerForPerspective = 50.0;
  110783. this._linesPositions = new Array();
  110784. this._linesNormals = new Array();
  110785. this._linesIndices = new Array();
  110786. this._buffers = {};
  110787. this._checkVerticesInsteadOfIndices = false;
  110788. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  110789. this.isEnabled = true;
  110790. this._source = source;
  110791. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  110792. this._epsilon = epsilon;
  110793. this._prepareRessources();
  110794. if (generateEdgesLines) {
  110795. this._generateEdgesLines();
  110796. }
  110797. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  110798. _this._rebuild();
  110799. });
  110800. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  110801. _this.dispose();
  110802. });
  110803. }
  110804. EdgesRenderer.prototype._prepareRessources = function () {
  110805. if (this._lineShader) {
  110806. return;
  110807. }
  110808. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  110809. attributes: ["position", "normal"],
  110810. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  110811. });
  110812. this._lineShader.disableDepthWrite = true;
  110813. this._lineShader.backFaceCulling = false;
  110814. };
  110815. /** @hidden */
  110816. EdgesRenderer.prototype._rebuild = function () {
  110817. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  110818. if (buffer) {
  110819. buffer._rebuild();
  110820. }
  110821. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  110822. if (buffer) {
  110823. buffer._rebuild();
  110824. }
  110825. var scene = this._source.getScene();
  110826. var engine = scene.getEngine();
  110827. this._ib = engine.createIndexBuffer(this._linesIndices);
  110828. };
  110829. /**
  110830. * Releases the required resources for the edges renderer
  110831. */
  110832. EdgesRenderer.prototype.dispose = function () {
  110833. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  110834. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  110835. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  110836. if (buffer) {
  110837. buffer.dispose();
  110838. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  110839. }
  110840. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  110841. if (buffer) {
  110842. buffer.dispose();
  110843. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  110844. }
  110845. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  110846. this._lineShader.dispose();
  110847. };
  110848. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  110849. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  110850. return 0;
  110851. }
  110852. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  110853. return 1;
  110854. }
  110855. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  110856. return 2;
  110857. }
  110858. return -1;
  110859. };
  110860. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  110861. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  110862. return 0;
  110863. }
  110864. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  110865. return 1;
  110866. }
  110867. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  110868. return 2;
  110869. }
  110870. return -1;
  110871. };
  110872. /**
  110873. * Checks if the pair of p0 and p1 is en edge
  110874. * @param faceIndex
  110875. * @param edge
  110876. * @param faceNormals
  110877. * @param p0
  110878. * @param p1
  110879. * @private
  110880. */
  110881. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  110882. var needToCreateLine;
  110883. if (edge === undefined) {
  110884. needToCreateLine = true;
  110885. }
  110886. else {
  110887. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  110888. needToCreateLine = dotProduct < this._epsilon;
  110889. }
  110890. if (needToCreateLine) {
  110891. this.createLine(p0, p1, this._linesPositions.length / 3);
  110892. }
  110893. };
  110894. /**
  110895. * push line into the position, normal and index buffer
  110896. * @protected
  110897. */
  110898. EdgesRenderer.prototype.createLine = function (p0, p1, offset) {
  110899. // Positions
  110900. this._linesPositions.push(p0.x, p0.y, p0.z, p0.x, p0.y, p0.z, p1.x, p1.y, p1.z, p1.x, p1.y, p1.z);
  110901. // Normals
  110902. this._linesNormals.push(p1.x, p1.y, p1.z, -1, p1.x, p1.y, p1.z, 1, p0.x, p0.y, p0.z, -1, p0.x, p0.y, p0.z, 1);
  110903. // Indices
  110904. this._linesIndices.push(offset, offset + 1, offset + 2, offset, offset + 2, offset + 3);
  110905. };
  110906. /**
  110907. * Generates lines edges from adjacencjes
  110908. * @private
  110909. */
  110910. EdgesRenderer.prototype._generateEdgesLines = function () {
  110911. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  110912. var indices = this._source.getIndices();
  110913. if (!indices || !positions) {
  110914. return;
  110915. }
  110916. // First let's find adjacencies
  110917. var adjacencies = new Array();
  110918. var faceNormals = new Array();
  110919. var index;
  110920. var faceAdjacencies;
  110921. // Prepare faces
  110922. for (index = 0; index < indices.length; index += 3) {
  110923. faceAdjacencies = new FaceAdjacencies();
  110924. var p0Index = indices[index];
  110925. var p1Index = indices[index + 1];
  110926. var p2Index = indices[index + 2];
  110927. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  110928. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  110929. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  110930. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  110931. faceNormal.normalize();
  110932. faceNormals.push(faceNormal);
  110933. adjacencies.push(faceAdjacencies);
  110934. }
  110935. // Scan
  110936. for (index = 0; index < adjacencies.length; index++) {
  110937. faceAdjacencies = adjacencies[index];
  110938. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  110939. var otherFaceAdjacencies = adjacencies[otherIndex];
  110940. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  110941. break;
  110942. }
  110943. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  110944. continue;
  110945. }
  110946. var otherP0 = indices[otherIndex * 3];
  110947. var otherP1 = indices[otherIndex * 3 + 1];
  110948. var otherP2 = indices[otherIndex * 3 + 2];
  110949. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  110950. var otherEdgeIndex = 0;
  110951. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  110952. continue;
  110953. }
  110954. switch (edgeIndex) {
  110955. case 0:
  110956. if (this._checkVerticesInsteadOfIndices) {
  110957. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  110958. }
  110959. else {
  110960. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  110961. }
  110962. break;
  110963. case 1:
  110964. if (this._checkVerticesInsteadOfIndices) {
  110965. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  110966. }
  110967. else {
  110968. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  110969. }
  110970. break;
  110971. case 2:
  110972. if (this._checkVerticesInsteadOfIndices) {
  110973. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  110974. }
  110975. else {
  110976. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  110977. }
  110978. break;
  110979. }
  110980. if (otherEdgeIndex === -1) {
  110981. continue;
  110982. }
  110983. faceAdjacencies.edges[edgeIndex] = otherIndex;
  110984. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  110985. faceAdjacencies.edgesConnectedCount++;
  110986. otherFaceAdjacencies.edgesConnectedCount++;
  110987. if (faceAdjacencies.edgesConnectedCount === 3) {
  110988. break;
  110989. }
  110990. }
  110991. }
  110992. }
  110993. // Create lines
  110994. for (index = 0; index < adjacencies.length; index++) {
  110995. // 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
  110996. var current = adjacencies[index];
  110997. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  110998. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  110999. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  111000. }
  111001. // Merge into a single mesh
  111002. var engine = this._source.getScene().getEngine();
  111003. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  111004. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  111005. this._ib = engine.createIndexBuffer(this._linesIndices);
  111006. this._indicesCount = this._linesIndices.length;
  111007. };
  111008. /**
  111009. * Checks wether or not the edges renderer is ready to render.
  111010. * @return true if ready, otherwise false.
  111011. */
  111012. EdgesRenderer.prototype.isReady = function () {
  111013. return this._lineShader.isReady();
  111014. };
  111015. /**
  111016. * Renders the edges of the attached mesh,
  111017. */
  111018. EdgesRenderer.prototype.render = function () {
  111019. var scene = this._source.getScene();
  111020. if (!this.isReady() || !scene.activeCamera) {
  111021. return;
  111022. }
  111023. var engine = scene.getEngine();
  111024. this._lineShader._preBind();
  111025. if (this._source.edgesColor.a !== 1) {
  111026. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  111027. }
  111028. else {
  111029. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  111030. }
  111031. // VBOs
  111032. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  111033. scene.resetCachedMaterial();
  111034. this._lineShader.setColor4("color", this._source.edgesColor);
  111035. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  111036. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  111037. }
  111038. else {
  111039. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  111040. }
  111041. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  111042. this._lineShader.bind(this._source.getWorldMatrix());
  111043. // Draw order
  111044. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  111045. this._lineShader.unbind();
  111046. };
  111047. return EdgesRenderer;
  111048. }());
  111049. BABYLON.EdgesRenderer = EdgesRenderer;
  111050. })(BABYLON || (BABYLON = {}));
  111051. //# sourceMappingURL=edgesRenderer.js.map
  111052. var BABYLON;
  111053. (function (BABYLON) {
  111054. /**
  111055. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  111056. */
  111057. var LineEdgesRenderer = /** @class */ (function (_super) {
  111058. __extends(LineEdgesRenderer, _super);
  111059. /**
  111060. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  111061. * @param source LineMesh used to generate edges
  111062. * @param epsilon not important (specified angle for edge detection)
  111063. * @param checkVerticesInsteadOfIndices not important for LineMesh
  111064. */
  111065. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  111066. if (epsilon === void 0) { epsilon = 0.95; }
  111067. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  111068. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  111069. _this._generateEdgesLines();
  111070. return _this;
  111071. }
  111072. /**
  111073. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  111074. */
  111075. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  111076. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  111077. var indices = this._source.getIndices();
  111078. if (!indices || !positions) {
  111079. return;
  111080. }
  111081. var p0 = BABYLON.Tmp.Vector3[0];
  111082. var p1 = BABYLON.Tmp.Vector3[1];
  111083. var len = indices.length - 1;
  111084. for (var i = 0, offset = 0; i < len; i += 2, offset += 4) {
  111085. BABYLON.Vector3.FromArrayToRef(positions, 3 * indices[i], p0);
  111086. BABYLON.Vector3.FromArrayToRef(positions, 3 * indices[i + 1], p1);
  111087. this.createLine(p0, p1, offset);
  111088. }
  111089. // Merge into a single mesh
  111090. var engine = this._source.getScene().getEngine();
  111091. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  111092. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  111093. this._ib = engine.createIndexBuffer(this._linesIndices);
  111094. this._indicesCount = this._linesIndices.length;
  111095. };
  111096. return LineEdgesRenderer;
  111097. }(BABYLON.EdgesRenderer));
  111098. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  111099. })(BABYLON || (BABYLON = {}));
  111100. //# sourceMappingURL=lineEdgesRenderer.js.map
  111101. var BABYLON;
  111102. (function (BABYLON) {
  111103. // Adds the parser to the scene parsers.
  111104. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  111105. if (parsedData.effectLayers) {
  111106. if (!container.effectLayers) {
  111107. container.effectLayers = new Array();
  111108. }
  111109. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  111110. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  111111. container.effectLayers.push(effectLayer);
  111112. }
  111113. }
  111114. });
  111115. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  111116. var index = this.effectLayers.indexOf(toRemove);
  111117. if (index !== -1) {
  111118. this.effectLayers.splice(index, 1);
  111119. }
  111120. return index;
  111121. };
  111122. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  111123. this.effectLayers.push(newEffectLayer);
  111124. };
  111125. /**
  111126. * Defines the layer scene component responsible to manage any effect layers
  111127. * in a given scene.
  111128. */
  111129. var EffectLayerSceneComponent = /** @class */ (function () {
  111130. /**
  111131. * Creates a new instance of the component for the given scene
  111132. * @param scene Defines the scene to register the component in
  111133. */
  111134. function EffectLayerSceneComponent(scene) {
  111135. /**
  111136. * The component name helpfull to identify the component in the list of scene components.
  111137. */
  111138. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  111139. this._renderEffects = false;
  111140. this._needStencil = false;
  111141. this._previousStencilState = false;
  111142. this.scene = scene;
  111143. this._engine = scene.getEngine();
  111144. scene.effectLayers = new Array();
  111145. }
  111146. /**
  111147. * Registers the component in a given scene
  111148. */
  111149. EffectLayerSceneComponent.prototype.register = function () {
  111150. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  111151. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  111152. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  111153. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  111154. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  111155. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  111156. };
  111157. /**
  111158. * Rebuilds the elements related to this component in case of
  111159. * context lost for instance.
  111160. */
  111161. EffectLayerSceneComponent.prototype.rebuild = function () {
  111162. var layers = this.scene.effectLayers;
  111163. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  111164. var effectLayer = layers_1[_i];
  111165. effectLayer._rebuild();
  111166. }
  111167. };
  111168. /**
  111169. * Serializes the component data to the specified json object
  111170. * @param serializationObject The object to serialize to
  111171. */
  111172. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  111173. // Effect layers
  111174. serializationObject.effectLayers = [];
  111175. var layers = this.scene.effectLayers;
  111176. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  111177. var effectLayer = layers_2[_i];
  111178. if (effectLayer.serialize) {
  111179. serializationObject.effectLayers.push(effectLayer.serialize());
  111180. }
  111181. }
  111182. };
  111183. /**
  111184. * Adds all the element from the container to the scene
  111185. * @param container the container holding the elements
  111186. */
  111187. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  111188. var _this = this;
  111189. if (!container.effectLayers) {
  111190. return;
  111191. }
  111192. container.effectLayers.forEach(function (o) {
  111193. _this.scene.addEffectLayer(o);
  111194. });
  111195. };
  111196. /**
  111197. * Removes all the elements in the container from the scene
  111198. * @param container contains the elements to remove
  111199. */
  111200. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  111201. var _this = this;
  111202. if (!container.effectLayers) {
  111203. return;
  111204. }
  111205. container.effectLayers.forEach(function (o) {
  111206. _this.scene.removeEffectLayer(o);
  111207. });
  111208. };
  111209. /**
  111210. * Disposes the component and the associated ressources.
  111211. */
  111212. EffectLayerSceneComponent.prototype.dispose = function () {
  111213. var layers = this.scene.effectLayers;
  111214. while (layers.length) {
  111215. layers[0].dispose();
  111216. }
  111217. };
  111218. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  111219. var layers = this.scene.effectLayers;
  111220. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  111221. var layer = layers_3[_i];
  111222. if (!layer.hasMesh(mesh)) {
  111223. continue;
  111224. }
  111225. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  111226. var subMesh = _b[_a];
  111227. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  111228. return false;
  111229. }
  111230. }
  111231. }
  111232. return true;
  111233. };
  111234. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  111235. this._renderEffects = false;
  111236. this._needStencil = false;
  111237. var layers = this.scene.effectLayers;
  111238. if (layers && layers.length > 0) {
  111239. this._previousStencilState = this._engine.getStencilBuffer();
  111240. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  111241. var effectLayer = layers_4[_i];
  111242. if (effectLayer.shouldRender() &&
  111243. (!effectLayer.camera ||
  111244. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  111245. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  111246. this._renderEffects = true;
  111247. this._needStencil = this._needStencil || effectLayer.needStencil();
  111248. var renderTarget = effectLayer._mainTexture;
  111249. if (renderTarget._shouldRender()) {
  111250. this.scene.incrementRenderId();
  111251. renderTarget.render(false, false);
  111252. }
  111253. }
  111254. }
  111255. this.scene.incrementRenderId();
  111256. }
  111257. };
  111258. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  111259. // Activate effect Layer stencil
  111260. if (this._needStencil) {
  111261. this._engine.setStencilBuffer(true);
  111262. }
  111263. };
  111264. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  111265. // Restore effect Layer stencil
  111266. if (this._needStencil) {
  111267. this._engine.setStencilBuffer(this._previousStencilState);
  111268. }
  111269. };
  111270. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  111271. if (this._renderEffects) {
  111272. this._engine.setDepthBuffer(false);
  111273. var layers = this.scene.effectLayers;
  111274. for (var i = 0; i < layers.length; i++) {
  111275. var effectLayer = layers[i];
  111276. if (effectLayer.renderingGroupId === renderingGroupId) {
  111277. if (effectLayer.shouldRender()) {
  111278. effectLayer.render();
  111279. }
  111280. }
  111281. }
  111282. this._engine.setDepthBuffer(true);
  111283. }
  111284. };
  111285. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  111286. if (this._renderEffects) {
  111287. this._draw(-1);
  111288. }
  111289. };
  111290. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  111291. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  111292. this._draw(index);
  111293. }
  111294. };
  111295. return EffectLayerSceneComponent;
  111296. }());
  111297. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  111298. })(BABYLON || (BABYLON = {}));
  111299. //# sourceMappingURL=effectLayerSceneComponent.js.map
  111300. var __assign = (this && this.__assign) || function () {
  111301. __assign = Object.assign || function(t) {
  111302. for (var s, i = 1, n = arguments.length; i < n; i++) {
  111303. s = arguments[i];
  111304. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  111305. t[p] = s[p];
  111306. }
  111307. return t;
  111308. };
  111309. return __assign.apply(this, arguments);
  111310. };
  111311. var BABYLON;
  111312. (function (BABYLON) {
  111313. /**
  111314. * The effect layer Helps adding post process effect blended with the main pass.
  111315. *
  111316. * This can be for instance use to generate glow or higlight effects on the scene.
  111317. *
  111318. * The effect layer class can not be used directly and is intented to inherited from to be
  111319. * customized per effects.
  111320. */
  111321. var EffectLayer = /** @class */ (function () {
  111322. /**
  111323. * Instantiates a new effect Layer and references it in the scene.
  111324. * @param name The name of the layer
  111325. * @param scene The scene to use the layer in
  111326. */
  111327. function EffectLayer(
  111328. /** The Friendly of the effect in the scene */
  111329. name, scene) {
  111330. this._vertexBuffers = {};
  111331. this._maxSize = 0;
  111332. this._mainTextureDesiredSize = { width: 0, height: 0 };
  111333. this._shouldRender = true;
  111334. this._postProcesses = [];
  111335. this._textures = [];
  111336. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  111337. /**
  111338. * The clear color of the texture used to generate the glow map.
  111339. */
  111340. this.neutralColor = new BABYLON.Color4();
  111341. /**
  111342. * Specifies wether the highlight layer is enabled or not.
  111343. */
  111344. this.isEnabled = true;
  111345. /**
  111346. * An event triggered when the effect layer has been disposed.
  111347. */
  111348. this.onDisposeObservable = new BABYLON.Observable();
  111349. /**
  111350. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  111351. */
  111352. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  111353. /**
  111354. * An event triggered when the generated texture is being merged in the scene.
  111355. */
  111356. this.onBeforeComposeObservable = new BABYLON.Observable();
  111357. /**
  111358. * An event triggered when the generated texture has been merged in the scene.
  111359. */
  111360. this.onAfterComposeObservable = new BABYLON.Observable();
  111361. /**
  111362. * An event triggered when the efffect layer changes its size.
  111363. */
  111364. this.onSizeChangedObservable = new BABYLON.Observable();
  111365. this.name = name;
  111366. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  111367. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  111368. if (!component) {
  111369. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  111370. this._scene._addComponent(component);
  111371. }
  111372. this._engine = this._scene.getEngine();
  111373. this._maxSize = this._engine.getCaps().maxTextureSize;
  111374. this._scene.effectLayers.push(this);
  111375. // Generate Buffers
  111376. this._generateIndexBuffer();
  111377. this._genrateVertexBuffer();
  111378. }
  111379. Object.defineProperty(EffectLayer.prototype, "camera", {
  111380. /**
  111381. * Gets the camera attached to the layer.
  111382. */
  111383. get: function () {
  111384. return this._effectLayerOptions.camera;
  111385. },
  111386. enumerable: true,
  111387. configurable: true
  111388. });
  111389. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  111390. /**
  111391. * Gets the rendering group id the layer should render in.
  111392. */
  111393. get: function () {
  111394. return this._effectLayerOptions.renderingGroupId;
  111395. },
  111396. enumerable: true,
  111397. configurable: true
  111398. });
  111399. /**
  111400. * Initializes the effect layer with the required options.
  111401. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  111402. */
  111403. EffectLayer.prototype._init = function (options) {
  111404. // Adapt options
  111405. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  111406. this._setMainTextureSize();
  111407. this._createMainTexture();
  111408. this._createTextureAndPostProcesses();
  111409. this._mergeEffect = this._createMergeEffect();
  111410. };
  111411. /**
  111412. * Generates the index buffer of the full screen quad blending to the main canvas.
  111413. */
  111414. EffectLayer.prototype._generateIndexBuffer = function () {
  111415. // Indices
  111416. var indices = [];
  111417. indices.push(0);
  111418. indices.push(1);
  111419. indices.push(2);
  111420. indices.push(0);
  111421. indices.push(2);
  111422. indices.push(3);
  111423. this._indexBuffer = this._engine.createIndexBuffer(indices);
  111424. };
  111425. /**
  111426. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  111427. */
  111428. EffectLayer.prototype._genrateVertexBuffer = function () {
  111429. // VBO
  111430. var vertices = [];
  111431. vertices.push(1, 1);
  111432. vertices.push(-1, 1);
  111433. vertices.push(-1, -1);
  111434. vertices.push(1, -1);
  111435. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  111436. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  111437. };
  111438. /**
  111439. * Sets the main texture desired size which is the closest power of two
  111440. * of the engine canvas size.
  111441. */
  111442. EffectLayer.prototype._setMainTextureSize = function () {
  111443. if (this._effectLayerOptions.mainTextureFixedSize) {
  111444. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  111445. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  111446. }
  111447. else {
  111448. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  111449. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  111450. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  111451. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  111452. }
  111453. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  111454. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  111455. };
  111456. /**
  111457. * Creates the main texture for the effect layer.
  111458. */
  111459. EffectLayer.prototype._createMainTexture = function () {
  111460. var _this = this;
  111461. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  111462. width: this._mainTextureDesiredSize.width,
  111463. height: this._mainTextureDesiredSize.height
  111464. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  111465. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  111466. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111467. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111468. this._mainTexture.anisotropicFilteringLevel = 1;
  111469. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  111470. this._mainTexture.renderParticles = false;
  111471. this._mainTexture.renderList = null;
  111472. this._mainTexture.ignoreCameraViewport = true;
  111473. // Custom render function
  111474. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  111475. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  111476. var index;
  111477. var engine = _this._scene.getEngine();
  111478. if (depthOnlySubMeshes.length) {
  111479. engine.setColorWrite(false);
  111480. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  111481. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  111482. }
  111483. engine.setColorWrite(true);
  111484. }
  111485. for (index = 0; index < opaqueSubMeshes.length; index++) {
  111486. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  111487. }
  111488. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  111489. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  111490. }
  111491. for (index = 0; index < transparentSubMeshes.length; index++) {
  111492. _this._renderSubMesh(transparentSubMeshes.data[index]);
  111493. }
  111494. };
  111495. this._mainTexture.onClearObservable.add(function (engine) {
  111496. engine.clear(_this.neutralColor, true, true, true);
  111497. });
  111498. };
  111499. /**
  111500. * Checks for the readiness of the element composing the layer.
  111501. * @param subMesh the mesh to check for
  111502. * @param useInstances specify wether or not to use instances to render the mesh
  111503. * @param emissiveTexture the associated emissive texture used to generate the glow
  111504. * @return true if ready otherwise, false
  111505. */
  111506. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  111507. var material = subMesh.getMaterial();
  111508. if (!material) {
  111509. return false;
  111510. }
  111511. if (!material.isReadyForSubMesh(subMesh.getMesh(), subMesh, useInstances)) {
  111512. return false;
  111513. }
  111514. var defines = [];
  111515. var attribs = [BABYLON.VertexBuffer.PositionKind];
  111516. var mesh = subMesh.getMesh();
  111517. var uv1 = false;
  111518. var uv2 = false;
  111519. // Alpha test
  111520. if (material && material.needAlphaTesting()) {
  111521. var alphaTexture = material.getAlphaTestTexture();
  111522. if (alphaTexture) {
  111523. defines.push("#define ALPHATEST");
  111524. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  111525. alphaTexture.coordinatesIndex === 1) {
  111526. defines.push("#define DIFFUSEUV2");
  111527. uv2 = true;
  111528. }
  111529. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  111530. defines.push("#define DIFFUSEUV1");
  111531. uv1 = true;
  111532. }
  111533. }
  111534. }
  111535. // Emissive
  111536. if (emissiveTexture) {
  111537. defines.push("#define EMISSIVE");
  111538. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  111539. emissiveTexture.coordinatesIndex === 1) {
  111540. defines.push("#define EMISSIVEUV2");
  111541. uv2 = true;
  111542. }
  111543. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  111544. defines.push("#define EMISSIVEUV1");
  111545. uv1 = true;
  111546. }
  111547. }
  111548. if (uv1) {
  111549. attribs.push(BABYLON.VertexBuffer.UVKind);
  111550. defines.push("#define UV1");
  111551. }
  111552. if (uv2) {
  111553. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  111554. defines.push("#define UV2");
  111555. }
  111556. // Bones
  111557. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  111558. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  111559. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  111560. if (mesh.numBoneInfluencers > 4) {
  111561. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  111562. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  111563. }
  111564. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  111565. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  111566. }
  111567. else {
  111568. defines.push("#define NUM_BONE_INFLUENCERS 0");
  111569. }
  111570. // Morph targets
  111571. var manager = mesh.morphTargetManager;
  111572. var morphInfluencers = 0;
  111573. if (manager) {
  111574. if (manager.numInfluencers > 0) {
  111575. defines.push("#define MORPHTARGETS");
  111576. morphInfluencers = manager.numInfluencers;
  111577. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  111578. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  111579. }
  111580. }
  111581. // Instances
  111582. if (useInstances) {
  111583. defines.push("#define INSTANCES");
  111584. attribs.push("world0");
  111585. attribs.push("world1");
  111586. attribs.push("world2");
  111587. attribs.push("world3");
  111588. }
  111589. // Get correct effect
  111590. var join = defines.join("\n");
  111591. if (this._cachedDefines !== join) {
  111592. this._cachedDefines = join;
  111593. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  111594. }
  111595. return this._effectLayerMapGenerationEffect.isReady();
  111596. };
  111597. /**
  111598. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  111599. */
  111600. EffectLayer.prototype.render = function () {
  111601. var currentEffect = this._mergeEffect;
  111602. // Check
  111603. if (!currentEffect.isReady()) {
  111604. return;
  111605. }
  111606. for (var i = 0; i < this._postProcesses.length; i++) {
  111607. if (!this._postProcesses[i].isReady()) {
  111608. return;
  111609. }
  111610. }
  111611. var engine = this._scene.getEngine();
  111612. this.onBeforeComposeObservable.notifyObservers(this);
  111613. // Render
  111614. engine.enableEffect(currentEffect);
  111615. engine.setState(false);
  111616. // VBOs
  111617. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  111618. // Cache
  111619. var previousAlphaMode = engine.getAlphaMode();
  111620. // Go Blend.
  111621. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  111622. // Blends the map on the main canvas.
  111623. this._internalRender(currentEffect);
  111624. // Restore Alpha
  111625. engine.setAlphaMode(previousAlphaMode);
  111626. this.onAfterComposeObservable.notifyObservers(this);
  111627. // Handle size changes.
  111628. var size = this._mainTexture.getSize();
  111629. this._setMainTextureSize();
  111630. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  111631. // Recreate RTT and post processes on size change.
  111632. this.onSizeChangedObservable.notifyObservers(this);
  111633. this._disposeTextureAndPostProcesses();
  111634. this._createMainTexture();
  111635. this._createTextureAndPostProcesses();
  111636. }
  111637. };
  111638. /**
  111639. * Determine if a given mesh will be used in the current effect.
  111640. * @param mesh mesh to test
  111641. * @returns true if the mesh will be used
  111642. */
  111643. EffectLayer.prototype.hasMesh = function (mesh) {
  111644. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  111645. return true;
  111646. }
  111647. return false;
  111648. };
  111649. /**
  111650. * Returns true if the layer contains information to display, otherwise false.
  111651. * @returns true if the glow layer should be rendered
  111652. */
  111653. EffectLayer.prototype.shouldRender = function () {
  111654. return this.isEnabled && this._shouldRender;
  111655. };
  111656. /**
  111657. * Returns true if the mesh should render, otherwise false.
  111658. * @param mesh The mesh to render
  111659. * @returns true if it should render otherwise false
  111660. */
  111661. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  111662. return true;
  111663. };
  111664. /**
  111665. * Returns true if the mesh should render, otherwise false.
  111666. * @param mesh The mesh to render
  111667. * @returns true if it should render otherwise false
  111668. */
  111669. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  111670. return true;
  111671. };
  111672. /**
  111673. * Renders the submesh passed in parameter to the generation map.
  111674. */
  111675. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  111676. var _this = this;
  111677. if (!this.shouldRender()) {
  111678. return;
  111679. }
  111680. var material = subMesh.getMaterial();
  111681. var mesh = subMesh.getRenderingMesh();
  111682. var scene = this._scene;
  111683. var engine = scene.getEngine();
  111684. if (!material) {
  111685. return;
  111686. }
  111687. // Do not block in blend mode.
  111688. if (material.needAlphaBlendingForMesh(mesh)) {
  111689. return;
  111690. }
  111691. // Culling
  111692. engine.setState(material.backFaceCulling);
  111693. // Managing instances
  111694. var batch = mesh._getInstancesRenderList(subMesh._id);
  111695. if (batch.mustReturn) {
  111696. return;
  111697. }
  111698. // Early Exit per mesh
  111699. if (!this._shouldRenderMesh(mesh)) {
  111700. return;
  111701. }
  111702. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  111703. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  111704. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  111705. engine.enableEffect(this._effectLayerMapGenerationEffect);
  111706. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  111707. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  111708. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  111709. // Alpha test
  111710. if (material && material.needAlphaTesting()) {
  111711. var alphaTexture = material.getAlphaTestTexture();
  111712. if (alphaTexture) {
  111713. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  111714. var textureMatrix = alphaTexture.getTextureMatrix();
  111715. if (textureMatrix) {
  111716. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  111717. }
  111718. }
  111719. }
  111720. // Glow emissive only
  111721. if (this._emissiveTextureAndColor.texture) {
  111722. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  111723. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  111724. }
  111725. // Bones
  111726. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  111727. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  111728. }
  111729. // Morph targets
  111730. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  111731. // Draw
  111732. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  111733. }
  111734. else {
  111735. // Need to reset refresh rate of the main map
  111736. this._mainTexture.resetRefreshCounter();
  111737. }
  111738. };
  111739. /**
  111740. * Rebuild the required buffers.
  111741. * @hidden Internal use only.
  111742. */
  111743. EffectLayer.prototype._rebuild = function () {
  111744. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  111745. if (vb) {
  111746. vb._rebuild();
  111747. }
  111748. this._generateIndexBuffer();
  111749. };
  111750. /**
  111751. * Dispose only the render target textures and post process.
  111752. */
  111753. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  111754. this._mainTexture.dispose();
  111755. for (var i = 0; i < this._postProcesses.length; i++) {
  111756. if (this._postProcesses[i]) {
  111757. this._postProcesses[i].dispose();
  111758. }
  111759. }
  111760. this._postProcesses = [];
  111761. for (var i = 0; i < this._textures.length; i++) {
  111762. if (this._textures[i]) {
  111763. this._textures[i].dispose();
  111764. }
  111765. }
  111766. this._textures = [];
  111767. };
  111768. /**
  111769. * Dispose the highlight layer and free resources.
  111770. */
  111771. EffectLayer.prototype.dispose = function () {
  111772. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  111773. if (vertexBuffer) {
  111774. vertexBuffer.dispose();
  111775. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  111776. }
  111777. if (this._indexBuffer) {
  111778. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  111779. this._indexBuffer = null;
  111780. }
  111781. // Clean textures and post processes
  111782. this._disposeTextureAndPostProcesses();
  111783. // Remove from scene
  111784. var index = this._scene.effectLayers.indexOf(this, 0);
  111785. if (index > -1) {
  111786. this._scene.effectLayers.splice(index, 1);
  111787. }
  111788. // Callback
  111789. this.onDisposeObservable.notifyObservers(this);
  111790. this.onDisposeObservable.clear();
  111791. this.onBeforeRenderMainTextureObservable.clear();
  111792. this.onBeforeComposeObservable.clear();
  111793. this.onAfterComposeObservable.clear();
  111794. this.onSizeChangedObservable.clear();
  111795. };
  111796. /**
  111797. * Gets the class name of the effect layer
  111798. * @returns the string with the class name of the effect layer
  111799. */
  111800. EffectLayer.prototype.getClassName = function () {
  111801. return "EffectLayer";
  111802. };
  111803. /**
  111804. * Creates an effect layer from parsed effect layer data
  111805. * @param parsedEffectLayer defines effect layer data
  111806. * @param scene defines the current scene
  111807. * @param rootUrl defines the root URL containing the effect layer information
  111808. * @returns a parsed effect Layer
  111809. */
  111810. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  111811. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  111812. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  111813. };
  111814. __decorate([
  111815. BABYLON.serialize()
  111816. ], EffectLayer.prototype, "name", void 0);
  111817. __decorate([
  111818. BABYLON.serializeAsColor4()
  111819. ], EffectLayer.prototype, "neutralColor", void 0);
  111820. __decorate([
  111821. BABYLON.serialize()
  111822. ], EffectLayer.prototype, "isEnabled", void 0);
  111823. __decorate([
  111824. BABYLON.serializeAsCameraReference()
  111825. ], EffectLayer.prototype, "camera", null);
  111826. __decorate([
  111827. BABYLON.serialize()
  111828. ], EffectLayer.prototype, "renderingGroupId", null);
  111829. return EffectLayer;
  111830. }());
  111831. BABYLON.EffectLayer = EffectLayer;
  111832. })(BABYLON || (BABYLON = {}));
  111833. //# sourceMappingURL=effectLayer.js.map
  111834. var BABYLON;
  111835. (function (BABYLON) {
  111836. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  111837. for (var index = 0; index < this.effectLayers.length; index++) {
  111838. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  111839. return this.effectLayers[index];
  111840. }
  111841. }
  111842. return null;
  111843. };
  111844. /**
  111845. * Special Glow Blur post process only blurring the alpha channel
  111846. * It enforces keeping the most luminous color in the color channel.
  111847. */
  111848. var GlowBlurPostProcess = /** @class */ (function (_super) {
  111849. __extends(GlowBlurPostProcess, _super);
  111850. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  111851. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  111852. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  111853. _this.direction = direction;
  111854. _this.kernel = kernel;
  111855. _this.onApplyObservable.add(function (effect) {
  111856. effect.setFloat2("screenSize", _this.width, _this.height);
  111857. effect.setVector2("direction", _this.direction);
  111858. effect.setFloat("blurWidth", _this.kernel);
  111859. });
  111860. return _this;
  111861. }
  111862. return GlowBlurPostProcess;
  111863. }(BABYLON.PostProcess));
  111864. /**
  111865. * The highlight layer Helps adding a glow effect around a mesh.
  111866. *
  111867. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  111868. * glowy meshes to your scene.
  111869. *
  111870. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  111871. */
  111872. var HighlightLayer = /** @class */ (function (_super) {
  111873. __extends(HighlightLayer, _super);
  111874. /**
  111875. * Instantiates a new highlight Layer and references it to the scene..
  111876. * @param name The name of the layer
  111877. * @param scene The scene to use the layer in
  111878. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  111879. */
  111880. function HighlightLayer(name, scene, options) {
  111881. var _this = _super.call(this, name, scene) || this;
  111882. _this.name = name;
  111883. /**
  111884. * Specifies whether or not the inner glow is ACTIVE in the layer.
  111885. */
  111886. _this.innerGlow = true;
  111887. /**
  111888. * Specifies whether or not the outer glow is ACTIVE in the layer.
  111889. */
  111890. _this.outerGlow = true;
  111891. /**
  111892. * An event triggered when the highlight layer is being blurred.
  111893. */
  111894. _this.onBeforeBlurObservable = new BABYLON.Observable();
  111895. /**
  111896. * An event triggered when the highlight layer has been blurred.
  111897. */
  111898. _this.onAfterBlurObservable = new BABYLON.Observable();
  111899. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  111900. _this._meshes = {};
  111901. _this._excludedMeshes = {};
  111902. _this.neutralColor = HighlightLayer.NeutralColor;
  111903. // Warn on stencil
  111904. if (!_this._engine.isStencilEnable) {
  111905. 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 }");
  111906. }
  111907. // Adapt options
  111908. _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);
  111909. // Initialize the layer
  111910. _this._init({
  111911. alphaBlendingMode: _this._options.alphaBlendingMode,
  111912. camera: _this._options.camera,
  111913. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  111914. mainTextureRatio: _this._options.mainTextureRatio,
  111915. renderingGroupId: _this._options.renderingGroupId
  111916. });
  111917. // Do not render as long as no meshes have been added
  111918. _this._shouldRender = false;
  111919. return _this;
  111920. }
  111921. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  111922. /**
  111923. * Gets the horizontal size of the blur.
  111924. */
  111925. get: function () {
  111926. return this._horizontalBlurPostprocess.kernel;
  111927. },
  111928. /**
  111929. * Specifies the horizontal size of the blur.
  111930. */
  111931. set: function (value) {
  111932. this._horizontalBlurPostprocess.kernel = value;
  111933. },
  111934. enumerable: true,
  111935. configurable: true
  111936. });
  111937. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  111938. /**
  111939. * Gets the vertical size of the blur.
  111940. */
  111941. get: function () {
  111942. return this._verticalBlurPostprocess.kernel;
  111943. },
  111944. /**
  111945. * Specifies the vertical size of the blur.
  111946. */
  111947. set: function (value) {
  111948. this._verticalBlurPostprocess.kernel = value;
  111949. },
  111950. enumerable: true,
  111951. configurable: true
  111952. });
  111953. /**
  111954. * Get the effect name of the layer.
  111955. * @return The effect name
  111956. */
  111957. HighlightLayer.prototype.getEffectName = function () {
  111958. return HighlightLayer.EffectName;
  111959. };
  111960. /**
  111961. * Create the merge effect. This is the shader use to blit the information back
  111962. * to the main canvas at the end of the scene rendering.
  111963. */
  111964. HighlightLayer.prototype._createMergeEffect = function () {
  111965. // Effect
  111966. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  111967. };
  111968. /**
  111969. * Creates the render target textures and post processes used in the highlight layer.
  111970. */
  111971. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  111972. var _this = this;
  111973. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  111974. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  111975. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  111976. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  111977. var textureType = 0;
  111978. if (this._engine.getCaps().textureHalfFloatRender) {
  111979. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  111980. }
  111981. else {
  111982. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  111983. }
  111984. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  111985. width: blurTextureWidth,
  111986. height: blurTextureHeight
  111987. }, this._scene, false, true, textureType);
  111988. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111989. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111990. this._blurTexture.anisotropicFilteringLevel = 16;
  111991. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  111992. this._blurTexture.renderParticles = false;
  111993. this._blurTexture.ignoreCameraViewport = true;
  111994. this._textures = [this._blurTexture];
  111995. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  111996. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  111997. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  111998. effect.setTexture("textureSampler", _this._mainTexture);
  111999. });
  112000. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  112001. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  112002. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  112003. });
  112004. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  112005. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  112006. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  112007. });
  112008. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  112009. }
  112010. else {
  112011. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  112012. width: blurTextureWidth,
  112013. height: blurTextureHeight
  112014. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  112015. this._horizontalBlurPostprocess.width = blurTextureWidth;
  112016. this._horizontalBlurPostprocess.height = blurTextureHeight;
  112017. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  112018. effect.setTexture("textureSampler", _this._mainTexture);
  112019. });
  112020. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  112021. width: blurTextureWidth,
  112022. height: blurTextureHeight
  112023. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  112024. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  112025. }
  112026. this._mainTexture.onAfterUnbindObservable.add(function () {
  112027. _this.onBeforeBlurObservable.notifyObservers(_this);
  112028. var internalTexture = _this._blurTexture.getInternalTexture();
  112029. if (internalTexture) {
  112030. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  112031. }
  112032. _this.onAfterBlurObservable.notifyObservers(_this);
  112033. });
  112034. // Prevent autoClear.
  112035. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  112036. };
  112037. /**
  112038. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  112039. */
  112040. HighlightLayer.prototype.needStencil = function () {
  112041. return true;
  112042. };
  112043. /**
  112044. * Checks for the readiness of the element composing the layer.
  112045. * @param subMesh the mesh to check for
  112046. * @param useInstances specify wether or not to use instances to render the mesh
  112047. * @param emissiveTexture the associated emissive texture used to generate the glow
  112048. * @return true if ready otherwise, false
  112049. */
  112050. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  112051. var material = subMesh.getMaterial();
  112052. var mesh = subMesh.getRenderingMesh();
  112053. if (!material || !mesh || !this._meshes) {
  112054. return false;
  112055. }
  112056. var emissiveTexture = null;
  112057. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  112058. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  112059. emissiveTexture = material.emissiveTexture;
  112060. }
  112061. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  112062. };
  112063. /**
  112064. * Implementation specific of rendering the generating effect on the main canvas.
  112065. * @param effect The effect used to render through
  112066. */
  112067. HighlightLayer.prototype._internalRender = function (effect) {
  112068. // Texture
  112069. effect.setTexture("textureSampler", this._blurTexture);
  112070. // Cache
  112071. var engine = this._engine;
  112072. var previousStencilBuffer = engine.getStencilBuffer();
  112073. var previousStencilFunction = engine.getStencilFunction();
  112074. var previousStencilMask = engine.getStencilMask();
  112075. var previousStencilOperationPass = engine.getStencilOperationPass();
  112076. var previousStencilOperationFail = engine.getStencilOperationFail();
  112077. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  112078. var previousStencilReference = engine.getStencilFunctionReference();
  112079. // Stencil operations
  112080. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  112081. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  112082. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  112083. // Draw order
  112084. engine.setStencilMask(0x00);
  112085. engine.setStencilBuffer(true);
  112086. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  112087. // 2 passes inner outer
  112088. if (this.outerGlow) {
  112089. effect.setFloat("offset", 0);
  112090. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  112091. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  112092. }
  112093. if (this.innerGlow) {
  112094. effect.setFloat("offset", 1);
  112095. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  112096. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  112097. }
  112098. // Restore Cache
  112099. engine.setStencilFunction(previousStencilFunction);
  112100. engine.setStencilMask(previousStencilMask);
  112101. engine.setStencilBuffer(previousStencilBuffer);
  112102. engine.setStencilOperationPass(previousStencilOperationPass);
  112103. engine.setStencilOperationFail(previousStencilOperationFail);
  112104. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  112105. engine.setStencilFunctionReference(previousStencilReference);
  112106. };
  112107. /**
  112108. * Returns true if the layer contains information to display, otherwise false.
  112109. */
  112110. HighlightLayer.prototype.shouldRender = function () {
  112111. if (_super.prototype.shouldRender.call(this)) {
  112112. return this._meshes ? true : false;
  112113. }
  112114. return false;
  112115. };
  112116. /**
  112117. * Returns true if the mesh should render, otherwise false.
  112118. * @param mesh The mesh to render
  112119. * @returns true if it should render otherwise false
  112120. */
  112121. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  112122. // Excluded Mesh
  112123. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  112124. return false;
  112125. }
  112126. if (!_super.prototype.hasMesh.call(this, mesh)) {
  112127. return false;
  112128. }
  112129. return true;
  112130. };
  112131. /**
  112132. * Sets the required values for both the emissive texture and and the main color.
  112133. */
  112134. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  112135. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  112136. if (highlightLayerMesh) {
  112137. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  112138. }
  112139. else {
  112140. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  112141. }
  112142. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  112143. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  112144. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  112145. }
  112146. else {
  112147. this._emissiveTextureAndColor.texture = null;
  112148. }
  112149. };
  112150. /**
  112151. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  112152. * @param mesh The mesh to exclude from the highlight layer
  112153. */
  112154. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  112155. if (!this._excludedMeshes) {
  112156. return;
  112157. }
  112158. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  112159. if (!meshExcluded) {
  112160. this._excludedMeshes[mesh.uniqueId] = {
  112161. mesh: mesh,
  112162. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  112163. mesh.getEngine().setStencilBuffer(false);
  112164. }),
  112165. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  112166. mesh.getEngine().setStencilBuffer(true);
  112167. }),
  112168. };
  112169. }
  112170. };
  112171. /**
  112172. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  112173. * @param mesh The mesh to highlight
  112174. */
  112175. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  112176. if (!this._excludedMeshes) {
  112177. return;
  112178. }
  112179. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  112180. if (meshExcluded) {
  112181. if (meshExcluded.beforeRender) {
  112182. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  112183. }
  112184. if (meshExcluded.afterRender) {
  112185. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  112186. }
  112187. }
  112188. this._excludedMeshes[mesh.uniqueId] = null;
  112189. };
  112190. /**
  112191. * Determine if a given mesh will be highlighted by the current HighlightLayer
  112192. * @param mesh mesh to test
  112193. * @returns true if the mesh will be highlighted by the current HighlightLayer
  112194. */
  112195. HighlightLayer.prototype.hasMesh = function (mesh) {
  112196. if (!this._meshes) {
  112197. return false;
  112198. }
  112199. if (!_super.prototype.hasMesh.call(this, mesh)) {
  112200. return false;
  112201. }
  112202. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  112203. };
  112204. /**
  112205. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  112206. * @param mesh The mesh to highlight
  112207. * @param color The color of the highlight
  112208. * @param glowEmissiveOnly Extract the glow from the emissive texture
  112209. */
  112210. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  112211. var _this = this;
  112212. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  112213. if (!this._meshes) {
  112214. return;
  112215. }
  112216. var meshHighlight = this._meshes[mesh.uniqueId];
  112217. if (meshHighlight) {
  112218. meshHighlight.color = color;
  112219. }
  112220. else {
  112221. this._meshes[mesh.uniqueId] = {
  112222. mesh: mesh,
  112223. color: color,
  112224. // Lambda required for capture due to Observable this context
  112225. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  112226. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  112227. _this._defaultStencilReference(mesh);
  112228. }
  112229. else {
  112230. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  112231. }
  112232. }),
  112233. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  112234. glowEmissiveOnly: glowEmissiveOnly
  112235. };
  112236. mesh.onDisposeObservable.add(function () {
  112237. _this._disposeMesh(mesh);
  112238. });
  112239. }
  112240. this._shouldRender = true;
  112241. };
  112242. /**
  112243. * Remove a mesh from the highlight layer in order to make it stop glowing.
  112244. * @param mesh The mesh to highlight
  112245. */
  112246. HighlightLayer.prototype.removeMesh = function (mesh) {
  112247. if (!this._meshes) {
  112248. return;
  112249. }
  112250. var meshHighlight = this._meshes[mesh.uniqueId];
  112251. if (meshHighlight) {
  112252. if (meshHighlight.observerHighlight) {
  112253. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  112254. }
  112255. if (meshHighlight.observerDefault) {
  112256. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  112257. }
  112258. delete this._meshes[mesh.uniqueId];
  112259. }
  112260. this._shouldRender = false;
  112261. for (var meshHighlightToCheck in this._meshes) {
  112262. if (this._meshes[meshHighlightToCheck]) {
  112263. this._shouldRender = true;
  112264. break;
  112265. }
  112266. }
  112267. };
  112268. /**
  112269. * Force the stencil to the normal expected value for none glowing parts
  112270. */
  112271. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  112272. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  112273. };
  112274. /**
  112275. * Free any resources and references associated to a mesh.
  112276. * Internal use
  112277. * @param mesh The mesh to free.
  112278. * @hidden
  112279. */
  112280. HighlightLayer.prototype._disposeMesh = function (mesh) {
  112281. this.removeMesh(mesh);
  112282. this.removeExcludedMesh(mesh);
  112283. };
  112284. /**
  112285. * Dispose the highlight layer and free resources.
  112286. */
  112287. HighlightLayer.prototype.dispose = function () {
  112288. if (this._meshes) {
  112289. // Clean mesh references
  112290. for (var id in this._meshes) {
  112291. var meshHighlight = this._meshes[id];
  112292. if (meshHighlight && meshHighlight.mesh) {
  112293. if (meshHighlight.observerHighlight) {
  112294. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  112295. }
  112296. if (meshHighlight.observerDefault) {
  112297. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  112298. }
  112299. }
  112300. }
  112301. this._meshes = null;
  112302. }
  112303. if (this._excludedMeshes) {
  112304. for (var id in this._excludedMeshes) {
  112305. var meshHighlight = this._excludedMeshes[id];
  112306. if (meshHighlight) {
  112307. if (meshHighlight.beforeRender) {
  112308. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  112309. }
  112310. if (meshHighlight.afterRender) {
  112311. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  112312. }
  112313. }
  112314. }
  112315. this._excludedMeshes = null;
  112316. }
  112317. _super.prototype.dispose.call(this);
  112318. };
  112319. /**
  112320. * Gets the class name of the effect layer
  112321. * @returns the string with the class name of the effect layer
  112322. */
  112323. HighlightLayer.prototype.getClassName = function () {
  112324. return "HighlightLayer";
  112325. };
  112326. /**
  112327. * Serializes this Highlight layer
  112328. * @returns a serialized Highlight layer object
  112329. */
  112330. HighlightLayer.prototype.serialize = function () {
  112331. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  112332. serializationObject.customType = "BABYLON.HighlightLayer";
  112333. // Highlighted meshes
  112334. serializationObject.meshes = [];
  112335. if (this._meshes) {
  112336. for (var m in this._meshes) {
  112337. var mesh = this._meshes[m];
  112338. if (mesh) {
  112339. serializationObject.meshes.push({
  112340. glowEmissiveOnly: mesh.glowEmissiveOnly,
  112341. color: mesh.color.asArray(),
  112342. meshId: mesh.mesh.id
  112343. });
  112344. }
  112345. }
  112346. }
  112347. // Excluded meshes
  112348. serializationObject.excludedMeshes = [];
  112349. if (this._excludedMeshes) {
  112350. for (var e in this._excludedMeshes) {
  112351. var excludedMesh = this._excludedMeshes[e];
  112352. if (excludedMesh) {
  112353. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  112354. }
  112355. }
  112356. }
  112357. return serializationObject;
  112358. };
  112359. /**
  112360. * Creates a Highlight layer from parsed Highlight layer data
  112361. * @param parsedHightlightLayer defines the Highlight layer data
  112362. * @param scene defines the current scene
  112363. * @param rootUrl defines the root URL containing the Highlight layer information
  112364. * @returns a parsed Highlight layer
  112365. */
  112366. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  112367. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  112368. var index;
  112369. // Excluded meshes
  112370. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  112371. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  112372. if (mesh) {
  112373. hl.addExcludedMesh(mesh);
  112374. }
  112375. }
  112376. // Included meshes
  112377. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  112378. var highlightedMesh = parsedHightlightLayer.meshes[index];
  112379. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  112380. if (mesh) {
  112381. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  112382. }
  112383. }
  112384. return hl;
  112385. };
  112386. /**
  112387. * Effect Name of the highlight layer.
  112388. */
  112389. HighlightLayer.EffectName = "HighlightLayer";
  112390. /**
  112391. * The neutral color used during the preparation of the glow effect.
  112392. * This is black by default as the blend operation is a blend operation.
  112393. */
  112394. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  112395. /**
  112396. * Stencil value used for glowing meshes.
  112397. */
  112398. HighlightLayer.GlowingMeshStencilReference = 0x02;
  112399. /**
  112400. * Stencil value used for the other meshes in the scene.
  112401. */
  112402. HighlightLayer.NormalMeshStencilReference = 0x01;
  112403. __decorate([
  112404. BABYLON.serialize()
  112405. ], HighlightLayer.prototype, "innerGlow", void 0);
  112406. __decorate([
  112407. BABYLON.serialize()
  112408. ], HighlightLayer.prototype, "outerGlow", void 0);
  112409. __decorate([
  112410. BABYLON.serialize()
  112411. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  112412. __decorate([
  112413. BABYLON.serialize()
  112414. ], HighlightLayer.prototype, "blurVerticalSize", null);
  112415. __decorate([
  112416. BABYLON.serialize("options")
  112417. ], HighlightLayer.prototype, "_options", void 0);
  112418. return HighlightLayer;
  112419. }(BABYLON.EffectLayer));
  112420. BABYLON.HighlightLayer = HighlightLayer;
  112421. })(BABYLON || (BABYLON = {}));
  112422. //# sourceMappingURL=highlightLayer.js.map
  112423. var BABYLON;
  112424. (function (BABYLON) {
  112425. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  112426. for (var index = 0; index < this.effectLayers.length; index++) {
  112427. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  112428. return this.effectLayers[index];
  112429. }
  112430. }
  112431. return null;
  112432. };
  112433. /**
  112434. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  112435. *
  112436. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  112437. * glowy meshes to your scene.
  112438. *
  112439. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  112440. */
  112441. var GlowLayer = /** @class */ (function (_super) {
  112442. __extends(GlowLayer, _super);
  112443. /**
  112444. * Instantiates a new glow Layer and references it to the scene.
  112445. * @param name The name of the layer
  112446. * @param scene The scene to use the layer in
  112447. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  112448. */
  112449. function GlowLayer(name, scene, options) {
  112450. var _this = _super.call(this, name, scene) || this;
  112451. _this._intensity = 1.0;
  112452. _this._includedOnlyMeshes = [];
  112453. _this._excludedMeshes = [];
  112454. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  112455. // Adapt options
  112456. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  112457. // Initialize the layer
  112458. _this._init({
  112459. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  112460. camera: _this._options.camera,
  112461. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  112462. mainTextureRatio: _this._options.mainTextureRatio,
  112463. renderingGroupId: _this._options.renderingGroupId
  112464. });
  112465. return _this;
  112466. }
  112467. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  112468. /**
  112469. * Gets the kernel size of the blur.
  112470. */
  112471. get: function () {
  112472. return this._horizontalBlurPostprocess1.kernel;
  112473. },
  112474. /**
  112475. * Sets the kernel size of the blur.
  112476. */
  112477. set: function (value) {
  112478. this._horizontalBlurPostprocess1.kernel = value;
  112479. this._verticalBlurPostprocess1.kernel = value;
  112480. this._horizontalBlurPostprocess2.kernel = value;
  112481. this._verticalBlurPostprocess2.kernel = value;
  112482. },
  112483. enumerable: true,
  112484. configurable: true
  112485. });
  112486. Object.defineProperty(GlowLayer.prototype, "intensity", {
  112487. /**
  112488. * Gets the glow intensity.
  112489. */
  112490. get: function () {
  112491. return this._intensity;
  112492. },
  112493. /**
  112494. * Sets the glow intensity.
  112495. */
  112496. set: function (value) {
  112497. this._intensity = value;
  112498. },
  112499. enumerable: true,
  112500. configurable: true
  112501. });
  112502. /**
  112503. * Get the effect name of the layer.
  112504. * @return The effect name
  112505. */
  112506. GlowLayer.prototype.getEffectName = function () {
  112507. return GlowLayer.EffectName;
  112508. };
  112509. /**
  112510. * Create the merge effect. This is the shader use to blit the information back
  112511. * to the main canvas at the end of the scene rendering.
  112512. */
  112513. GlowLayer.prototype._createMergeEffect = function () {
  112514. // Effect
  112515. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  112516. };
  112517. /**
  112518. * Creates the render target textures and post processes used in the glow layer.
  112519. */
  112520. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  112521. var _this = this;
  112522. var blurTextureWidth = this._mainTextureDesiredSize.width;
  112523. var blurTextureHeight = this._mainTextureDesiredSize.height;
  112524. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  112525. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  112526. var textureType = 0;
  112527. if (this._engine.getCaps().textureHalfFloatRender) {
  112528. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  112529. }
  112530. else {
  112531. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  112532. }
  112533. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  112534. width: blurTextureWidth,
  112535. height: blurTextureHeight
  112536. }, this._scene, false, true, textureType);
  112537. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112538. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112539. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  112540. this._blurTexture1.renderParticles = false;
  112541. this._blurTexture1.ignoreCameraViewport = true;
  112542. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  112543. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  112544. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  112545. width: blurTextureWidth2,
  112546. height: blurTextureHeight2
  112547. }, this._scene, false, true, textureType);
  112548. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112549. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112550. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  112551. this._blurTexture2.renderParticles = false;
  112552. this._blurTexture2.ignoreCameraViewport = true;
  112553. this._textures = [this._blurTexture1, this._blurTexture2];
  112554. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  112555. width: blurTextureWidth,
  112556. height: blurTextureHeight
  112557. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  112558. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  112559. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  112560. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  112561. effect.setTexture("textureSampler", _this._mainTexture);
  112562. });
  112563. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  112564. width: blurTextureWidth,
  112565. height: blurTextureHeight
  112566. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  112567. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  112568. width: blurTextureWidth2,
  112569. height: blurTextureHeight2
  112570. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  112571. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  112572. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  112573. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  112574. effect.setTexture("textureSampler", _this._blurTexture1);
  112575. });
  112576. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  112577. width: blurTextureWidth2,
  112578. height: blurTextureHeight2
  112579. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  112580. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  112581. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  112582. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  112583. this._mainTexture.samples = this._options.mainTextureSamples;
  112584. this._mainTexture.onAfterUnbindObservable.add(function () {
  112585. var internalTexture = _this._blurTexture1.getInternalTexture();
  112586. if (internalTexture) {
  112587. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  112588. internalTexture = _this._blurTexture2.getInternalTexture();
  112589. if (internalTexture) {
  112590. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  112591. }
  112592. }
  112593. });
  112594. // Prevent autoClear.
  112595. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  112596. };
  112597. /**
  112598. * Checks for the readiness of the element composing the layer.
  112599. * @param subMesh the mesh to check for
  112600. * @param useInstances specify wether or not to use instances to render the mesh
  112601. * @param emissiveTexture the associated emissive texture used to generate the glow
  112602. * @return true if ready otherwise, false
  112603. */
  112604. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  112605. var material = subMesh.getMaterial();
  112606. var mesh = subMesh.getRenderingMesh();
  112607. if (!material || !mesh) {
  112608. return false;
  112609. }
  112610. var emissiveTexture = material.emissiveTexture;
  112611. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  112612. };
  112613. /**
  112614. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  112615. */
  112616. GlowLayer.prototype.needStencil = function () {
  112617. return false;
  112618. };
  112619. /**
  112620. * Implementation specific of rendering the generating effect on the main canvas.
  112621. * @param effect The effect used to render through
  112622. */
  112623. GlowLayer.prototype._internalRender = function (effect) {
  112624. // Texture
  112625. effect.setTexture("textureSampler", this._blurTexture1);
  112626. effect.setTexture("textureSampler2", this._blurTexture2);
  112627. effect.setFloat("offset", this._intensity);
  112628. // Cache
  112629. var engine = this._engine;
  112630. var previousStencilBuffer = engine.getStencilBuffer();
  112631. // Draw order
  112632. engine.setStencilBuffer(false);
  112633. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  112634. // Draw order
  112635. engine.setStencilBuffer(previousStencilBuffer);
  112636. };
  112637. /**
  112638. * Sets the required values for both the emissive texture and and the main color.
  112639. */
  112640. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  112641. var textureLevel = 1.0;
  112642. if (this.customEmissiveTextureSelector) {
  112643. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  112644. }
  112645. else {
  112646. if (material) {
  112647. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  112648. if (this._emissiveTextureAndColor.texture) {
  112649. textureLevel = this._emissiveTextureAndColor.texture.level;
  112650. }
  112651. }
  112652. else {
  112653. this._emissiveTextureAndColor.texture = null;
  112654. }
  112655. }
  112656. if (this.customEmissiveColorSelector) {
  112657. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  112658. }
  112659. else {
  112660. if (material.emissiveColor) {
  112661. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  112662. }
  112663. else {
  112664. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  112665. }
  112666. }
  112667. };
  112668. /**
  112669. * Returns true if the mesh should render, otherwise false.
  112670. * @param mesh The mesh to render
  112671. * @returns true if it should render otherwise false
  112672. */
  112673. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  112674. return this.hasMesh(mesh);
  112675. };
  112676. /**
  112677. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  112678. * @param mesh The mesh to exclude from the glow layer
  112679. */
  112680. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  112681. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  112682. this._excludedMeshes.push(mesh.uniqueId);
  112683. }
  112684. };
  112685. /**
  112686. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  112687. * @param mesh The mesh to remove
  112688. */
  112689. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  112690. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  112691. if (index !== -1) {
  112692. this._excludedMeshes.splice(index, 1);
  112693. }
  112694. };
  112695. /**
  112696. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  112697. * @param mesh The mesh to include in the glow layer
  112698. */
  112699. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  112700. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  112701. this._includedOnlyMeshes.push(mesh.uniqueId);
  112702. }
  112703. };
  112704. /**
  112705. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  112706. * @param mesh The mesh to remove
  112707. */
  112708. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  112709. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  112710. if (index !== -1) {
  112711. this._includedOnlyMeshes.splice(index, 1);
  112712. }
  112713. };
  112714. /**
  112715. * Determine if a given mesh will be used in the glow layer
  112716. * @param mesh The mesh to test
  112717. * @returns true if the mesh will be highlighted by the current glow layer
  112718. */
  112719. GlowLayer.prototype.hasMesh = function (mesh) {
  112720. if (!_super.prototype.hasMesh.call(this, mesh)) {
  112721. return false;
  112722. }
  112723. // Included Mesh
  112724. if (this._includedOnlyMeshes.length) {
  112725. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  112726. }
  112727. // Excluded Mesh
  112728. if (this._excludedMeshes.length) {
  112729. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  112730. }
  112731. return true;
  112732. };
  112733. /**
  112734. * Free any resources and references associated to a mesh.
  112735. * Internal use
  112736. * @param mesh The mesh to free.
  112737. * @hidden
  112738. */
  112739. GlowLayer.prototype._disposeMesh = function (mesh) {
  112740. this.removeIncludedOnlyMesh(mesh);
  112741. this.removeExcludedMesh(mesh);
  112742. };
  112743. /**
  112744. * Gets the class name of the effect layer
  112745. * @returns the string with the class name of the effect layer
  112746. */
  112747. GlowLayer.prototype.getClassName = function () {
  112748. return "GlowLayer";
  112749. };
  112750. /**
  112751. * Serializes this glow layer
  112752. * @returns a serialized glow layer object
  112753. */
  112754. GlowLayer.prototype.serialize = function () {
  112755. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  112756. serializationObject.customType = "BABYLON.GlowLayer";
  112757. var index;
  112758. // Included meshes
  112759. serializationObject.includedMeshes = [];
  112760. if (this._includedOnlyMeshes.length) {
  112761. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  112762. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  112763. if (mesh) {
  112764. serializationObject.includedMeshes.push(mesh.id);
  112765. }
  112766. }
  112767. }
  112768. // Excluded meshes
  112769. serializationObject.excludedMeshes = [];
  112770. if (this._excludedMeshes.length) {
  112771. for (index = 0; index < this._excludedMeshes.length; index++) {
  112772. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  112773. if (mesh) {
  112774. serializationObject.excludedMeshes.push(mesh.id);
  112775. }
  112776. }
  112777. }
  112778. return serializationObject;
  112779. };
  112780. /**
  112781. * Creates a Glow Layer from parsed glow layer data
  112782. * @param parsedGlowLayer defines glow layer data
  112783. * @param scene defines the current scene
  112784. * @param rootUrl defines the root URL containing the glow layer information
  112785. * @returns a parsed Glow Layer
  112786. */
  112787. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  112788. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  112789. var index;
  112790. // Excluded meshes
  112791. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  112792. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  112793. if (mesh) {
  112794. gl.addExcludedMesh(mesh);
  112795. }
  112796. }
  112797. // Included meshes
  112798. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  112799. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  112800. if (mesh) {
  112801. gl.addIncludedOnlyMesh(mesh);
  112802. }
  112803. }
  112804. return gl;
  112805. };
  112806. /**
  112807. * Effect Name of the layer.
  112808. */
  112809. GlowLayer.EffectName = "GlowLayer";
  112810. /**
  112811. * The default blur kernel size used for the glow.
  112812. */
  112813. GlowLayer.DefaultBlurKernelSize = 32;
  112814. /**
  112815. * The default texture size ratio used for the glow.
  112816. */
  112817. GlowLayer.DefaultTextureRatio = 0.5;
  112818. __decorate([
  112819. BABYLON.serialize()
  112820. ], GlowLayer.prototype, "blurKernelSize", null);
  112821. __decorate([
  112822. BABYLON.serialize()
  112823. ], GlowLayer.prototype, "intensity", null);
  112824. __decorate([
  112825. BABYLON.serialize("options")
  112826. ], GlowLayer.prototype, "_options", void 0);
  112827. return GlowLayer;
  112828. }(BABYLON.EffectLayer));
  112829. BABYLON.GlowLayer = GlowLayer;
  112830. })(BABYLON || (BABYLON = {}));
  112831. //# sourceMappingURL=glowLayer.js.map
  112832. var BABYLON;
  112833. (function (BABYLON) {
  112834. /**
  112835. * Defines the list of states available for a task inside a AssetsManager
  112836. */
  112837. var AssetTaskState;
  112838. (function (AssetTaskState) {
  112839. /**
  112840. * Initialization
  112841. */
  112842. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  112843. /**
  112844. * Running
  112845. */
  112846. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  112847. /**
  112848. * Done
  112849. */
  112850. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  112851. /**
  112852. * Error
  112853. */
  112854. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  112855. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  112856. /**
  112857. * Define an abstract asset task used with a AssetsManager class to load assets into a scene
  112858. */
  112859. var AbstractAssetTask = /** @class */ (function () {
  112860. /**
  112861. * Creates a new AssetsManager
  112862. * @param name defines the name of the task
  112863. */
  112864. function AbstractAssetTask(
  112865. /**
  112866. * Task name
  112867. */ name) {
  112868. this.name = name;
  112869. this._isCompleted = false;
  112870. this._taskState = AssetTaskState.INIT;
  112871. }
  112872. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  112873. /**
  112874. * Get if the task is completed
  112875. */
  112876. get: function () {
  112877. return this._isCompleted;
  112878. },
  112879. enumerable: true,
  112880. configurable: true
  112881. });
  112882. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  112883. /**
  112884. * Gets the current state of the task
  112885. */
  112886. get: function () {
  112887. return this._taskState;
  112888. },
  112889. enumerable: true,
  112890. configurable: true
  112891. });
  112892. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  112893. /**
  112894. * Gets the current error object (if task is in error)
  112895. */
  112896. get: function () {
  112897. return this._errorObject;
  112898. },
  112899. enumerable: true,
  112900. configurable: true
  112901. });
  112902. /**
  112903. * Internal only
  112904. * @hidden
  112905. */
  112906. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  112907. if (this._errorObject) {
  112908. return;
  112909. }
  112910. this._errorObject = {
  112911. message: message,
  112912. exception: exception
  112913. };
  112914. };
  112915. /**
  112916. * Execute the current task
  112917. * @param scene defines the scene where you want your assets to be loaded
  112918. * @param onSuccess is a callback called when the task is successfully executed
  112919. * @param onError is a callback called if an error occurs
  112920. */
  112921. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  112922. var _this = this;
  112923. this._taskState = AssetTaskState.RUNNING;
  112924. this.runTask(scene, function () {
  112925. _this.onDoneCallback(onSuccess, onError);
  112926. }, function (msg, exception) {
  112927. _this.onErrorCallback(onError, msg, exception);
  112928. });
  112929. };
  112930. /**
  112931. * Execute the current task
  112932. * @param scene defines the scene where you want your assets to be loaded
  112933. * @param onSuccess is a callback called when the task is successfully executed
  112934. * @param onError is a callback called if an error occurs
  112935. */
  112936. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  112937. throw new Error("runTask is not implemented");
  112938. };
  112939. /**
  112940. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  112941. * This can be used with failed tasks that have the reason for failure fixed.
  112942. */
  112943. AbstractAssetTask.prototype.reset = function () {
  112944. this._taskState = AssetTaskState.INIT;
  112945. };
  112946. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  112947. this._taskState = AssetTaskState.ERROR;
  112948. this._errorObject = {
  112949. message: message,
  112950. exception: exception
  112951. };
  112952. if (this.onError) {
  112953. this.onError(this, message, exception);
  112954. }
  112955. onError();
  112956. };
  112957. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  112958. try {
  112959. this._taskState = AssetTaskState.DONE;
  112960. this._isCompleted = true;
  112961. if (this.onSuccess) {
  112962. this.onSuccess(this);
  112963. }
  112964. onSuccess();
  112965. }
  112966. catch (e) {
  112967. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  112968. }
  112969. };
  112970. return AbstractAssetTask;
  112971. }());
  112972. BABYLON.AbstractAssetTask = AbstractAssetTask;
  112973. /**
  112974. * Class used to share progress information about assets loading
  112975. */
  112976. var AssetsProgressEvent = /** @class */ (function () {
  112977. /**
  112978. * Creates a AssetsProgressEvent
  112979. * @param remainingCount defines the number of remaining tasks to process
  112980. * @param totalCount defines the total number of tasks
  112981. * @param task defines the task that was just processed
  112982. */
  112983. function AssetsProgressEvent(remainingCount, totalCount, task) {
  112984. this.remainingCount = remainingCount;
  112985. this.totalCount = totalCount;
  112986. this.task = task;
  112987. }
  112988. return AssetsProgressEvent;
  112989. }());
  112990. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  112991. /**
  112992. * Define a task used by AssetsManager to load meshes
  112993. */
  112994. var MeshAssetTask = /** @class */ (function (_super) {
  112995. __extends(MeshAssetTask, _super);
  112996. /**
  112997. * Creates a new MeshAssetTask
  112998. * @param name defines the name of the task
  112999. * @param meshesNames defines the list of mesh's names you want to load
  113000. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  113001. * @param sceneFilename defines the filename of the scene to load from
  113002. */
  113003. function MeshAssetTask(
  113004. /**
  113005. * Defines the name of the task
  113006. */
  113007. name,
  113008. /**
  113009. * Defines the list of mesh's names you want to load
  113010. */
  113011. meshesNames,
  113012. /**
  113013. * Defines the root url to use as a base to load your meshes and associated resources
  113014. */
  113015. rootUrl,
  113016. /**
  113017. * Defines the filename of the scene to load from
  113018. */
  113019. sceneFilename) {
  113020. var _this = _super.call(this, name) || this;
  113021. _this.name = name;
  113022. _this.meshesNames = meshesNames;
  113023. _this.rootUrl = rootUrl;
  113024. _this.sceneFilename = sceneFilename;
  113025. return _this;
  113026. }
  113027. /**
  113028. * Execute the current task
  113029. * @param scene defines the scene where you want your assets to be loaded
  113030. * @param onSuccess is a callback called when the task is successfully executed
  113031. * @param onError is a callback called if an error occurs
  113032. */
  113033. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  113034. var _this = this;
  113035. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  113036. _this.loadedMeshes = meshes;
  113037. _this.loadedParticleSystems = particleSystems;
  113038. _this.loadedSkeletons = skeletons;
  113039. onSuccess();
  113040. }, null, function (scene, message, exception) {
  113041. onError(message, exception);
  113042. });
  113043. };
  113044. return MeshAssetTask;
  113045. }(AbstractAssetTask));
  113046. BABYLON.MeshAssetTask = MeshAssetTask;
  113047. /**
  113048. * Define a task used by AssetsManager to load text content
  113049. */
  113050. var TextFileAssetTask = /** @class */ (function (_super) {
  113051. __extends(TextFileAssetTask, _super);
  113052. /**
  113053. * Creates a new TextFileAssetTask object
  113054. * @param name defines the name of the task
  113055. * @param url defines the location of the file to load
  113056. */
  113057. function TextFileAssetTask(
  113058. /**
  113059. * Defines the name of the task
  113060. */
  113061. name,
  113062. /**
  113063. * Defines the location of the file to load
  113064. */
  113065. url) {
  113066. var _this = _super.call(this, name) || this;
  113067. _this.name = name;
  113068. _this.url = url;
  113069. return _this;
  113070. }
  113071. /**
  113072. * Execute the current task
  113073. * @param scene defines the scene where you want your assets to be loaded
  113074. * @param onSuccess is a callback called when the task is successfully executed
  113075. * @param onError is a callback called if an error occurs
  113076. */
  113077. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  113078. var _this = this;
  113079. scene._loadFile(this.url, function (data) {
  113080. _this.text = data;
  113081. onSuccess();
  113082. }, undefined, false, false, function (request, exception) {
  113083. if (request) {
  113084. onError(request.status + " " + request.statusText, exception);
  113085. }
  113086. });
  113087. };
  113088. return TextFileAssetTask;
  113089. }(AbstractAssetTask));
  113090. BABYLON.TextFileAssetTask = TextFileAssetTask;
  113091. /**
  113092. * Define a task used by AssetsManager to load binary data
  113093. */
  113094. var BinaryFileAssetTask = /** @class */ (function (_super) {
  113095. __extends(BinaryFileAssetTask, _super);
  113096. /**
  113097. * Creates a new BinaryFileAssetTask object
  113098. * @param name defines the name of the new task
  113099. * @param url defines the location of the file to load
  113100. */
  113101. function BinaryFileAssetTask(
  113102. /**
  113103. * Defines the name of the task
  113104. */
  113105. name,
  113106. /**
  113107. * Defines the location of the file to load
  113108. */
  113109. url) {
  113110. var _this = _super.call(this, name) || this;
  113111. _this.name = name;
  113112. _this.url = url;
  113113. return _this;
  113114. }
  113115. /**
  113116. * Execute the current task
  113117. * @param scene defines the scene where you want your assets to be loaded
  113118. * @param onSuccess is a callback called when the task is successfully executed
  113119. * @param onError is a callback called if an error occurs
  113120. */
  113121. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  113122. var _this = this;
  113123. scene._loadFile(this.url, function (data) {
  113124. _this.data = data;
  113125. onSuccess();
  113126. }, undefined, true, true, function (request, exception) {
  113127. if (request) {
  113128. onError(request.status + " " + request.statusText, exception);
  113129. }
  113130. });
  113131. };
  113132. return BinaryFileAssetTask;
  113133. }(AbstractAssetTask));
  113134. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  113135. /**
  113136. * Define a task used by AssetsManager to load images
  113137. */
  113138. var ImageAssetTask = /** @class */ (function (_super) {
  113139. __extends(ImageAssetTask, _super);
  113140. /**
  113141. * Creates a new ImageAssetTask
  113142. * @param name defines the name of the task
  113143. * @param url defines the location of the image to load
  113144. */
  113145. function ImageAssetTask(
  113146. /**
  113147. * Defines the name of the task
  113148. */
  113149. name,
  113150. /**
  113151. * Defines the location of the image to load
  113152. */
  113153. url) {
  113154. var _this = _super.call(this, name) || this;
  113155. _this.name = name;
  113156. _this.url = url;
  113157. return _this;
  113158. }
  113159. /**
  113160. * Execute the current task
  113161. * @param scene defines the scene where you want your assets to be loaded
  113162. * @param onSuccess is a callback called when the task is successfully executed
  113163. * @param onError is a callback called if an error occurs
  113164. */
  113165. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  113166. var _this = this;
  113167. var img = new Image();
  113168. BABYLON.Tools.SetCorsBehavior(this.url, img);
  113169. img.onload = function () {
  113170. _this.image = img;
  113171. onSuccess();
  113172. };
  113173. img.onerror = function (err) {
  113174. onError("Error loading image", err);
  113175. };
  113176. img.src = this.url;
  113177. };
  113178. return ImageAssetTask;
  113179. }(AbstractAssetTask));
  113180. BABYLON.ImageAssetTask = ImageAssetTask;
  113181. /**
  113182. * Define a task used by AssetsManager to load 2D textures
  113183. */
  113184. var TextureAssetTask = /** @class */ (function (_super) {
  113185. __extends(TextureAssetTask, _super);
  113186. /**
  113187. * Creates a new TextureAssetTask object
  113188. * @param name defines the name of the task
  113189. * @param url defines the location of the file to load
  113190. * @param noMipmap defines if mipmap should not be generated (default is false)
  113191. * @param invertY defines if texture must be inverted on Y axis (default is false)
  113192. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  113193. */
  113194. function TextureAssetTask(
  113195. /**
  113196. * Defines the name of the task
  113197. */
  113198. name,
  113199. /**
  113200. * Defines the location of the file to load
  113201. */
  113202. url,
  113203. /**
  113204. * Defines if mipmap should not be generated (default is false)
  113205. */
  113206. noMipmap,
  113207. /**
  113208. * Defines if texture must be inverted on Y axis (default is false)
  113209. */
  113210. invertY,
  113211. /**
  113212. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  113213. */
  113214. samplingMode) {
  113215. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  113216. var _this = _super.call(this, name) || this;
  113217. _this.name = name;
  113218. _this.url = url;
  113219. _this.noMipmap = noMipmap;
  113220. _this.invertY = invertY;
  113221. _this.samplingMode = samplingMode;
  113222. return _this;
  113223. }
  113224. /**
  113225. * Execute the current task
  113226. * @param scene defines the scene where you want your assets to be loaded
  113227. * @param onSuccess is a callback called when the task is successfully executed
  113228. * @param onError is a callback called if an error occurs
  113229. */
  113230. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  113231. var onload = function () {
  113232. onSuccess();
  113233. };
  113234. var onerror = function (message, exception) {
  113235. onError(message, exception);
  113236. };
  113237. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  113238. };
  113239. return TextureAssetTask;
  113240. }(AbstractAssetTask));
  113241. BABYLON.TextureAssetTask = TextureAssetTask;
  113242. /**
  113243. * Define a task used by AssetsManager to load cube textures
  113244. */
  113245. var CubeTextureAssetTask = /** @class */ (function (_super) {
  113246. __extends(CubeTextureAssetTask, _super);
  113247. /**
  113248. * Creates a new CubeTextureAssetTask
  113249. * @param name defines the name of the task
  113250. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  113251. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  113252. * @param noMipmap defines if mipmaps should not be generated (default is false)
  113253. * @param files defines the explicit list of files (undefined by default)
  113254. */
  113255. function CubeTextureAssetTask(
  113256. /**
  113257. * Defines the name of the task
  113258. */
  113259. name,
  113260. /**
  113261. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  113262. */
  113263. url,
  113264. /**
  113265. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  113266. */
  113267. extensions,
  113268. /**
  113269. * Defines if mipmaps should not be generated (default is false)
  113270. */
  113271. noMipmap,
  113272. /**
  113273. * Defines the explicit list of files (undefined by default)
  113274. */
  113275. files) {
  113276. var _this = _super.call(this, name) || this;
  113277. _this.name = name;
  113278. _this.url = url;
  113279. _this.extensions = extensions;
  113280. _this.noMipmap = noMipmap;
  113281. _this.files = files;
  113282. return _this;
  113283. }
  113284. /**
  113285. * Execute the current task
  113286. * @param scene defines the scene where you want your assets to be loaded
  113287. * @param onSuccess is a callback called when the task is successfully executed
  113288. * @param onError is a callback called if an error occurs
  113289. */
  113290. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  113291. var onload = function () {
  113292. onSuccess();
  113293. };
  113294. var onerror = function (message, exception) {
  113295. onError(message, exception);
  113296. };
  113297. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  113298. };
  113299. return CubeTextureAssetTask;
  113300. }(AbstractAssetTask));
  113301. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  113302. /**
  113303. * Define a task used by AssetsManager to load HDR cube textures
  113304. */
  113305. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  113306. __extends(HDRCubeTextureAssetTask, _super);
  113307. /**
  113308. * Creates a new HDRCubeTextureAssetTask object
  113309. * @param name defines the name of the task
  113310. * @param url defines the location of the file to load
  113311. * @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.
  113312. * @param noMipmap defines if mipmaps should not be generated (default is false)
  113313. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  113314. * @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)
  113315. * @param reserved Internal use only
  113316. */
  113317. function HDRCubeTextureAssetTask(
  113318. /**
  113319. * Defines the name of the task
  113320. */
  113321. name,
  113322. /**
  113323. * Defines the location of the file to load
  113324. */
  113325. url,
  113326. /**
  113327. * Defines the desired size (the more it increases the longer the generation will be)
  113328. */
  113329. size,
  113330. /**
  113331. * Defines if mipmaps should not be generated (default is false)
  113332. */
  113333. noMipmap,
  113334. /**
  113335. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  113336. */
  113337. generateHarmonics,
  113338. /**
  113339. * 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)
  113340. */
  113341. gammaSpace,
  113342. /**
  113343. * Internal Use Only
  113344. */
  113345. reserved) {
  113346. if (noMipmap === void 0) { noMipmap = false; }
  113347. if (generateHarmonics === void 0) { generateHarmonics = true; }
  113348. if (gammaSpace === void 0) { gammaSpace = false; }
  113349. if (reserved === void 0) { reserved = false; }
  113350. var _this = _super.call(this, name) || this;
  113351. _this.name = name;
  113352. _this.url = url;
  113353. _this.size = size;
  113354. _this.noMipmap = noMipmap;
  113355. _this.generateHarmonics = generateHarmonics;
  113356. _this.gammaSpace = gammaSpace;
  113357. _this.reserved = reserved;
  113358. return _this;
  113359. }
  113360. /**
  113361. * Execute the current task
  113362. * @param scene defines the scene where you want your assets to be loaded
  113363. * @param onSuccess is a callback called when the task is successfully executed
  113364. * @param onError is a callback called if an error occurs
  113365. */
  113366. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  113367. var onload = function () {
  113368. onSuccess();
  113369. };
  113370. var onerror = function (message, exception) {
  113371. onError(message, exception);
  113372. };
  113373. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  113374. };
  113375. return HDRCubeTextureAssetTask;
  113376. }(AbstractAssetTask));
  113377. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  113378. /**
  113379. * This class can be used to easily import assets into a scene
  113380. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  113381. */
  113382. var AssetsManager = /** @class */ (function () {
  113383. /**
  113384. * Creates a new AssetsManager
  113385. * @param scene defines the scene to work on
  113386. */
  113387. function AssetsManager(scene) {
  113388. this._isLoading = false;
  113389. this._tasks = new Array();
  113390. this._waitingTasksCount = 0;
  113391. this._totalTasksCount = 0;
  113392. /**
  113393. * Observable called when all tasks are processed
  113394. */
  113395. this.onTaskSuccessObservable = new BABYLON.Observable();
  113396. /**
  113397. * Observable called when a task had an error
  113398. */
  113399. this.onTaskErrorObservable = new BABYLON.Observable();
  113400. /**
  113401. * Observable called when a task is successful
  113402. */
  113403. this.onTasksDoneObservable = new BABYLON.Observable();
  113404. /**
  113405. * Observable called when a task is done (whatever the result is)
  113406. */
  113407. this.onProgressObservable = new BABYLON.Observable();
  113408. /**
  113409. * Gets or sets a boolean defining if the AssetsManager should use the default loading screen
  113410. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  113411. */
  113412. this.useDefaultLoadingScreen = true;
  113413. this._scene = scene;
  113414. }
  113415. /**
  113416. * Add a MeshAssetTask to the list of active tasks
  113417. * @param taskName defines the name of the new task
  113418. * @param meshesNames defines the name of meshes to load
  113419. * @param rootUrl defines the root url to use to locate files
  113420. * @param sceneFilename defines the filename of the scene file
  113421. * @returns a new MeshAssetTask object
  113422. */
  113423. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  113424. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  113425. this._tasks.push(task);
  113426. return task;
  113427. };
  113428. /**
  113429. * Add a TextFileAssetTask to the list of active tasks
  113430. * @param taskName defines the name of the new task
  113431. * @param url defines the url of the file to load
  113432. * @returns a new TextFileAssetTask object
  113433. */
  113434. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  113435. var task = new TextFileAssetTask(taskName, url);
  113436. this._tasks.push(task);
  113437. return task;
  113438. };
  113439. /**
  113440. * Add a BinaryFileAssetTask to the list of active tasks
  113441. * @param taskName defines the name of the new task
  113442. * @param url defines the url of the file to load
  113443. * @returns a new BinaryFileAssetTask object
  113444. */
  113445. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  113446. var task = new BinaryFileAssetTask(taskName, url);
  113447. this._tasks.push(task);
  113448. return task;
  113449. };
  113450. /**
  113451. * Add a ImageAssetTask to the list of active tasks
  113452. * @param taskName defines the name of the new task
  113453. * @param url defines the url of the file to load
  113454. * @returns a new ImageAssetTask object
  113455. */
  113456. AssetsManager.prototype.addImageTask = function (taskName, url) {
  113457. var task = new ImageAssetTask(taskName, url);
  113458. this._tasks.push(task);
  113459. return task;
  113460. };
  113461. /**
  113462. * Add a TextureAssetTask to the list of active tasks
  113463. * @param taskName defines the name of the new task
  113464. * @param url defines the url of the file to load
  113465. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  113466. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  113467. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  113468. * @returns a new TextureAssetTask object
  113469. */
  113470. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  113471. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  113472. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  113473. this._tasks.push(task);
  113474. return task;
  113475. };
  113476. /**
  113477. * Add a CubeTextureAssetTask to the list of active tasks
  113478. * @param taskName defines the name of the new task
  113479. * @param url defines the url of the file to load
  113480. * @param extensions defines the extension to use to load the cube map (can be null)
  113481. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  113482. * @param files defines the list of files to load (can be null)
  113483. * @returns a new CubeTextureAssetTask object
  113484. */
  113485. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  113486. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  113487. this._tasks.push(task);
  113488. return task;
  113489. };
  113490. /**
  113491. *
  113492. * Add a HDRCubeTextureAssetTask to the list of active tasks
  113493. * @param taskName defines the name of the new task
  113494. * @param url defines the url of the file to load
  113495. * @param size defines the size you want for the cubemap (can be null)
  113496. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  113497. * @param generateHarmonics defines if you want to automatically generate (true by default)
  113498. * @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)
  113499. * @param reserved Internal use only
  113500. * @returns a new HDRCubeTextureAssetTask object
  113501. */
  113502. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  113503. if (noMipmap === void 0) { noMipmap = false; }
  113504. if (generateHarmonics === void 0) { generateHarmonics = true; }
  113505. if (gammaSpace === void 0) { gammaSpace = false; }
  113506. if (reserved === void 0) { reserved = false; }
  113507. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  113508. this._tasks.push(task);
  113509. return task;
  113510. };
  113511. /**
  113512. * Remove a task from the assets manager.
  113513. * @param task the task to remove
  113514. */
  113515. AssetsManager.prototype.removeTask = function (task) {
  113516. var index = this._tasks.indexOf(task);
  113517. if (index > -1) {
  113518. this._tasks.splice(index, 1);
  113519. }
  113520. };
  113521. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  113522. this._waitingTasksCount--;
  113523. try {
  113524. if (this.onProgress) {
  113525. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  113526. }
  113527. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  113528. }
  113529. catch (e) {
  113530. BABYLON.Tools.Error("Error running progress callbacks.");
  113531. console.log(e);
  113532. }
  113533. if (this._waitingTasksCount === 0) {
  113534. try {
  113535. if (this.onFinish) {
  113536. this.onFinish(this._tasks);
  113537. }
  113538. // Let's remove successfull tasks
  113539. var currentTasks = this._tasks.slice();
  113540. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  113541. var task = currentTasks_1[_i];
  113542. if (task.taskState === AssetTaskState.DONE) {
  113543. var index = this._tasks.indexOf(task);
  113544. if (index > -1) {
  113545. this._tasks.splice(index, 1);
  113546. }
  113547. }
  113548. }
  113549. this.onTasksDoneObservable.notifyObservers(this._tasks);
  113550. }
  113551. catch (e) {
  113552. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  113553. console.log(e);
  113554. }
  113555. this._isLoading = false;
  113556. this._scene.getEngine().hideLoadingUI();
  113557. }
  113558. };
  113559. AssetsManager.prototype._runTask = function (task) {
  113560. var _this = this;
  113561. var done = function () {
  113562. try {
  113563. if (_this.onTaskSuccess) {
  113564. _this.onTaskSuccess(task);
  113565. }
  113566. _this.onTaskSuccessObservable.notifyObservers(task);
  113567. _this._decreaseWaitingTasksCount(task);
  113568. }
  113569. catch (e) {
  113570. error("Error executing task success callbacks", e);
  113571. }
  113572. };
  113573. var error = function (message, exception) {
  113574. task._setErrorObject(message, exception);
  113575. if (_this.onTaskError) {
  113576. _this.onTaskError(task);
  113577. }
  113578. _this.onTaskErrorObservable.notifyObservers(task);
  113579. _this._decreaseWaitingTasksCount(task);
  113580. };
  113581. task.run(this._scene, done, error);
  113582. };
  113583. /**
  113584. * Reset the AssetsManager and remove all tasks
  113585. * @return the current instance of the AssetsManager
  113586. */
  113587. AssetsManager.prototype.reset = function () {
  113588. this._isLoading = false;
  113589. this._tasks = new Array();
  113590. return this;
  113591. };
  113592. /**
  113593. * Start the loading process
  113594. * @return the current instance of the AssetsManager
  113595. */
  113596. AssetsManager.prototype.load = function () {
  113597. if (this._isLoading) {
  113598. return this;
  113599. }
  113600. this._isLoading = true;
  113601. this._waitingTasksCount = this._tasks.length;
  113602. this._totalTasksCount = this._tasks.length;
  113603. if (this._waitingTasksCount === 0) {
  113604. this._isLoading = false;
  113605. if (this.onFinish) {
  113606. this.onFinish(this._tasks);
  113607. }
  113608. this.onTasksDoneObservable.notifyObservers(this._tasks);
  113609. return this;
  113610. }
  113611. if (this.useDefaultLoadingScreen) {
  113612. this._scene.getEngine().displayLoadingUI();
  113613. }
  113614. for (var index = 0; index < this._tasks.length; index++) {
  113615. var task = this._tasks[index];
  113616. if (task.taskState === AssetTaskState.INIT) {
  113617. this._runTask(task);
  113618. }
  113619. }
  113620. return this;
  113621. };
  113622. return AssetsManager;
  113623. }());
  113624. BABYLON.AssetsManager = AssetsManager;
  113625. })(BABYLON || (BABYLON = {}));
  113626. //# sourceMappingURL=assetsManager.js.map
  113627. var BABYLON;
  113628. (function (BABYLON) {
  113629. var serializedGeometries = [];
  113630. var serializeGeometry = function (geometry, serializationGeometries) {
  113631. if (serializedGeometries[geometry.id]) {
  113632. return;
  113633. }
  113634. if (geometry.doNotSerialize) {
  113635. return;
  113636. }
  113637. if (geometry instanceof BABYLON.BoxGeometry) {
  113638. serializationGeometries.boxes.push(geometry.serialize());
  113639. }
  113640. else if (geometry instanceof BABYLON.SphereGeometry) {
  113641. serializationGeometries.spheres.push(geometry.serialize());
  113642. }
  113643. else if (geometry instanceof BABYLON.CylinderGeometry) {
  113644. serializationGeometries.cylinders.push(geometry.serialize());
  113645. }
  113646. else if (geometry instanceof BABYLON.TorusGeometry) {
  113647. serializationGeometries.toruses.push(geometry.serialize());
  113648. }
  113649. else if (geometry instanceof BABYLON.GroundGeometry) {
  113650. serializationGeometries.grounds.push(geometry.serialize());
  113651. }
  113652. else if (geometry instanceof BABYLON.Plane) {
  113653. serializationGeometries.planes.push(geometry.serialize());
  113654. }
  113655. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  113656. serializationGeometries.torusKnots.push(geometry.serialize());
  113657. }
  113658. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  113659. throw new Error("Unknown primitive type");
  113660. }
  113661. else {
  113662. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  113663. }
  113664. serializedGeometries[geometry.id] = true;
  113665. };
  113666. var serializeMesh = function (mesh, serializationScene) {
  113667. var serializationObject = {};
  113668. // Geometry
  113669. var geometry = mesh._geometry;
  113670. if (geometry) {
  113671. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  113672. // 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
  113673. serializeGeometry(geometry, serializationScene.geometries);
  113674. }
  113675. }
  113676. // Custom
  113677. if (mesh.serialize) {
  113678. mesh.serialize(serializationObject);
  113679. }
  113680. return serializationObject;
  113681. };
  113682. var finalizeSingleMesh = function (mesh, serializationObject) {
  113683. //only works if the mesh is already loaded
  113684. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  113685. //serialize material
  113686. if (mesh.material) {
  113687. if (mesh.material instanceof BABYLON.MultiMaterial) {
  113688. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  113689. serializationObject.materials = serializationObject.materials || [];
  113690. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  113691. serializationObject.multiMaterials.push(mesh.material.serialize());
  113692. var _loop_1 = function (submaterial) {
  113693. if (submaterial) {
  113694. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  113695. serializationObject.materials.push(submaterial.serialize());
  113696. }
  113697. }
  113698. };
  113699. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  113700. var submaterial = _a[_i];
  113701. _loop_1(submaterial);
  113702. }
  113703. }
  113704. }
  113705. else {
  113706. serializationObject.materials = serializationObject.materials || [];
  113707. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  113708. serializationObject.materials.push(mesh.material.serialize());
  113709. }
  113710. }
  113711. }
  113712. //serialize geometry
  113713. var geometry = mesh._geometry;
  113714. if (geometry) {
  113715. if (!serializationObject.geometries) {
  113716. serializationObject.geometries = {};
  113717. serializationObject.geometries.boxes = [];
  113718. serializationObject.geometries.spheres = [];
  113719. serializationObject.geometries.cylinders = [];
  113720. serializationObject.geometries.toruses = [];
  113721. serializationObject.geometries.grounds = [];
  113722. serializationObject.geometries.planes = [];
  113723. serializationObject.geometries.torusKnots = [];
  113724. serializationObject.geometries.vertexData = [];
  113725. }
  113726. serializeGeometry(geometry, serializationObject.geometries);
  113727. }
  113728. // Skeletons
  113729. if (mesh.skeleton) {
  113730. serializationObject.skeletons = serializationObject.skeletons || [];
  113731. serializationObject.skeletons.push(mesh.skeleton.serialize());
  113732. }
  113733. //serialize the actual mesh
  113734. serializationObject.meshes = serializationObject.meshes || [];
  113735. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  113736. }
  113737. };
  113738. /**
  113739. * Class used to serialize a scene into a string
  113740. */
  113741. var SceneSerializer = /** @class */ (function () {
  113742. function SceneSerializer() {
  113743. }
  113744. /**
  113745. * Clear cache used by a previous serialization
  113746. */
  113747. SceneSerializer.ClearCache = function () {
  113748. serializedGeometries = [];
  113749. };
  113750. /**
  113751. * Serialize a scene into a JSON compatible object
  113752. * @param scene defines the scene to serialize
  113753. * @returns a JSON compatible object
  113754. */
  113755. SceneSerializer.Serialize = function (scene) {
  113756. var serializationObject = {};
  113757. SceneSerializer.ClearCache();
  113758. // Scene
  113759. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  113760. serializationObject.autoClear = scene.autoClear;
  113761. serializationObject.clearColor = scene.clearColor.asArray();
  113762. serializationObject.ambientColor = scene.ambientColor.asArray();
  113763. serializationObject.gravity = scene.gravity.asArray();
  113764. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  113765. serializationObject.workerCollisions = scene.workerCollisions;
  113766. // Fog
  113767. if (scene.fogMode && scene.fogMode !== 0) {
  113768. serializationObject.fogMode = scene.fogMode;
  113769. serializationObject.fogColor = scene.fogColor.asArray();
  113770. serializationObject.fogStart = scene.fogStart;
  113771. serializationObject.fogEnd = scene.fogEnd;
  113772. serializationObject.fogDensity = scene.fogDensity;
  113773. }
  113774. //Physics
  113775. if (scene.isPhysicsEnabled()) {
  113776. var physicEngine = scene.getPhysicsEngine();
  113777. if (physicEngine) {
  113778. serializationObject.physicsEnabled = true;
  113779. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  113780. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  113781. }
  113782. }
  113783. // Metadata
  113784. if (scene.metadata) {
  113785. serializationObject.metadata = scene.metadata;
  113786. }
  113787. // Morph targets
  113788. serializationObject.morphTargetManagers = [];
  113789. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  113790. var abstractMesh = _a[_i];
  113791. var manager = abstractMesh.morphTargetManager;
  113792. if (manager) {
  113793. serializationObject.morphTargetManagers.push(manager.serialize());
  113794. }
  113795. }
  113796. // Lights
  113797. serializationObject.lights = [];
  113798. var index;
  113799. var light;
  113800. for (index = 0; index < scene.lights.length; index++) {
  113801. light = scene.lights[index];
  113802. if (!light.doNotSerialize) {
  113803. serializationObject.lights.push(light.serialize());
  113804. }
  113805. }
  113806. // Cameras
  113807. serializationObject.cameras = [];
  113808. for (index = 0; index < scene.cameras.length; index++) {
  113809. var camera = scene.cameras[index];
  113810. if (!camera.doNotSerialize) {
  113811. serializationObject.cameras.push(camera.serialize());
  113812. }
  113813. }
  113814. if (scene.activeCamera) {
  113815. serializationObject.activeCameraID = scene.activeCamera.id;
  113816. }
  113817. // Animations
  113818. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  113819. // Materials
  113820. serializationObject.materials = [];
  113821. serializationObject.multiMaterials = [];
  113822. var material;
  113823. for (index = 0; index < scene.materials.length; index++) {
  113824. material = scene.materials[index];
  113825. if (!material.doNotSerialize) {
  113826. serializationObject.materials.push(material.serialize());
  113827. }
  113828. }
  113829. // MultiMaterials
  113830. serializationObject.multiMaterials = [];
  113831. for (index = 0; index < scene.multiMaterials.length; index++) {
  113832. var multiMaterial = scene.multiMaterials[index];
  113833. serializationObject.multiMaterials.push(multiMaterial.serialize());
  113834. }
  113835. // Environment texture
  113836. if (scene.environmentTexture) {
  113837. serializationObject.environmentTexture = scene.environmentTexture.name;
  113838. }
  113839. // Skeletons
  113840. serializationObject.skeletons = [];
  113841. for (index = 0; index < scene.skeletons.length; index++) {
  113842. var skeleton = scene.skeletons[index];
  113843. if (!skeleton.doNotSerialize) {
  113844. serializationObject.skeletons.push(skeleton.serialize());
  113845. }
  113846. }
  113847. // Transform nodes
  113848. serializationObject.transformNodes = [];
  113849. for (index = 0; index < scene.transformNodes.length; index++) {
  113850. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  113851. }
  113852. // Geometries
  113853. serializationObject.geometries = {};
  113854. serializationObject.geometries.boxes = [];
  113855. serializationObject.geometries.spheres = [];
  113856. serializationObject.geometries.cylinders = [];
  113857. serializationObject.geometries.toruses = [];
  113858. serializationObject.geometries.grounds = [];
  113859. serializationObject.geometries.planes = [];
  113860. serializationObject.geometries.torusKnots = [];
  113861. serializationObject.geometries.vertexData = [];
  113862. serializedGeometries = [];
  113863. var geometries = scene.getGeometries();
  113864. for (index = 0; index < geometries.length; index++) {
  113865. var geometry = geometries[index];
  113866. if (geometry.isReady()) {
  113867. serializeGeometry(geometry, serializationObject.geometries);
  113868. }
  113869. }
  113870. // Meshes
  113871. serializationObject.meshes = [];
  113872. for (index = 0; index < scene.meshes.length; index++) {
  113873. var abstractMesh = scene.meshes[index];
  113874. if (abstractMesh instanceof BABYLON.Mesh) {
  113875. var mesh = abstractMesh;
  113876. if (!mesh.doNotSerialize) {
  113877. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  113878. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  113879. }
  113880. }
  113881. }
  113882. }
  113883. // Particles Systems
  113884. serializationObject.particleSystems = [];
  113885. for (index = 0; index < scene.particleSystems.length; index++) {
  113886. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  113887. }
  113888. // Action Manager
  113889. if (scene.actionManager) {
  113890. serializationObject.actions = scene.actionManager.serialize("scene");
  113891. }
  113892. // Components
  113893. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  113894. var component = _c[_b];
  113895. component.serialize(serializationObject);
  113896. }
  113897. return serializationObject;
  113898. };
  113899. /**
  113900. * Serialize a mesh into a JSON compatible object
  113901. * @param toSerialize defines the mesh to serialize
  113902. * @param withParents defines if parents must be serialized as well
  113903. * @param withChildren defines if children must be serialized as well
  113904. * @returns a JSON compatible object
  113905. */
  113906. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  113907. if (withParents === void 0) { withParents = false; }
  113908. if (withChildren === void 0) { withChildren = false; }
  113909. var serializationObject = {};
  113910. SceneSerializer.ClearCache();
  113911. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  113912. if (withParents || withChildren) {
  113913. //deliberate for loop! not for each, appended should be processed as well.
  113914. for (var i = 0; i < toSerialize.length; ++i) {
  113915. if (withChildren) {
  113916. toSerialize[i].getDescendants().forEach(function (node) {
  113917. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  113918. toSerialize.push(node);
  113919. }
  113920. });
  113921. }
  113922. //make sure the array doesn't contain the object already
  113923. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  113924. toSerialize.push(toSerialize[i].parent);
  113925. }
  113926. }
  113927. }
  113928. toSerialize.forEach(function (mesh) {
  113929. finalizeSingleMesh(mesh, serializationObject);
  113930. });
  113931. return serializationObject;
  113932. };
  113933. return SceneSerializer;
  113934. }());
  113935. BABYLON.SceneSerializer = SceneSerializer;
  113936. })(BABYLON || (BABYLON = {}));
  113937. //# sourceMappingURL=sceneSerializer.js.map
  113938. var BABYLON;
  113939. (function (BABYLON) {
  113940. /**
  113941. * Class used to generate realtime reflection / refraction cube textures
  113942. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  113943. */
  113944. var ReflectionProbe = /** @class */ (function () {
  113945. /**
  113946. * Creates a new reflection probe
  113947. * @param name defines the name of the probe
  113948. * @param size defines the texture resolution (for each face)
  113949. * @param scene defines the hosting scene
  113950. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  113951. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  113952. */
  113953. function ReflectionProbe(
  113954. /** defines the name of the probe */
  113955. name, size, scene, generateMipMaps, useFloat) {
  113956. if (generateMipMaps === void 0) { generateMipMaps = true; }
  113957. if (useFloat === void 0) { useFloat = false; }
  113958. var _this = this;
  113959. this.name = name;
  113960. this._viewMatrix = BABYLON.Matrix.Identity();
  113961. this._target = BABYLON.Vector3.Zero();
  113962. this._add = BABYLON.Vector3.Zero();
  113963. this._invertYAxis = false;
  113964. /** Gets or sets probe position (center of the cube map) */
  113965. this.position = BABYLON.Vector3.Zero();
  113966. this._scene = scene;
  113967. // Create the scene field if not exist.
  113968. if (!this._scene.reflectionProbes) {
  113969. this._scene.reflectionProbes = new Array();
  113970. }
  113971. this._scene.reflectionProbes.push(this);
  113972. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  113973. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  113974. switch (faceIndex) {
  113975. case 0:
  113976. _this._add.copyFromFloats(1, 0, 0);
  113977. break;
  113978. case 1:
  113979. _this._add.copyFromFloats(-1, 0, 0);
  113980. break;
  113981. case 2:
  113982. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  113983. break;
  113984. case 3:
  113985. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  113986. break;
  113987. case 4:
  113988. _this._add.copyFromFloats(0, 0, 1);
  113989. break;
  113990. case 5:
  113991. _this._add.copyFromFloats(0, 0, -1);
  113992. break;
  113993. }
  113994. if (_this._attachedMesh) {
  113995. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  113996. }
  113997. _this.position.addToRef(_this._add, _this._target);
  113998. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  113999. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  114000. scene._forcedViewPosition = _this.position;
  114001. });
  114002. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  114003. scene._forcedViewPosition = null;
  114004. scene.updateTransformMatrix(true);
  114005. });
  114006. if (scene.activeCamera) {
  114007. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  114008. }
  114009. }
  114010. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  114011. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  114012. get: function () {
  114013. return this._renderTargetTexture.samples;
  114014. },
  114015. set: function (value) {
  114016. this._renderTargetTexture.samples = value;
  114017. },
  114018. enumerable: true,
  114019. configurable: true
  114020. });
  114021. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  114022. /** Gets or sets the refresh rate to use (on every frame by default) */
  114023. get: function () {
  114024. return this._renderTargetTexture.refreshRate;
  114025. },
  114026. set: function (value) {
  114027. this._renderTargetTexture.refreshRate = value;
  114028. },
  114029. enumerable: true,
  114030. configurable: true
  114031. });
  114032. /**
  114033. * Gets the hosting scene
  114034. * @returns a Scene
  114035. */
  114036. ReflectionProbe.prototype.getScene = function () {
  114037. return this._scene;
  114038. };
  114039. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  114040. /** Gets the internal CubeTexture used to render to */
  114041. get: function () {
  114042. return this._renderTargetTexture;
  114043. },
  114044. enumerable: true,
  114045. configurable: true
  114046. });
  114047. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  114048. /** Gets the list of meshes to render */
  114049. get: function () {
  114050. return this._renderTargetTexture.renderList;
  114051. },
  114052. enumerable: true,
  114053. configurable: true
  114054. });
  114055. /**
  114056. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  114057. * @param mesh defines the mesh to attach to
  114058. */
  114059. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  114060. this._attachedMesh = mesh;
  114061. };
  114062. /**
  114063. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  114064. * @param renderingGroupId The rendering group id corresponding to its index
  114065. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  114066. */
  114067. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  114068. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  114069. };
  114070. /**
  114071. * Clean all associated resources
  114072. */
  114073. ReflectionProbe.prototype.dispose = function () {
  114074. var index = this._scene.reflectionProbes.indexOf(this);
  114075. if (index !== -1) {
  114076. // Remove from the scene if found
  114077. this._scene.reflectionProbes.splice(index, 1);
  114078. }
  114079. if (this._renderTargetTexture) {
  114080. this._renderTargetTexture.dispose();
  114081. this._renderTargetTexture = null;
  114082. }
  114083. };
  114084. return ReflectionProbe;
  114085. }());
  114086. BABYLON.ReflectionProbe = ReflectionProbe;
  114087. })(BABYLON || (BABYLON = {}));
  114088. //# sourceMappingURL=reflectionProbe.js.map
  114089. var BABYLON;
  114090. (function (BABYLON) {
  114091. /**
  114092. * Defines the layer scene component responsible to manage any layers
  114093. * in a given scene.
  114094. */
  114095. var LayerSceneComponent = /** @class */ (function () {
  114096. /**
  114097. * Creates a new instance of the component for the given scene
  114098. * @param scene Defines the scene to register the component in
  114099. */
  114100. function LayerSceneComponent(scene) {
  114101. /**
  114102. * The component name helpfull to identify the component in the list of scene components.
  114103. */
  114104. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  114105. this.scene = scene;
  114106. this._engine = scene.getEngine();
  114107. scene.layers = new Array();
  114108. }
  114109. /**
  114110. * Registers the component in a given scene
  114111. */
  114112. LayerSceneComponent.prototype.register = function () {
  114113. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  114114. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  114115. };
  114116. /**
  114117. * Rebuilds the elements related to this component in case of
  114118. * context lost for instance.
  114119. */
  114120. LayerSceneComponent.prototype.rebuild = function () {
  114121. var layers = this.scene.layers;
  114122. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  114123. var layer = layers_1[_i];
  114124. layer._rebuild();
  114125. }
  114126. };
  114127. /**
  114128. * Disposes the component and the associated ressources.
  114129. */
  114130. LayerSceneComponent.prototype.dispose = function () {
  114131. var layers = this.scene.layers;
  114132. while (layers.length) {
  114133. layers[0].dispose();
  114134. }
  114135. };
  114136. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  114137. var layers = this.scene.layers;
  114138. if (layers.length) {
  114139. this._engine.setDepthBuffer(false);
  114140. var cameraLayerMask = camera.layerMask;
  114141. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  114142. var layer = layers_2[_i];
  114143. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  114144. layer.render();
  114145. }
  114146. }
  114147. this._engine.setDepthBuffer(true);
  114148. }
  114149. };
  114150. LayerSceneComponent.prototype._drawBackground = function (camera) {
  114151. this._draw(camera, true);
  114152. };
  114153. LayerSceneComponent.prototype._drawForeground = function (camera) {
  114154. this._draw(camera, false);
  114155. };
  114156. return LayerSceneComponent;
  114157. }());
  114158. BABYLON.LayerSceneComponent = LayerSceneComponent;
  114159. })(BABYLON || (BABYLON = {}));
  114160. //# sourceMappingURL=layerSceneComponent.js.map
  114161. var BABYLON;
  114162. (function (BABYLON) {
  114163. /**
  114164. * This represents a full screen 2d layer.
  114165. * This can be usefull to display a picture in the background of your scene for instance.
  114166. * @see https://www.babylonjs-playground.com/#08A2BS#1
  114167. */
  114168. var Layer = /** @class */ (function () {
  114169. /**
  114170. * Instantiates a new layer.
  114171. * This represents a full screen 2d layer.
  114172. * This can be usefull to display a picture in the background of your scene for instance.
  114173. * @see https://www.babylonjs-playground.com/#08A2BS#1
  114174. * @param name Define the name of the layer in the scene
  114175. * @param imgUrl Define the url of the texture to display in the layer
  114176. * @param scene Define the scene the layer belongs to
  114177. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  114178. * @param color Defines a color for the layer
  114179. */
  114180. function Layer(
  114181. /**
  114182. * Define the name of the layer.
  114183. */
  114184. name, imgUrl, scene, isBackground, color) {
  114185. this.name = name;
  114186. /**
  114187. * Define the scale of the layer in order to zoom in out of the texture.
  114188. */
  114189. this.scale = new BABYLON.Vector2(1, 1);
  114190. /**
  114191. * Define an offset for the layer in order to shift the texture.
  114192. */
  114193. this.offset = new BABYLON.Vector2(0, 0);
  114194. /**
  114195. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  114196. */
  114197. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  114198. /**
  114199. * Define a mask to restrict the layer to only some of the scene cameras.
  114200. */
  114201. this.layerMask = 0x0FFFFFFF;
  114202. this._vertexBuffers = {};
  114203. /**
  114204. * An event triggered when the layer is disposed.
  114205. */
  114206. this.onDisposeObservable = new BABYLON.Observable();
  114207. /**
  114208. * An event triggered before rendering the scene
  114209. */
  114210. this.onBeforeRenderObservable = new BABYLON.Observable();
  114211. /**
  114212. * An event triggered after rendering the scene
  114213. */
  114214. this.onAfterRenderObservable = new BABYLON.Observable();
  114215. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  114216. this.isBackground = isBackground === undefined ? true : isBackground;
  114217. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  114218. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  114219. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  114220. if (!layerComponent) {
  114221. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  114222. this._scene._addComponent(layerComponent);
  114223. }
  114224. this._scene.layers.push(this);
  114225. var engine = this._scene.getEngine();
  114226. // VBO
  114227. var vertices = [];
  114228. vertices.push(1, 1);
  114229. vertices.push(-1, 1);
  114230. vertices.push(-1, -1);
  114231. vertices.push(1, -1);
  114232. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  114233. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  114234. this._createIndexBuffer();
  114235. // Effects
  114236. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  114237. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  114238. }
  114239. Object.defineProperty(Layer.prototype, "onDispose", {
  114240. /**
  114241. * Back compatibility with callback before the onDisposeObservable existed.
  114242. * The set callback will be triggered when the layer has been disposed.
  114243. */
  114244. set: function (callback) {
  114245. if (this._onDisposeObserver) {
  114246. this.onDisposeObservable.remove(this._onDisposeObserver);
  114247. }
  114248. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  114249. },
  114250. enumerable: true,
  114251. configurable: true
  114252. });
  114253. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  114254. /**
  114255. * Back compatibility with callback before the onBeforeRenderObservable existed.
  114256. * The set callback will be triggered just before rendering the layer.
  114257. */
  114258. set: function (callback) {
  114259. if (this._onBeforeRenderObserver) {
  114260. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  114261. }
  114262. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  114263. },
  114264. enumerable: true,
  114265. configurable: true
  114266. });
  114267. Object.defineProperty(Layer.prototype, "onAfterRender", {
  114268. /**
  114269. * Back compatibility with callback before the onAfterRenderObservable existed.
  114270. * The set callback will be triggered just after rendering the layer.
  114271. */
  114272. set: function (callback) {
  114273. if (this._onAfterRenderObserver) {
  114274. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  114275. }
  114276. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  114277. },
  114278. enumerable: true,
  114279. configurable: true
  114280. });
  114281. Layer.prototype._createIndexBuffer = function () {
  114282. var engine = this._scene.getEngine();
  114283. // Indices
  114284. var indices = [];
  114285. indices.push(0);
  114286. indices.push(1);
  114287. indices.push(2);
  114288. indices.push(0);
  114289. indices.push(2);
  114290. indices.push(3);
  114291. this._indexBuffer = engine.createIndexBuffer(indices);
  114292. };
  114293. /** @hidden */
  114294. Layer.prototype._rebuild = function () {
  114295. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  114296. if (vb) {
  114297. vb._rebuild();
  114298. }
  114299. this._createIndexBuffer();
  114300. };
  114301. /**
  114302. * Renders the layer in the scene.
  114303. */
  114304. Layer.prototype.render = function () {
  114305. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  114306. // Check
  114307. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady()) {
  114308. return;
  114309. }
  114310. var engine = this._scene.getEngine();
  114311. this.onBeforeRenderObservable.notifyObservers(this);
  114312. // Render
  114313. engine.enableEffect(currentEffect);
  114314. engine.setState(false);
  114315. // Texture
  114316. currentEffect.setTexture("textureSampler", this.texture);
  114317. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  114318. // Color
  114319. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  114320. // Scale / offset
  114321. currentEffect.setVector2("offset", this.offset);
  114322. currentEffect.setVector2("scale", this.scale);
  114323. // VBOs
  114324. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  114325. // Draw order
  114326. if (!this.alphaTest) {
  114327. engine.setAlphaMode(this.alphaBlendingMode);
  114328. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  114329. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  114330. }
  114331. else {
  114332. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  114333. }
  114334. this.onAfterRenderObservable.notifyObservers(this);
  114335. };
  114336. /**
  114337. * Disposes and releases the associated ressources.
  114338. */
  114339. Layer.prototype.dispose = function () {
  114340. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  114341. if (vertexBuffer) {
  114342. vertexBuffer.dispose();
  114343. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  114344. }
  114345. if (this._indexBuffer) {
  114346. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  114347. this._indexBuffer = null;
  114348. }
  114349. if (this.texture) {
  114350. this.texture.dispose();
  114351. this.texture = null;
  114352. }
  114353. // Remove from scene
  114354. var index = this._scene.layers.indexOf(this);
  114355. this._scene.layers.splice(index, 1);
  114356. // Callback
  114357. this.onDisposeObservable.notifyObservers(this);
  114358. this.onDisposeObservable.clear();
  114359. this.onAfterRenderObservable.clear();
  114360. this.onBeforeRenderObservable.clear();
  114361. };
  114362. return Layer;
  114363. }());
  114364. BABYLON.Layer = Layer;
  114365. })(BABYLON || (BABYLON = {}));
  114366. //# sourceMappingURL=layer.js.map
  114367. var BABYLON;
  114368. (function (BABYLON) {
  114369. /**
  114370. * Class used to host texture specific utilities
  114371. */
  114372. var TextureTools = /** @class */ (function () {
  114373. function TextureTools() {
  114374. }
  114375. /**
  114376. * Uses the GPU to create a copy texture rescaled at a given size
  114377. * @param texture Texture to copy from
  114378. * @param width defines the desired width
  114379. * @param height defines the desired height
  114380. * @param useBilinearMode defines if bilinear mode has to be used
  114381. * @return the generated texture
  114382. */
  114383. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  114384. if (useBilinearMode === void 0) { useBilinearMode = true; }
  114385. var scene = texture.getScene();
  114386. var engine = scene.getEngine();
  114387. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  114388. rtt.wrapU = texture.wrapU;
  114389. rtt.wrapV = texture.wrapV;
  114390. rtt.uOffset = texture.uOffset;
  114391. rtt.vOffset = texture.vOffset;
  114392. rtt.uScale = texture.uScale;
  114393. rtt.vScale = texture.vScale;
  114394. rtt.uAng = texture.uAng;
  114395. rtt.vAng = texture.vAng;
  114396. rtt.wAng = texture.wAng;
  114397. rtt.coordinatesIndex = texture.coordinatesIndex;
  114398. rtt.level = texture.level;
  114399. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  114400. rtt._texture.isReady = false;
  114401. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114402. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114403. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  114404. passPostProcess.getEffect().executeWhenCompiled(function () {
  114405. passPostProcess.onApply = function (effect) {
  114406. effect.setTexture("textureSampler", texture);
  114407. };
  114408. var internalTexture = rtt.getInternalTexture();
  114409. if (internalTexture) {
  114410. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  114411. engine.unBindFramebuffer(internalTexture);
  114412. rtt.disposeFramebufferObjects();
  114413. passPostProcess.dispose();
  114414. internalTexture.isReady = true;
  114415. }
  114416. });
  114417. return rtt;
  114418. };
  114419. /**
  114420. * Gets an environment BRDF texture for a given scene
  114421. * @param scene defines the hosting scene
  114422. * @returns the environment BRDF texture
  114423. */
  114424. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  114425. if (!scene._environmentBRDFTexture) {
  114426. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  114427. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114428. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114429. scene._environmentBRDFTexture = texture;
  114430. }
  114431. return scene._environmentBRDFTexture;
  114432. };
  114433. 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=";
  114434. return TextureTools;
  114435. }());
  114436. BABYLON.TextureTools = TextureTools;
  114437. })(BABYLON || (BABYLON = {}));
  114438. //# sourceMappingURL=textureTools.js.map
  114439. var BABYLON;
  114440. (function (BABYLON) {
  114441. /**
  114442. * 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.
  114443. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  114444. */
  114445. var FramingBehavior = /** @class */ (function () {
  114446. function FramingBehavior() {
  114447. this._mode = FramingBehavior.FitFrustumSidesMode;
  114448. this._radiusScale = 1.0;
  114449. this._positionScale = 0.5;
  114450. this._defaultElevation = 0.3;
  114451. this._elevationReturnTime = 1500;
  114452. this._elevationReturnWaitTime = 1000;
  114453. this._zoomStopsAnimation = false;
  114454. this._framingTime = 1500;
  114455. /**
  114456. * Define if the behavior should automatically change the configured
  114457. * camera limits and sensibilities.
  114458. */
  114459. this.autoCorrectCameraLimitsAndSensibility = true;
  114460. this._isPointerDown = false;
  114461. this._lastInteractionTime = -Infinity;
  114462. // Framing control
  114463. this._animatables = new Array();
  114464. this._betaIsAnimating = false;
  114465. }
  114466. Object.defineProperty(FramingBehavior.prototype, "name", {
  114467. /**
  114468. * Gets the name of the behavior.
  114469. */
  114470. get: function () {
  114471. return "Framing";
  114472. },
  114473. enumerable: true,
  114474. configurable: true
  114475. });
  114476. Object.defineProperty(FramingBehavior.prototype, "mode", {
  114477. /**
  114478. * Gets current mode used by the behavior.
  114479. */
  114480. get: function () {
  114481. return this._mode;
  114482. },
  114483. /**
  114484. * Sets the current mode used by the behavior
  114485. */
  114486. set: function (mode) {
  114487. this._mode = mode;
  114488. },
  114489. enumerable: true,
  114490. configurable: true
  114491. });
  114492. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  114493. /**
  114494. * Gets the scale applied to the radius
  114495. */
  114496. get: function () {
  114497. return this._radiusScale;
  114498. },
  114499. /**
  114500. * Sets the scale applied to the radius (1 by default)
  114501. */
  114502. set: function (radius) {
  114503. this._radiusScale = radius;
  114504. },
  114505. enumerable: true,
  114506. configurable: true
  114507. });
  114508. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  114509. /**
  114510. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  114511. */
  114512. get: function () {
  114513. return this._positionScale;
  114514. },
  114515. /**
  114516. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  114517. */
  114518. set: function (scale) {
  114519. this._positionScale = scale;
  114520. },
  114521. enumerable: true,
  114522. configurable: true
  114523. });
  114524. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  114525. /**
  114526. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  114527. * behaviour is triggered, in radians.
  114528. */
  114529. get: function () {
  114530. return this._defaultElevation;
  114531. },
  114532. /**
  114533. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  114534. * behaviour is triggered, in radians.
  114535. */
  114536. set: function (elevation) {
  114537. this._defaultElevation = elevation;
  114538. },
  114539. enumerable: true,
  114540. configurable: true
  114541. });
  114542. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  114543. /**
  114544. * Gets the time (in milliseconds) taken to return to the default beta position.
  114545. * Negative value indicates camera should not return to default.
  114546. */
  114547. get: function () {
  114548. return this._elevationReturnTime;
  114549. },
  114550. /**
  114551. * Sets the time (in milliseconds) taken to return to the default beta position.
  114552. * Negative value indicates camera should not return to default.
  114553. */
  114554. set: function (speed) {
  114555. this._elevationReturnTime = speed;
  114556. },
  114557. enumerable: true,
  114558. configurable: true
  114559. });
  114560. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  114561. /**
  114562. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  114563. */
  114564. get: function () {
  114565. return this._elevationReturnWaitTime;
  114566. },
  114567. /**
  114568. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  114569. */
  114570. set: function (time) {
  114571. this._elevationReturnWaitTime = time;
  114572. },
  114573. enumerable: true,
  114574. configurable: true
  114575. });
  114576. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  114577. /**
  114578. * Gets the flag that indicates if user zooming should stop animation.
  114579. */
  114580. get: function () {
  114581. return this._zoomStopsAnimation;
  114582. },
  114583. /**
  114584. * Sets the flag that indicates if user zooming should stop animation.
  114585. */
  114586. set: function (flag) {
  114587. this._zoomStopsAnimation = flag;
  114588. },
  114589. enumerable: true,
  114590. configurable: true
  114591. });
  114592. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  114593. /**
  114594. * Gets the transition time when framing the mesh, in milliseconds
  114595. */
  114596. get: function () {
  114597. return this._framingTime;
  114598. },
  114599. /**
  114600. * Sets the transition time when framing the mesh, in milliseconds
  114601. */
  114602. set: function (time) {
  114603. this._framingTime = time;
  114604. },
  114605. enumerable: true,
  114606. configurable: true
  114607. });
  114608. /**
  114609. * Initializes the behavior.
  114610. */
  114611. FramingBehavior.prototype.init = function () {
  114612. // Do notihng
  114613. };
  114614. /**
  114615. * Attaches the behavior to its arc rotate camera.
  114616. * @param camera Defines the camera to attach the behavior to
  114617. */
  114618. FramingBehavior.prototype.attach = function (camera) {
  114619. var _this = this;
  114620. this._attachedCamera = camera;
  114621. var scene = this._attachedCamera.getScene();
  114622. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  114623. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  114624. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  114625. _this._isPointerDown = true;
  114626. return;
  114627. }
  114628. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  114629. _this._isPointerDown = false;
  114630. }
  114631. });
  114632. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  114633. if (mesh) {
  114634. _this.zoomOnMesh(mesh);
  114635. }
  114636. });
  114637. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  114638. // Stop the animation if there is user interaction and the animation should stop for this interaction
  114639. _this._applyUserInteraction();
  114640. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  114641. // back to the default position after a given timeout
  114642. _this._maintainCameraAboveGround();
  114643. });
  114644. };
  114645. /**
  114646. * Detaches the behavior from its current arc rotate camera.
  114647. */
  114648. FramingBehavior.prototype.detach = function () {
  114649. if (!this._attachedCamera) {
  114650. return;
  114651. }
  114652. var scene = this._attachedCamera.getScene();
  114653. if (this._onPrePointerObservableObserver) {
  114654. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  114655. }
  114656. if (this._onAfterCheckInputsObserver) {
  114657. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  114658. }
  114659. if (this._onMeshTargetChangedObserver) {
  114660. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  114661. }
  114662. this._attachedCamera = null;
  114663. };
  114664. /**
  114665. * Targets the given mesh and updates zoom level accordingly.
  114666. * @param mesh The mesh to target.
  114667. * @param radius Optional. If a cached radius position already exists, overrides default.
  114668. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  114669. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  114670. * @param onAnimationEnd Callback triggered at the end of the framing animation
  114671. */
  114672. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  114673. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  114674. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  114675. mesh.computeWorldMatrix(true);
  114676. var boundingBox = mesh.getBoundingInfo().boundingBox;
  114677. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  114678. };
  114679. /**
  114680. * Targets the given mesh with its children and updates zoom level accordingly.
  114681. * @param mesh The mesh to target.
  114682. * @param radius Optional. If a cached radius position already exists, overrides default.
  114683. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  114684. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  114685. * @param onAnimationEnd Callback triggered at the end of the framing animation
  114686. */
  114687. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  114688. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  114689. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  114690. mesh.computeWorldMatrix(true);
  114691. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  114692. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  114693. };
  114694. /**
  114695. * Targets the given meshes with their children and updates zoom level accordingly.
  114696. * @param meshes The mesh to target.
  114697. * @param radius Optional. If a cached radius position already exists, overrides default.
  114698. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  114699. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  114700. * @param onAnimationEnd Callback triggered at the end of the framing animation
  114701. */
  114702. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  114703. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  114704. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  114705. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  114706. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  114707. for (var i = 0; i < meshes.length; i++) {
  114708. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  114709. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  114710. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  114711. }
  114712. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  114713. };
  114714. /**
  114715. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  114716. * @param minimumWorld Determines the smaller position of the bounding box extend
  114717. * @param maximumWorld Determines the bigger position of the bounding box extend
  114718. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  114719. * @param onAnimationEnd Callback triggered at the end of the framing animation
  114720. */
  114721. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  114722. var _this = this;
  114723. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  114724. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  114725. var zoomTarget;
  114726. if (!this._attachedCamera) {
  114727. return;
  114728. }
  114729. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  114730. var bottom = minimumWorld.y;
  114731. var top = maximumWorld.y;
  114732. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  114733. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  114734. if (focusOnOriginXZ) {
  114735. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  114736. }
  114737. else {
  114738. var centerWorld = minimumWorld.add(radiusWorld);
  114739. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  114740. }
  114741. if (!this._vectorTransition) {
  114742. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  114743. }
  114744. this._betaIsAnimating = true;
  114745. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  114746. if (animatable) {
  114747. this._animatables.push(animatable);
  114748. }
  114749. // sets the radius and lower radius bounds
  114750. // Small delta ensures camera is not always at lower zoom limit.
  114751. var radius = 0;
  114752. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  114753. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  114754. if (this.autoCorrectCameraLimitsAndSensibility) {
  114755. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  114756. }
  114757. radius = position;
  114758. }
  114759. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  114760. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  114761. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  114762. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  114763. }
  114764. }
  114765. // Set sensibilities
  114766. if (this.autoCorrectCameraLimitsAndSensibility) {
  114767. var extend = maximumWorld.subtract(minimumWorld).length();
  114768. this._attachedCamera.panningSensibility = 5000 / extend;
  114769. this._attachedCamera.wheelPrecision = 100 / radius;
  114770. }
  114771. // transition to new radius
  114772. if (!this._radiusTransition) {
  114773. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  114774. }
  114775. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  114776. _this.stopAllAnimations();
  114777. if (onAnimationEnd) {
  114778. onAnimationEnd();
  114779. }
  114780. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  114781. _this._attachedCamera.storeState();
  114782. }
  114783. });
  114784. if (animatable) {
  114785. this._animatables.push(animatable);
  114786. }
  114787. };
  114788. /**
  114789. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  114790. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  114791. * frustum width.
  114792. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  114793. * to fully enclose the mesh in the viewing frustum.
  114794. */
  114795. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  114796. var size = maximumWorld.subtract(minimumWorld);
  114797. var boxVectorGlobalDiagonal = size.length();
  114798. var frustumSlope = this._getFrustumSlope();
  114799. // Formula for setting distance
  114800. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  114801. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  114802. // Horizon distance
  114803. var radius = radiusWithoutFraming * this._radiusScale;
  114804. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  114805. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  114806. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  114807. var camera = this._attachedCamera;
  114808. if (!camera) {
  114809. return 0;
  114810. }
  114811. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  114812. // Don't exceed the requested limit
  114813. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  114814. }
  114815. // Don't exceed the upper radius limit
  114816. if (camera.upperRadiusLimit) {
  114817. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  114818. }
  114819. return distance;
  114820. };
  114821. /**
  114822. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  114823. * is automatically returned to its default position (expected to be above ground plane).
  114824. */
  114825. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  114826. var _this = this;
  114827. if (this._elevationReturnTime < 0) {
  114828. return;
  114829. }
  114830. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  114831. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  114832. var limitBeta = Math.PI * 0.5;
  114833. // Bring the camera back up if below the ground plane
  114834. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  114835. this._betaIsAnimating = true;
  114836. //Transition to new position
  114837. this.stopAllAnimations();
  114838. if (!this._betaTransition) {
  114839. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  114840. }
  114841. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  114842. _this._clearAnimationLocks();
  114843. _this.stopAllAnimations();
  114844. });
  114845. if (animatabe) {
  114846. this._animatables.push(animatabe);
  114847. }
  114848. }
  114849. };
  114850. /**
  114851. * Returns the frustum slope based on the canvas ratio and camera FOV
  114852. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  114853. */
  114854. FramingBehavior.prototype._getFrustumSlope = function () {
  114855. // Calculate the viewport ratio
  114856. // Aspect Ratio is Height/Width.
  114857. var camera = this._attachedCamera;
  114858. if (!camera) {
  114859. return BABYLON.Vector2.Zero();
  114860. }
  114861. var engine = camera.getScene().getEngine();
  114862. var aspectRatio = engine.getAspectRatio(camera);
  114863. // Camera FOV is the vertical field of view (top-bottom) in radians.
  114864. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  114865. var frustumSlopeY = Math.tan(camera.fov / 2);
  114866. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  114867. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  114868. // along the forward vector.
  114869. var frustumSlopeX = frustumSlopeY * aspectRatio;
  114870. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  114871. };
  114872. /**
  114873. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  114874. */
  114875. FramingBehavior.prototype._clearAnimationLocks = function () {
  114876. this._betaIsAnimating = false;
  114877. };
  114878. /**
  114879. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  114880. */
  114881. FramingBehavior.prototype._applyUserInteraction = function () {
  114882. if (this.isUserIsMoving) {
  114883. this._lastInteractionTime = BABYLON.Tools.Now;
  114884. this.stopAllAnimations();
  114885. this._clearAnimationLocks();
  114886. }
  114887. };
  114888. /**
  114889. * Stops and removes all animations that have been applied to the camera
  114890. */
  114891. FramingBehavior.prototype.stopAllAnimations = function () {
  114892. if (this._attachedCamera) {
  114893. this._attachedCamera.animations = [];
  114894. }
  114895. while (this._animatables.length) {
  114896. if (this._animatables[0]) {
  114897. this._animatables[0].onAnimationEnd = null;
  114898. this._animatables[0].stop();
  114899. }
  114900. this._animatables.shift();
  114901. }
  114902. };
  114903. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  114904. /**
  114905. * Gets a value indicating if the user is moving the camera
  114906. */
  114907. get: function () {
  114908. if (!this._attachedCamera) {
  114909. return false;
  114910. }
  114911. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  114912. this._attachedCamera.inertialBetaOffset !== 0 ||
  114913. this._attachedCamera.inertialRadiusOffset !== 0 ||
  114914. this._attachedCamera.inertialPanningX !== 0 ||
  114915. this._attachedCamera.inertialPanningY !== 0 ||
  114916. this._isPointerDown;
  114917. },
  114918. enumerable: true,
  114919. configurable: true
  114920. });
  114921. /**
  114922. * The easing function used by animations
  114923. */
  114924. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  114925. /**
  114926. * The easing mode used by animations
  114927. */
  114928. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  114929. // Statics
  114930. /**
  114931. * The camera can move all the way towards the mesh.
  114932. */
  114933. FramingBehavior.IgnoreBoundsSizeMode = 0;
  114934. /**
  114935. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  114936. */
  114937. FramingBehavior.FitFrustumSidesMode = 1;
  114938. return FramingBehavior;
  114939. }());
  114940. BABYLON.FramingBehavior = FramingBehavior;
  114941. })(BABYLON || (BABYLON = {}));
  114942. //# sourceMappingURL=framingBehavior.js.map
  114943. var BABYLON;
  114944. (function (BABYLON) {
  114945. /**
  114946. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  114947. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  114948. */
  114949. var BouncingBehavior = /** @class */ (function () {
  114950. function BouncingBehavior() {
  114951. /**
  114952. * The duration of the animation, in milliseconds
  114953. */
  114954. this.transitionDuration = 450;
  114955. /**
  114956. * Length of the distance animated by the transition when lower radius is reached
  114957. */
  114958. this.lowerRadiusTransitionRange = 2;
  114959. /**
  114960. * Length of the distance animated by the transition when upper radius is reached
  114961. */
  114962. this.upperRadiusTransitionRange = -2;
  114963. this._autoTransitionRange = false;
  114964. // Animations
  114965. this._radiusIsAnimating = false;
  114966. this._radiusBounceTransition = null;
  114967. this._animatables = new Array();
  114968. }
  114969. Object.defineProperty(BouncingBehavior.prototype, "name", {
  114970. /**
  114971. * Gets the name of the behavior.
  114972. */
  114973. get: function () {
  114974. return "Bouncing";
  114975. },
  114976. enumerable: true,
  114977. configurable: true
  114978. });
  114979. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  114980. /**
  114981. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  114982. */
  114983. get: function () {
  114984. return this._autoTransitionRange;
  114985. },
  114986. /**
  114987. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  114988. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  114989. */
  114990. set: function (value) {
  114991. var _this = this;
  114992. if (this._autoTransitionRange === value) {
  114993. return;
  114994. }
  114995. this._autoTransitionRange = value;
  114996. var camera = this._attachedCamera;
  114997. if (!camera) {
  114998. return;
  114999. }
  115000. if (value) {
  115001. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  115002. if (!mesh) {
  115003. return;
  115004. }
  115005. mesh.computeWorldMatrix(true);
  115006. var diagonal = mesh.getBoundingInfo().diagonalLength;
  115007. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  115008. _this.upperRadiusTransitionRange = diagonal * 0.05;
  115009. });
  115010. }
  115011. else if (this._onMeshTargetChangedObserver) {
  115012. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  115013. }
  115014. },
  115015. enumerable: true,
  115016. configurable: true
  115017. });
  115018. /**
  115019. * Initializes the behavior.
  115020. */
  115021. BouncingBehavior.prototype.init = function () {
  115022. // Do notihng
  115023. };
  115024. /**
  115025. * Attaches the behavior to its arc rotate camera.
  115026. * @param camera Defines the camera to attach the behavior to
  115027. */
  115028. BouncingBehavior.prototype.attach = function (camera) {
  115029. var _this = this;
  115030. this._attachedCamera = camera;
  115031. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  115032. if (!_this._attachedCamera) {
  115033. return;
  115034. }
  115035. // Add the bounce animation to the lower radius limit
  115036. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  115037. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  115038. }
  115039. // Add the bounce animation to the upper radius limit
  115040. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  115041. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  115042. }
  115043. });
  115044. };
  115045. /**
  115046. * Detaches the behavior from its current arc rotate camera.
  115047. */
  115048. BouncingBehavior.prototype.detach = function () {
  115049. if (!this._attachedCamera) {
  115050. return;
  115051. }
  115052. if (this._onAfterCheckInputsObserver) {
  115053. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  115054. }
  115055. if (this._onMeshTargetChangedObserver) {
  115056. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  115057. }
  115058. this._attachedCamera = null;
  115059. };
  115060. /**
  115061. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  115062. * @param radiusLimit The limit to check against.
  115063. * @return Bool to indicate if at limit.
  115064. */
  115065. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  115066. if (!this._attachedCamera) {
  115067. return false;
  115068. }
  115069. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  115070. return true;
  115071. }
  115072. return false;
  115073. };
  115074. /**
  115075. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  115076. * @param radiusDelta The delta by which to animate to. Can be negative.
  115077. */
  115078. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  115079. var _this = this;
  115080. if (!this._attachedCamera) {
  115081. return;
  115082. }
  115083. if (!this._radiusBounceTransition) {
  115084. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  115085. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  115086. }
  115087. // Prevent zoom until bounce has completed
  115088. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  115089. this._attachedCamera.wheelPrecision = Infinity;
  115090. this._attachedCamera.inertialRadiusOffset = 0;
  115091. // Animate to the radius limit
  115092. this.stopAllAnimations();
  115093. this._radiusIsAnimating = true;
  115094. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  115095. if (animatable) {
  115096. this._animatables.push(animatable);
  115097. }
  115098. };
  115099. /**
  115100. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  115101. */
  115102. BouncingBehavior.prototype._clearAnimationLocks = function () {
  115103. this._radiusIsAnimating = false;
  115104. if (this._attachedCamera) {
  115105. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  115106. }
  115107. };
  115108. /**
  115109. * Stops and removes all animations that have been applied to the camera
  115110. */
  115111. BouncingBehavior.prototype.stopAllAnimations = function () {
  115112. if (this._attachedCamera) {
  115113. this._attachedCamera.animations = [];
  115114. }
  115115. while (this._animatables.length) {
  115116. this._animatables[0].onAnimationEnd = null;
  115117. this._animatables[0].stop();
  115118. this._animatables.shift();
  115119. }
  115120. };
  115121. /**
  115122. * The easing function used by animations
  115123. */
  115124. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  115125. /**
  115126. * The easing mode used by animations
  115127. */
  115128. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  115129. return BouncingBehavior;
  115130. }());
  115131. BABYLON.BouncingBehavior = BouncingBehavior;
  115132. })(BABYLON || (BABYLON = {}));
  115133. //# sourceMappingURL=bouncingBehavior.js.map
  115134. var BABYLON;
  115135. (function (BABYLON) {
  115136. /**
  115137. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  115138. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  115139. */
  115140. var AutoRotationBehavior = /** @class */ (function () {
  115141. function AutoRotationBehavior() {
  115142. this._zoomStopsAnimation = false;
  115143. this._idleRotationSpeed = 0.05;
  115144. this._idleRotationWaitTime = 2000;
  115145. this._idleRotationSpinupTime = 2000;
  115146. this._isPointerDown = false;
  115147. this._lastFrameTime = null;
  115148. this._lastInteractionTime = -Infinity;
  115149. this._cameraRotationSpeed = 0;
  115150. this._lastFrameRadius = 0;
  115151. }
  115152. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  115153. /**
  115154. * Gets the name of the behavior.
  115155. */
  115156. get: function () {
  115157. return "AutoRotation";
  115158. },
  115159. enumerable: true,
  115160. configurable: true
  115161. });
  115162. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  115163. /**
  115164. * Gets the flag that indicates if user zooming should stop animation.
  115165. */
  115166. get: function () {
  115167. return this._zoomStopsAnimation;
  115168. },
  115169. /**
  115170. * Sets the flag that indicates if user zooming should stop animation.
  115171. */
  115172. set: function (flag) {
  115173. this._zoomStopsAnimation = flag;
  115174. },
  115175. enumerable: true,
  115176. configurable: true
  115177. });
  115178. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  115179. /**
  115180. * Gets the default speed at which the camera rotates around the model.
  115181. */
  115182. get: function () {
  115183. return this._idleRotationSpeed;
  115184. },
  115185. /**
  115186. * Sets the default speed at which the camera rotates around the model.
  115187. */
  115188. set: function (speed) {
  115189. this._idleRotationSpeed = speed;
  115190. },
  115191. enumerable: true,
  115192. configurable: true
  115193. });
  115194. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  115195. /**
  115196. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  115197. */
  115198. get: function () {
  115199. return this._idleRotationWaitTime;
  115200. },
  115201. /**
  115202. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  115203. */
  115204. set: function (time) {
  115205. this._idleRotationWaitTime = time;
  115206. },
  115207. enumerable: true,
  115208. configurable: true
  115209. });
  115210. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  115211. /**
  115212. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  115213. */
  115214. get: function () {
  115215. return this._idleRotationSpinupTime;
  115216. },
  115217. /**
  115218. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  115219. */
  115220. set: function (time) {
  115221. this._idleRotationSpinupTime = time;
  115222. },
  115223. enumerable: true,
  115224. configurable: true
  115225. });
  115226. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  115227. /**
  115228. * Gets a value indicating if the camera is currently rotating because of this behavior
  115229. */
  115230. get: function () {
  115231. return Math.abs(this._cameraRotationSpeed) > 0;
  115232. },
  115233. enumerable: true,
  115234. configurable: true
  115235. });
  115236. /**
  115237. * Initializes the behavior.
  115238. */
  115239. AutoRotationBehavior.prototype.init = function () {
  115240. // Do notihng
  115241. };
  115242. /**
  115243. * Attaches the behavior to its arc rotate camera.
  115244. * @param camera Defines the camera to attach the behavior to
  115245. */
  115246. AutoRotationBehavior.prototype.attach = function (camera) {
  115247. var _this = this;
  115248. this._attachedCamera = camera;
  115249. var scene = this._attachedCamera.getScene();
  115250. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  115251. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  115252. _this._isPointerDown = true;
  115253. return;
  115254. }
  115255. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  115256. _this._isPointerDown = false;
  115257. }
  115258. });
  115259. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  115260. var now = BABYLON.Tools.Now;
  115261. var dt = 0;
  115262. if (_this._lastFrameTime != null) {
  115263. dt = now - _this._lastFrameTime;
  115264. }
  115265. _this._lastFrameTime = now;
  115266. // Stop the animation if there is user interaction and the animation should stop for this interaction
  115267. _this._applyUserInteraction();
  115268. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  115269. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  115270. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  115271. // Step camera rotation by rotation speed
  115272. if (_this._attachedCamera) {
  115273. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  115274. }
  115275. });
  115276. };
  115277. /**
  115278. * Detaches the behavior from its current arc rotate camera.
  115279. */
  115280. AutoRotationBehavior.prototype.detach = function () {
  115281. if (!this._attachedCamera) {
  115282. return;
  115283. }
  115284. var scene = this._attachedCamera.getScene();
  115285. if (this._onPrePointerObservableObserver) {
  115286. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  115287. }
  115288. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  115289. this._attachedCamera = null;
  115290. };
  115291. /**
  115292. * Returns true if user is scrolling.
  115293. * @return true if user is scrolling.
  115294. */
  115295. AutoRotationBehavior.prototype._userIsZooming = function () {
  115296. if (!this._attachedCamera) {
  115297. return false;
  115298. }
  115299. return this._attachedCamera.inertialRadiusOffset !== 0;
  115300. };
  115301. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  115302. if (!this._attachedCamera) {
  115303. return false;
  115304. }
  115305. var zoomHasHitLimit = false;
  115306. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  115307. zoomHasHitLimit = true;
  115308. }
  115309. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  115310. this._lastFrameRadius = this._attachedCamera.radius;
  115311. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  115312. };
  115313. /**
  115314. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  115315. */
  115316. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  115317. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  115318. this._lastInteractionTime = BABYLON.Tools.Now;
  115319. }
  115320. };
  115321. // Tools
  115322. AutoRotationBehavior.prototype._userIsMoving = function () {
  115323. if (!this._attachedCamera) {
  115324. return false;
  115325. }
  115326. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  115327. this._attachedCamera.inertialBetaOffset !== 0 ||
  115328. this._attachedCamera.inertialRadiusOffset !== 0 ||
  115329. this._attachedCamera.inertialPanningX !== 0 ||
  115330. this._attachedCamera.inertialPanningY !== 0 ||
  115331. this._isPointerDown;
  115332. };
  115333. return AutoRotationBehavior;
  115334. }());
  115335. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  115336. })(BABYLON || (BABYLON = {}));
  115337. //# sourceMappingURL=autoRotationBehavior.js.map
  115338. var BABYLON;
  115339. (function (BABYLON) {
  115340. /**
  115341. * Options to create the null engine
  115342. */
  115343. var NullEngineOptions = /** @class */ (function () {
  115344. function NullEngineOptions() {
  115345. /**
  115346. * Render width (Default: 512)
  115347. */
  115348. this.renderWidth = 512;
  115349. /**
  115350. * Render height (Default: 256)
  115351. */
  115352. this.renderHeight = 256;
  115353. /**
  115354. * Texture size (Default: 512)
  115355. */
  115356. this.textureSize = 512;
  115357. /**
  115358. * If delta time between frames should be constant
  115359. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  115360. */
  115361. this.deterministicLockstep = false;
  115362. /**
  115363. * Maximum about of steps between frames (Default: 4)
  115364. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  115365. */
  115366. this.lockstepMaxSteps = 4;
  115367. }
  115368. return NullEngineOptions;
  115369. }());
  115370. BABYLON.NullEngineOptions = NullEngineOptions;
  115371. /**
  115372. * The null engine class provides support for headless version of babylon.js.
  115373. * This can be used in server side scenario or for testing purposes
  115374. */
  115375. var NullEngine = /** @class */ (function (_super) {
  115376. __extends(NullEngine, _super);
  115377. function NullEngine(options) {
  115378. if (options === void 0) { options = new NullEngineOptions(); }
  115379. var _this = _super.call(this, null) || this;
  115380. if (options.deterministicLockstep === undefined) {
  115381. options.deterministicLockstep = false;
  115382. }
  115383. if (options.lockstepMaxSteps === undefined) {
  115384. options.lockstepMaxSteps = 4;
  115385. }
  115386. _this._options = options;
  115387. // Init caps
  115388. // We consider we are on a webgl1 capable device
  115389. _this._caps = new BABYLON.EngineCapabilities();
  115390. _this._caps.maxTexturesImageUnits = 16;
  115391. _this._caps.maxVertexTextureImageUnits = 16;
  115392. _this._caps.maxTextureSize = 512;
  115393. _this._caps.maxCubemapTextureSize = 512;
  115394. _this._caps.maxRenderTextureSize = 512;
  115395. _this._caps.maxVertexAttribs = 16;
  115396. _this._caps.maxVaryingVectors = 16;
  115397. _this._caps.maxFragmentUniformVectors = 16;
  115398. _this._caps.maxVertexUniformVectors = 16;
  115399. // Extensions
  115400. _this._caps.standardDerivatives = false;
  115401. _this._caps.astc = null;
  115402. _this._caps.s3tc = null;
  115403. _this._caps.pvrtc = null;
  115404. _this._caps.etc1 = null;
  115405. _this._caps.etc2 = null;
  115406. _this._caps.textureAnisotropicFilterExtension = null;
  115407. _this._caps.maxAnisotropy = 0;
  115408. _this._caps.uintIndices = false;
  115409. _this._caps.fragmentDepthSupported = false;
  115410. _this._caps.highPrecisionShaderSupported = true;
  115411. _this._caps.colorBufferFloat = false;
  115412. _this._caps.textureFloat = false;
  115413. _this._caps.textureFloatLinearFiltering = false;
  115414. _this._caps.textureFloatRender = false;
  115415. _this._caps.textureHalfFloat = false;
  115416. _this._caps.textureHalfFloatLinearFiltering = false;
  115417. _this._caps.textureHalfFloatRender = false;
  115418. _this._caps.textureLOD = false;
  115419. _this._caps.drawBuffersExtension = false;
  115420. _this._caps.depthTextureExtension = false;
  115421. _this._caps.vertexArrayObject = false;
  115422. _this._caps.instancedArrays = false;
  115423. BABYLON.Tools.Log("Babylon.js v" + BABYLON.Engine.Version + " - Null engine");
  115424. // Wrappers
  115425. if (typeof URL === "undefined") {
  115426. URL = {
  115427. createObjectURL: function () { },
  115428. revokeObjectURL: function () { }
  115429. };
  115430. }
  115431. if (typeof Blob === "undefined") {
  115432. Blob = function () { };
  115433. }
  115434. return _this;
  115435. }
  115436. /**
  115437. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  115438. */
  115439. NullEngine.prototype.isDeterministicLockStep = function () {
  115440. return this._options.deterministicLockstep;
  115441. };
  115442. /** @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep */
  115443. NullEngine.prototype.getLockstepMaxSteps = function () {
  115444. return this._options.lockstepMaxSteps;
  115445. };
  115446. /**
  115447. * Sets hardware scaling, used to save performance if needed
  115448. * @see https://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  115449. */
  115450. NullEngine.prototype.getHardwareScalingLevel = function () {
  115451. return 1.0;
  115452. };
  115453. NullEngine.prototype.createVertexBuffer = function (vertices) {
  115454. return {
  115455. capacity: 0,
  115456. references: 1,
  115457. is32Bits: false
  115458. };
  115459. };
  115460. NullEngine.prototype.createIndexBuffer = function (indices) {
  115461. return {
  115462. capacity: 0,
  115463. references: 1,
  115464. is32Bits: false
  115465. };
  115466. };
  115467. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  115468. if (stencil === void 0) { stencil = false; }
  115469. };
  115470. NullEngine.prototype.getRenderWidth = function (useScreen) {
  115471. if (useScreen === void 0) { useScreen = false; }
  115472. if (!useScreen && this._currentRenderTarget) {
  115473. return this._currentRenderTarget.width;
  115474. }
  115475. return this._options.renderWidth;
  115476. };
  115477. NullEngine.prototype.getRenderHeight = function (useScreen) {
  115478. if (useScreen === void 0) { useScreen = false; }
  115479. if (!useScreen && this._currentRenderTarget) {
  115480. return this._currentRenderTarget.height;
  115481. }
  115482. return this._options.renderHeight;
  115483. };
  115484. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  115485. this._cachedViewport = viewport;
  115486. };
  115487. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  115488. return {
  115489. transformFeedback: null,
  115490. __SPECTOR_rebuildProgram: null,
  115491. isParallelCompiled: false
  115492. };
  115493. };
  115494. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  115495. return [];
  115496. };
  115497. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  115498. return [];
  115499. };
  115500. NullEngine.prototype.bindSamplers = function (effect) {
  115501. this._currentEffect = null;
  115502. };
  115503. NullEngine.prototype.enableEffect = function (effect) {
  115504. this._currentEffect = effect;
  115505. if (effect.onBind) {
  115506. effect.onBind(effect);
  115507. }
  115508. if (effect._onBindObservable) {
  115509. effect._onBindObservable.notifyObservers(effect);
  115510. }
  115511. };
  115512. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  115513. if (zOffset === void 0) { zOffset = 0; }
  115514. if (reverseSide === void 0) { reverseSide = false; }
  115515. };
  115516. NullEngine.prototype.setIntArray = function (uniform, array) {
  115517. };
  115518. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  115519. };
  115520. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  115521. };
  115522. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  115523. };
  115524. NullEngine.prototype.setFloatArray = function (uniform, array) {
  115525. };
  115526. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  115527. };
  115528. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  115529. };
  115530. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  115531. };
  115532. NullEngine.prototype.setArray = function (uniform, array) {
  115533. };
  115534. NullEngine.prototype.setArray2 = function (uniform, array) {
  115535. };
  115536. NullEngine.prototype.setArray3 = function (uniform, array) {
  115537. };
  115538. NullEngine.prototype.setArray4 = function (uniform, array) {
  115539. };
  115540. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  115541. };
  115542. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  115543. };
  115544. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  115545. };
  115546. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  115547. };
  115548. NullEngine.prototype.setFloat = function (uniform, value) {
  115549. };
  115550. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  115551. };
  115552. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  115553. };
  115554. NullEngine.prototype.setBool = function (uniform, bool) {
  115555. };
  115556. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  115557. };
  115558. NullEngine.prototype.setColor3 = function (uniform, color3) {
  115559. };
  115560. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  115561. };
  115562. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  115563. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  115564. if (this._alphaMode === mode) {
  115565. return;
  115566. }
  115567. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  115568. if (!noDepthWriteChange) {
  115569. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  115570. }
  115571. this._alphaMode = mode;
  115572. };
  115573. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  115574. };
  115575. NullEngine.prototype.wipeCaches = function (bruteForce) {
  115576. if (this.preventCacheWipeBetweenFrames) {
  115577. return;
  115578. }
  115579. this.resetTextureCache();
  115580. this._currentEffect = null;
  115581. if (bruteForce) {
  115582. this._currentProgram = null;
  115583. this._stencilState.reset();
  115584. this._depthCullingState.reset();
  115585. this._alphaState.reset();
  115586. }
  115587. this._cachedVertexBuffers = null;
  115588. this._cachedIndexBuffer = null;
  115589. this._cachedEffectForVertexBuffers = null;
  115590. };
  115591. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  115592. };
  115593. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  115594. };
  115595. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  115596. };
  115597. /** @hidden */
  115598. NullEngine.prototype._createTexture = function () {
  115599. return {};
  115600. };
  115601. /** @hidden */
  115602. NullEngine.prototype._releaseTexture = function (texture) {
  115603. };
  115604. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  115605. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  115606. if (onLoad === void 0) { onLoad = null; }
  115607. if (onError === void 0) { onError = null; }
  115608. if (buffer === void 0) { buffer = null; }
  115609. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  115610. var url = String(urlArg);
  115611. texture.url = url;
  115612. texture.generateMipMaps = !noMipmap;
  115613. texture.samplingMode = samplingMode;
  115614. texture.invertY = invertY;
  115615. texture.baseWidth = this._options.textureSize;
  115616. texture.baseHeight = this._options.textureSize;
  115617. texture.width = this._options.textureSize;
  115618. texture.height = this._options.textureSize;
  115619. if (format) {
  115620. texture.format = format;
  115621. }
  115622. texture.isReady = true;
  115623. if (onLoad) {
  115624. onLoad();
  115625. }
  115626. this._internalTexturesCache.push(texture);
  115627. return texture;
  115628. };
  115629. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  115630. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  115631. if (options !== undefined && typeof options === "object") {
  115632. fullOptions.generateMipMaps = options.generateMipMaps;
  115633. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  115634. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  115635. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  115636. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  115637. }
  115638. else {
  115639. fullOptions.generateMipMaps = options;
  115640. fullOptions.generateDepthBuffer = true;
  115641. fullOptions.generateStencilBuffer = false;
  115642. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  115643. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  115644. }
  115645. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  115646. var width = size.width || size;
  115647. var height = size.height || size;
  115648. texture._depthStencilBuffer = {};
  115649. texture._framebuffer = {};
  115650. texture.baseWidth = width;
  115651. texture.baseHeight = height;
  115652. texture.width = width;
  115653. texture.height = height;
  115654. texture.isReady = true;
  115655. texture.samples = 1;
  115656. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  115657. texture.samplingMode = fullOptions.samplingMode;
  115658. texture.type = fullOptions.type;
  115659. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  115660. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  115661. this._internalTexturesCache.push(texture);
  115662. return texture;
  115663. };
  115664. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  115665. texture.samplingMode = samplingMode;
  115666. };
  115667. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  115668. if (this._currentRenderTarget) {
  115669. this.unBindFramebuffer(this._currentRenderTarget);
  115670. }
  115671. this._currentRenderTarget = texture;
  115672. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  115673. if (this._cachedViewport && !forceFullscreenViewport) {
  115674. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  115675. }
  115676. };
  115677. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  115678. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  115679. this._currentRenderTarget = null;
  115680. if (onBeforeUnbind) {
  115681. if (texture._MSAAFramebuffer) {
  115682. this._currentFramebuffer = texture._framebuffer;
  115683. }
  115684. onBeforeUnbind();
  115685. }
  115686. this._currentFramebuffer = null;
  115687. };
  115688. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  115689. var vbo = {
  115690. capacity: 1,
  115691. references: 1,
  115692. is32Bits: false
  115693. };
  115694. return vbo;
  115695. };
  115696. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  115697. if (premulAlpha === void 0) { premulAlpha = false; }
  115698. };
  115699. NullEngine.prototype.areAllEffectsReady = function () {
  115700. return true;
  115701. };
  115702. /**
  115703. * @hidden
  115704. * Get the current error code of the webGL context
  115705. * @returns the error code
  115706. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  115707. */
  115708. NullEngine.prototype.getError = function () {
  115709. return 0;
  115710. };
  115711. /** @hidden */
  115712. NullEngine.prototype._getUnpackAlignement = function () {
  115713. return 1;
  115714. };
  115715. /** @hidden */
  115716. NullEngine.prototype._unpackFlipY = function (value) {
  115717. };
  115718. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  115719. if (offset === void 0) { offset = 0; }
  115720. };
  115721. /**
  115722. * Updates a dynamic vertex buffer.
  115723. * @param vertexBuffer the vertex buffer to update
  115724. * @param data the data used to update the vertex buffer
  115725. * @param byteOffset the byte offset of the data (optional)
  115726. * @param byteLength the byte length of the data (optional)
  115727. */
  115728. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  115729. };
  115730. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  115731. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  115732. this._boundTexturesCache[this._activeChannel] = texture;
  115733. return true;
  115734. }
  115735. return false;
  115736. };
  115737. /** @hidden */
  115738. NullEngine.prototype._bindTexture = function (channel, texture) {
  115739. if (channel < 0) {
  115740. return;
  115741. }
  115742. this._bindTextureDirectly(0, texture);
  115743. };
  115744. /** @hidden */
  115745. NullEngine.prototype._releaseBuffer = function (buffer) {
  115746. buffer.references--;
  115747. if (buffer.references === 0) {
  115748. return true;
  115749. }
  115750. return false;
  115751. };
  115752. NullEngine.prototype.releaseEffects = function () {
  115753. };
  115754. NullEngine.prototype.displayLoadingUI = function () {
  115755. };
  115756. NullEngine.prototype.hideLoadingUI = function () {
  115757. };
  115758. /** @hidden */
  115759. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  115760. if (faceIndex === void 0) { faceIndex = 0; }
  115761. if (lod === void 0) { lod = 0; }
  115762. };
  115763. /** @hidden */
  115764. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  115765. if (faceIndex === void 0) { faceIndex = 0; }
  115766. if (lod === void 0) { lod = 0; }
  115767. };
  115768. /** @hidden */
  115769. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  115770. if (faceIndex === void 0) { faceIndex = 0; }
  115771. if (lod === void 0) { lod = 0; }
  115772. };
  115773. /** @hidden */
  115774. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  115775. if (faceIndex === void 0) { faceIndex = 0; }
  115776. if (lod === void 0) { lod = 0; }
  115777. };
  115778. return NullEngine;
  115779. }(BABYLON.Engine));
  115780. BABYLON.NullEngine = NullEngine;
  115781. })(BABYLON || (BABYLON = {}));
  115782. //# sourceMappingURL=nullEngine.js.map
  115783. var BABYLON;
  115784. (function (BABYLON) {
  115785. /**
  115786. * This class can be used to get instrumentation data from a Babylon engine
  115787. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  115788. */
  115789. var EngineInstrumentation = /** @class */ (function () {
  115790. /**
  115791. * Instantiates a new engine instrumentation.
  115792. * This class can be used to get instrumentation data from a Babylon engine
  115793. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  115794. * @param engine Defines the engine to instrument
  115795. */
  115796. function EngineInstrumentation(
  115797. /**
  115798. * Define the instrumented engine.
  115799. */
  115800. engine) {
  115801. this.engine = engine;
  115802. this._captureGPUFrameTime = false;
  115803. this._gpuFrameTime = new BABYLON.PerfCounter();
  115804. this._captureShaderCompilationTime = false;
  115805. this._shaderCompilationTime = new BABYLON.PerfCounter();
  115806. // Observers
  115807. this._onBeginFrameObserver = null;
  115808. this._onEndFrameObserver = null;
  115809. this._onBeforeShaderCompilationObserver = null;
  115810. this._onAfterShaderCompilationObserver = null;
  115811. }
  115812. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  115813. // Properties
  115814. /**
  115815. * Gets the perf counter used for GPU frame time
  115816. */
  115817. get: function () {
  115818. return this._gpuFrameTime;
  115819. },
  115820. enumerable: true,
  115821. configurable: true
  115822. });
  115823. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  115824. /**
  115825. * Gets the GPU frame time capture status
  115826. */
  115827. get: function () {
  115828. return this._captureGPUFrameTime;
  115829. },
  115830. /**
  115831. * Enable or disable the GPU frame time capture
  115832. */
  115833. set: function (value) {
  115834. var _this = this;
  115835. if (value === this._captureGPUFrameTime) {
  115836. return;
  115837. }
  115838. this._captureGPUFrameTime = value;
  115839. if (value) {
  115840. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  115841. if (!_this._gpuFrameTimeToken) {
  115842. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  115843. }
  115844. });
  115845. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  115846. if (!_this._gpuFrameTimeToken) {
  115847. return;
  115848. }
  115849. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  115850. if (time > -1) {
  115851. _this._gpuFrameTimeToken = null;
  115852. _this._gpuFrameTime.fetchNewFrame();
  115853. _this._gpuFrameTime.addCount(time, true);
  115854. }
  115855. });
  115856. }
  115857. else {
  115858. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  115859. this._onBeginFrameObserver = null;
  115860. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  115861. this._onEndFrameObserver = null;
  115862. }
  115863. },
  115864. enumerable: true,
  115865. configurable: true
  115866. });
  115867. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  115868. /**
  115869. * Gets the perf counter used for shader compilation time
  115870. */
  115871. get: function () {
  115872. return this._shaderCompilationTime;
  115873. },
  115874. enumerable: true,
  115875. configurable: true
  115876. });
  115877. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  115878. /**
  115879. * Gets the shader compilation time capture status
  115880. */
  115881. get: function () {
  115882. return this._captureShaderCompilationTime;
  115883. },
  115884. /**
  115885. * Enable or disable the shader compilation time capture
  115886. */
  115887. set: function (value) {
  115888. var _this = this;
  115889. if (value === this._captureShaderCompilationTime) {
  115890. return;
  115891. }
  115892. this._captureShaderCompilationTime = value;
  115893. if (value) {
  115894. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  115895. _this._shaderCompilationTime.fetchNewFrame();
  115896. _this._shaderCompilationTime.beginMonitoring();
  115897. });
  115898. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  115899. _this._shaderCompilationTime.endMonitoring();
  115900. });
  115901. }
  115902. else {
  115903. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  115904. this._onBeforeShaderCompilationObserver = null;
  115905. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  115906. this._onAfterShaderCompilationObserver = null;
  115907. }
  115908. },
  115909. enumerable: true,
  115910. configurable: true
  115911. });
  115912. /**
  115913. * Dispose and release associated resources.
  115914. */
  115915. EngineInstrumentation.prototype.dispose = function () {
  115916. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  115917. this._onBeginFrameObserver = null;
  115918. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  115919. this._onEndFrameObserver = null;
  115920. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  115921. this._onBeforeShaderCompilationObserver = null;
  115922. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  115923. this._onAfterShaderCompilationObserver = null;
  115924. this.engine = null;
  115925. };
  115926. return EngineInstrumentation;
  115927. }());
  115928. BABYLON.EngineInstrumentation = EngineInstrumentation;
  115929. })(BABYLON || (BABYLON = {}));
  115930. //# sourceMappingURL=engineInstrumentation.js.map
  115931. var BABYLON;
  115932. (function (BABYLON) {
  115933. /**
  115934. * This class can be used to get instrumentation data from a Babylon engine
  115935. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  115936. */
  115937. var SceneInstrumentation = /** @class */ (function () {
  115938. /**
  115939. * Instantiates a new scene instrumentation.
  115940. * This class can be used to get instrumentation data from a Babylon engine
  115941. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  115942. * @param scene Defines the scene to instrument
  115943. */
  115944. function SceneInstrumentation(
  115945. /**
  115946. * Defines the scene to instrument
  115947. */
  115948. scene) {
  115949. var _this = this;
  115950. this.scene = scene;
  115951. this._captureActiveMeshesEvaluationTime = false;
  115952. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  115953. this._captureRenderTargetsRenderTime = false;
  115954. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  115955. this._captureFrameTime = false;
  115956. this._frameTime = new BABYLON.PerfCounter();
  115957. this._captureRenderTime = false;
  115958. this._renderTime = new BABYLON.PerfCounter();
  115959. this._captureInterFrameTime = false;
  115960. this._interFrameTime = new BABYLON.PerfCounter();
  115961. this._captureParticlesRenderTime = false;
  115962. this._particlesRenderTime = new BABYLON.PerfCounter();
  115963. this._captureSpritesRenderTime = false;
  115964. this._spritesRenderTime = new BABYLON.PerfCounter();
  115965. this._capturePhysicsTime = false;
  115966. this._physicsTime = new BABYLON.PerfCounter();
  115967. this._captureAnimationsTime = false;
  115968. this._animationsTime = new BABYLON.PerfCounter();
  115969. this._captureCameraRenderTime = false;
  115970. this._cameraRenderTime = new BABYLON.PerfCounter();
  115971. // Observers
  115972. this._onBeforeActiveMeshesEvaluationObserver = null;
  115973. this._onAfterActiveMeshesEvaluationObserver = null;
  115974. this._onBeforeRenderTargetsRenderObserver = null;
  115975. this._onAfterRenderTargetsRenderObserver = null;
  115976. this._onAfterRenderObserver = null;
  115977. this._onBeforeDrawPhaseObserver = null;
  115978. this._onAfterDrawPhaseObserver = null;
  115979. this._onBeforeAnimationsObserver = null;
  115980. this._onBeforeParticlesRenderingObserver = null;
  115981. this._onAfterParticlesRenderingObserver = null;
  115982. this._onBeforeSpritesRenderingObserver = null;
  115983. this._onAfterSpritesRenderingObserver = null;
  115984. this._onBeforePhysicsObserver = null;
  115985. this._onAfterPhysicsObserver = null;
  115986. this._onAfterAnimationsObserver = null;
  115987. this._onBeforeCameraRenderObserver = null;
  115988. this._onAfterCameraRenderObserver = null;
  115989. // Before render
  115990. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  115991. if (_this._captureActiveMeshesEvaluationTime) {
  115992. _this._activeMeshesEvaluationTime.fetchNewFrame();
  115993. }
  115994. if (_this._captureRenderTargetsRenderTime) {
  115995. _this._renderTargetsRenderTime.fetchNewFrame();
  115996. }
  115997. if (_this._captureFrameTime) {
  115998. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  115999. _this._frameTime.beginMonitoring();
  116000. }
  116001. if (_this._captureInterFrameTime) {
  116002. _this._interFrameTime.endMonitoring();
  116003. }
  116004. if (_this._captureParticlesRenderTime) {
  116005. _this._particlesRenderTime.fetchNewFrame();
  116006. }
  116007. if (_this._captureSpritesRenderTime) {
  116008. _this._spritesRenderTime.fetchNewFrame();
  116009. }
  116010. if (_this._captureAnimationsTime) {
  116011. _this._animationsTime.beginMonitoring();
  116012. }
  116013. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  116014. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  116015. });
  116016. // After render
  116017. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  116018. if (_this._captureFrameTime) {
  116019. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  116020. _this._frameTime.endMonitoring();
  116021. }
  116022. if (_this._captureRenderTime) {
  116023. _this._renderTime.endMonitoring(false);
  116024. }
  116025. if (_this._captureInterFrameTime) {
  116026. _this._interFrameTime.beginMonitoring();
  116027. }
  116028. });
  116029. }
  116030. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  116031. // Properties
  116032. /**
  116033. * Gets the perf counter used for active meshes evaluation time
  116034. */
  116035. get: function () {
  116036. return this._activeMeshesEvaluationTime;
  116037. },
  116038. enumerable: true,
  116039. configurable: true
  116040. });
  116041. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  116042. /**
  116043. * Gets the active meshes evaluation time capture status
  116044. */
  116045. get: function () {
  116046. return this._captureActiveMeshesEvaluationTime;
  116047. },
  116048. /**
  116049. * Enable or disable the active meshes evaluation time capture
  116050. */
  116051. set: function (value) {
  116052. var _this = this;
  116053. if (value === this._captureActiveMeshesEvaluationTime) {
  116054. return;
  116055. }
  116056. this._captureActiveMeshesEvaluationTime = value;
  116057. if (value) {
  116058. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  116059. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  116060. _this._activeMeshesEvaluationTime.beginMonitoring();
  116061. });
  116062. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  116063. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  116064. _this._activeMeshesEvaluationTime.endMonitoring();
  116065. });
  116066. }
  116067. else {
  116068. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  116069. this._onBeforeActiveMeshesEvaluationObserver = null;
  116070. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  116071. this._onAfterActiveMeshesEvaluationObserver = null;
  116072. }
  116073. },
  116074. enumerable: true,
  116075. configurable: true
  116076. });
  116077. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  116078. /**
  116079. * Gets the perf counter used for render targets render time
  116080. */
  116081. get: function () {
  116082. return this._renderTargetsRenderTime;
  116083. },
  116084. enumerable: true,
  116085. configurable: true
  116086. });
  116087. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  116088. /**
  116089. * Gets the render targets render time capture status
  116090. */
  116091. get: function () {
  116092. return this._captureRenderTargetsRenderTime;
  116093. },
  116094. /**
  116095. * Enable or disable the render targets render time capture
  116096. */
  116097. set: function (value) {
  116098. var _this = this;
  116099. if (value === this._captureRenderTargetsRenderTime) {
  116100. return;
  116101. }
  116102. this._captureRenderTargetsRenderTime = value;
  116103. if (value) {
  116104. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  116105. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  116106. _this._renderTargetsRenderTime.beginMonitoring();
  116107. });
  116108. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  116109. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  116110. _this._renderTargetsRenderTime.endMonitoring(false);
  116111. });
  116112. }
  116113. else {
  116114. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  116115. this._onBeforeRenderTargetsRenderObserver = null;
  116116. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  116117. this._onAfterRenderTargetsRenderObserver = null;
  116118. }
  116119. },
  116120. enumerable: true,
  116121. configurable: true
  116122. });
  116123. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  116124. /**
  116125. * Gets the perf counter used for particles render time
  116126. */
  116127. get: function () {
  116128. return this._particlesRenderTime;
  116129. },
  116130. enumerable: true,
  116131. configurable: true
  116132. });
  116133. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  116134. /**
  116135. * Gets the particles render time capture status
  116136. */
  116137. get: function () {
  116138. return this._captureParticlesRenderTime;
  116139. },
  116140. /**
  116141. * Enable or disable the particles render time capture
  116142. */
  116143. set: function (value) {
  116144. var _this = this;
  116145. if (value === this._captureParticlesRenderTime) {
  116146. return;
  116147. }
  116148. this._captureParticlesRenderTime = value;
  116149. if (value) {
  116150. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  116151. BABYLON.Tools.StartPerformanceCounter("Particles");
  116152. _this._particlesRenderTime.beginMonitoring();
  116153. });
  116154. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  116155. BABYLON.Tools.EndPerformanceCounter("Particles");
  116156. _this._particlesRenderTime.endMonitoring(false);
  116157. });
  116158. }
  116159. else {
  116160. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  116161. this._onBeforeParticlesRenderingObserver = null;
  116162. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  116163. this._onAfterParticlesRenderingObserver = null;
  116164. }
  116165. },
  116166. enumerable: true,
  116167. configurable: true
  116168. });
  116169. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  116170. /**
  116171. * Gets the perf counter used for sprites render time
  116172. */
  116173. get: function () {
  116174. return this._spritesRenderTime;
  116175. },
  116176. enumerable: true,
  116177. configurable: true
  116178. });
  116179. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  116180. /**
  116181. * Gets the sprites render time capture status
  116182. */
  116183. get: function () {
  116184. return this._captureSpritesRenderTime;
  116185. },
  116186. /**
  116187. * Enable or disable the sprites render time capture
  116188. */
  116189. set: function (value) {
  116190. var _this = this;
  116191. if (value === this._captureSpritesRenderTime) {
  116192. return;
  116193. }
  116194. this._captureSpritesRenderTime = value;
  116195. if (!this.scene.spriteManagers) {
  116196. return;
  116197. }
  116198. if (value) {
  116199. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  116200. BABYLON.Tools.StartPerformanceCounter("Sprites");
  116201. _this._spritesRenderTime.beginMonitoring();
  116202. });
  116203. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  116204. BABYLON.Tools.EndPerformanceCounter("Sprites");
  116205. _this._spritesRenderTime.endMonitoring(false);
  116206. });
  116207. }
  116208. else {
  116209. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  116210. this._onBeforeSpritesRenderingObserver = null;
  116211. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  116212. this._onAfterSpritesRenderingObserver = null;
  116213. }
  116214. },
  116215. enumerable: true,
  116216. configurable: true
  116217. });
  116218. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  116219. /**
  116220. * Gets the perf counter used for physics time
  116221. */
  116222. get: function () {
  116223. return this._physicsTime;
  116224. },
  116225. enumerable: true,
  116226. configurable: true
  116227. });
  116228. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  116229. /**
  116230. * Gets the physics time capture status
  116231. */
  116232. get: function () {
  116233. return this._capturePhysicsTime;
  116234. },
  116235. /**
  116236. * Enable or disable the physics time capture
  116237. */
  116238. set: function (value) {
  116239. var _this = this;
  116240. if (value === this._capturePhysicsTime) {
  116241. return;
  116242. }
  116243. if (!this.scene.onBeforePhysicsObservable) {
  116244. return;
  116245. }
  116246. this._capturePhysicsTime = value;
  116247. if (value) {
  116248. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  116249. BABYLON.Tools.StartPerformanceCounter("Physics");
  116250. _this._physicsTime.beginMonitoring();
  116251. });
  116252. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  116253. BABYLON.Tools.EndPerformanceCounter("Physics");
  116254. _this._physicsTime.endMonitoring();
  116255. });
  116256. }
  116257. else {
  116258. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  116259. this._onBeforePhysicsObserver = null;
  116260. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  116261. this._onAfterPhysicsObserver = null;
  116262. }
  116263. },
  116264. enumerable: true,
  116265. configurable: true
  116266. });
  116267. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  116268. /**
  116269. * Gets the perf counter used for animations time
  116270. */
  116271. get: function () {
  116272. return this._animationsTime;
  116273. },
  116274. enumerable: true,
  116275. configurable: true
  116276. });
  116277. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  116278. /**
  116279. * Gets the animations time capture status
  116280. */
  116281. get: function () {
  116282. return this._captureAnimationsTime;
  116283. },
  116284. /**
  116285. * Enable or disable the animations time capture
  116286. */
  116287. set: function (value) {
  116288. var _this = this;
  116289. if (value === this._captureAnimationsTime) {
  116290. return;
  116291. }
  116292. this._captureAnimationsTime = value;
  116293. if (value) {
  116294. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  116295. _this._animationsTime.endMonitoring();
  116296. });
  116297. }
  116298. else {
  116299. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  116300. this._onAfterAnimationsObserver = null;
  116301. }
  116302. },
  116303. enumerable: true,
  116304. configurable: true
  116305. });
  116306. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  116307. /**
  116308. * Gets the perf counter used for frame time capture
  116309. */
  116310. get: function () {
  116311. return this._frameTime;
  116312. },
  116313. enumerable: true,
  116314. configurable: true
  116315. });
  116316. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  116317. /**
  116318. * Gets the frame time capture status
  116319. */
  116320. get: function () {
  116321. return this._captureFrameTime;
  116322. },
  116323. /**
  116324. * Enable or disable the frame time capture
  116325. */
  116326. set: function (value) {
  116327. this._captureFrameTime = value;
  116328. },
  116329. enumerable: true,
  116330. configurable: true
  116331. });
  116332. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  116333. /**
  116334. * Gets the perf counter used for inter-frames time capture
  116335. */
  116336. get: function () {
  116337. return this._interFrameTime;
  116338. },
  116339. enumerable: true,
  116340. configurable: true
  116341. });
  116342. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  116343. /**
  116344. * Gets the inter-frames time capture status
  116345. */
  116346. get: function () {
  116347. return this._captureInterFrameTime;
  116348. },
  116349. /**
  116350. * Enable or disable the inter-frames time capture
  116351. */
  116352. set: function (value) {
  116353. this._captureInterFrameTime = value;
  116354. },
  116355. enumerable: true,
  116356. configurable: true
  116357. });
  116358. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  116359. /**
  116360. * Gets the perf counter used for render time capture
  116361. */
  116362. get: function () {
  116363. return this._renderTime;
  116364. },
  116365. enumerable: true,
  116366. configurable: true
  116367. });
  116368. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  116369. /**
  116370. * Gets the render time capture status
  116371. */
  116372. get: function () {
  116373. return this._captureRenderTime;
  116374. },
  116375. /**
  116376. * Enable or disable the render time capture
  116377. */
  116378. set: function (value) {
  116379. var _this = this;
  116380. if (value === this._captureRenderTime) {
  116381. return;
  116382. }
  116383. this._captureRenderTime = value;
  116384. if (value) {
  116385. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  116386. _this._renderTime.beginMonitoring();
  116387. BABYLON.Tools.StartPerformanceCounter("Main render");
  116388. });
  116389. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  116390. _this._renderTime.endMonitoring(false);
  116391. BABYLON.Tools.EndPerformanceCounter("Main render");
  116392. });
  116393. }
  116394. else {
  116395. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  116396. this._onBeforeDrawPhaseObserver = null;
  116397. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  116398. this._onAfterDrawPhaseObserver = null;
  116399. }
  116400. },
  116401. enumerable: true,
  116402. configurable: true
  116403. });
  116404. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  116405. /**
  116406. * Gets the perf counter used for camera render time capture
  116407. */
  116408. get: function () {
  116409. return this._cameraRenderTime;
  116410. },
  116411. enumerable: true,
  116412. configurable: true
  116413. });
  116414. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  116415. /**
  116416. * Gets the camera render time capture status
  116417. */
  116418. get: function () {
  116419. return this._captureCameraRenderTime;
  116420. },
  116421. /**
  116422. * Enable or disable the camera render time capture
  116423. */
  116424. set: function (value) {
  116425. var _this = this;
  116426. if (value === this._captureCameraRenderTime) {
  116427. return;
  116428. }
  116429. this._captureCameraRenderTime = value;
  116430. if (value) {
  116431. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  116432. _this._cameraRenderTime.beginMonitoring();
  116433. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  116434. });
  116435. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  116436. _this._cameraRenderTime.endMonitoring(false);
  116437. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  116438. });
  116439. }
  116440. else {
  116441. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  116442. this._onBeforeCameraRenderObserver = null;
  116443. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  116444. this._onAfterCameraRenderObserver = null;
  116445. }
  116446. },
  116447. enumerable: true,
  116448. configurable: true
  116449. });
  116450. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  116451. /**
  116452. * Gets the perf counter used for draw calls
  116453. */
  116454. get: function () {
  116455. return this.scene.getEngine()._drawCalls;
  116456. },
  116457. enumerable: true,
  116458. configurable: true
  116459. });
  116460. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  116461. /**
  116462. * Gets the perf counter used for texture collisions
  116463. */
  116464. get: function () {
  116465. return this.scene.getEngine()._textureCollisions;
  116466. },
  116467. enumerable: true,
  116468. configurable: true
  116469. });
  116470. /**
  116471. * Dispose and release associated resources.
  116472. */
  116473. SceneInstrumentation.prototype.dispose = function () {
  116474. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  116475. this._onAfterRenderObserver = null;
  116476. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  116477. this._onBeforeActiveMeshesEvaluationObserver = null;
  116478. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  116479. this._onAfterActiveMeshesEvaluationObserver = null;
  116480. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  116481. this._onBeforeRenderTargetsRenderObserver = null;
  116482. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  116483. this._onAfterRenderTargetsRenderObserver = null;
  116484. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  116485. this._onBeforeAnimationsObserver = null;
  116486. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  116487. this._onBeforeParticlesRenderingObserver = null;
  116488. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  116489. this._onAfterParticlesRenderingObserver = null;
  116490. if (this._onBeforeSpritesRenderingObserver) {
  116491. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  116492. this._onBeforeSpritesRenderingObserver = null;
  116493. }
  116494. if (this._onAfterSpritesRenderingObserver) {
  116495. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  116496. this._onAfterSpritesRenderingObserver = null;
  116497. }
  116498. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  116499. this._onBeforeDrawPhaseObserver = null;
  116500. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  116501. this._onAfterDrawPhaseObserver = null;
  116502. if (this._onBeforePhysicsObserver) {
  116503. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  116504. this._onBeforePhysicsObserver = null;
  116505. }
  116506. if (this._onAfterPhysicsObserver) {
  116507. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  116508. this._onAfterPhysicsObserver = null;
  116509. }
  116510. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  116511. this._onAfterAnimationsObserver = null;
  116512. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  116513. this._onBeforeCameraRenderObserver = null;
  116514. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  116515. this._onAfterCameraRenderObserver = null;
  116516. this.scene = null;
  116517. };
  116518. return SceneInstrumentation;
  116519. }());
  116520. BABYLON.SceneInstrumentation = SceneInstrumentation;
  116521. })(BABYLON || (BABYLON = {}));
  116522. //# sourceMappingURL=sceneInstrumentation.js.map
  116523. var BABYLON;
  116524. (function (BABYLON) {
  116525. /**
  116526. * @hidden
  116527. **/
  116528. var _TimeToken = /** @class */ (function () {
  116529. function _TimeToken() {
  116530. this._timeElapsedQueryEnded = false;
  116531. }
  116532. return _TimeToken;
  116533. }());
  116534. BABYLON._TimeToken = _TimeToken;
  116535. })(BABYLON || (BABYLON = {}));
  116536. //# sourceMappingURL=timeToken.js.map
  116537. var BABYLON;
  116538. (function (BABYLON) {
  116539. /**
  116540. * Background material defines definition.
  116541. * @hidden Mainly internal Use
  116542. */
  116543. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  116544. __extends(BackgroundMaterialDefines, _super);
  116545. /**
  116546. * Constructor of the defines.
  116547. */
  116548. function BackgroundMaterialDefines() {
  116549. var _this = _super.call(this) || this;
  116550. /**
  116551. * True if the diffuse texture is in use.
  116552. */
  116553. _this.DIFFUSE = false;
  116554. /**
  116555. * The direct UV channel to use.
  116556. */
  116557. _this.DIFFUSEDIRECTUV = 0;
  116558. /**
  116559. * True if the diffuse texture is in gamma space.
  116560. */
  116561. _this.GAMMADIFFUSE = false;
  116562. /**
  116563. * True if the diffuse texture has opacity in the alpha channel.
  116564. */
  116565. _this.DIFFUSEHASALPHA = false;
  116566. /**
  116567. * True if you want the material to fade to transparent at grazing angle.
  116568. */
  116569. _this.OPACITYFRESNEL = false;
  116570. /**
  116571. * True if an extra blur needs to be added in the reflection.
  116572. */
  116573. _this.REFLECTIONBLUR = false;
  116574. /**
  116575. * True if you want the material to fade to reflection at grazing angle.
  116576. */
  116577. _this.REFLECTIONFRESNEL = false;
  116578. /**
  116579. * True if you want the material to falloff as far as you move away from the scene center.
  116580. */
  116581. _this.REFLECTIONFALLOFF = false;
  116582. /**
  116583. * False if the current Webgl implementation does not support the texture lod extension.
  116584. */
  116585. _this.TEXTURELODSUPPORT = false;
  116586. /**
  116587. * True to ensure the data are premultiplied.
  116588. */
  116589. _this.PREMULTIPLYALPHA = false;
  116590. /**
  116591. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  116592. */
  116593. _this.USERGBCOLOR = false;
  116594. /**
  116595. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  116596. * stays aligned with the desired configuration.
  116597. */
  116598. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  116599. /**
  116600. * True to add noise in order to reduce the banding effect.
  116601. */
  116602. _this.NOISE = false;
  116603. /**
  116604. * is the reflection texture in BGR color scheme?
  116605. * Mainly used to solve a bug in ios10 video tag
  116606. */
  116607. _this.REFLECTIONBGR = false;
  116608. _this.IMAGEPROCESSING = false;
  116609. _this.VIGNETTE = false;
  116610. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  116611. _this.VIGNETTEBLENDMODEOPAQUE = false;
  116612. _this.TONEMAPPING = false;
  116613. _this.TONEMAPPING_ACES = false;
  116614. _this.CONTRAST = false;
  116615. _this.COLORCURVES = false;
  116616. _this.COLORGRADING = false;
  116617. _this.COLORGRADING3D = false;
  116618. _this.SAMPLER3DGREENDEPTH = false;
  116619. _this.SAMPLER3DBGRMAP = false;
  116620. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  116621. _this.EXPOSURE = false;
  116622. // Reflection.
  116623. _this.REFLECTION = false;
  116624. _this.REFLECTIONMAP_3D = false;
  116625. _this.REFLECTIONMAP_SPHERICAL = false;
  116626. _this.REFLECTIONMAP_PLANAR = false;
  116627. _this.REFLECTIONMAP_CUBIC = false;
  116628. _this.REFLECTIONMAP_PROJECTION = false;
  116629. _this.REFLECTIONMAP_SKYBOX = false;
  116630. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  116631. _this.REFLECTIONMAP_EXPLICIT = false;
  116632. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  116633. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  116634. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  116635. _this.INVERTCUBICMAP = false;
  116636. _this.REFLECTIONMAP_OPPOSITEZ = false;
  116637. _this.LODINREFLECTIONALPHA = false;
  116638. _this.GAMMAREFLECTION = false;
  116639. _this.RGBDREFLECTION = false;
  116640. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  116641. // Default BJS.
  116642. _this.MAINUV1 = false;
  116643. _this.MAINUV2 = false;
  116644. _this.UV1 = false;
  116645. _this.UV2 = false;
  116646. _this.CLIPPLANE = false;
  116647. _this.CLIPPLANE2 = false;
  116648. _this.CLIPPLANE3 = false;
  116649. _this.CLIPPLANE4 = false;
  116650. _this.POINTSIZE = false;
  116651. _this.FOG = false;
  116652. _this.NORMAL = false;
  116653. _this.NUM_BONE_INFLUENCERS = 0;
  116654. _this.BonesPerMesh = 0;
  116655. _this.INSTANCES = false;
  116656. _this.SHADOWFLOAT = false;
  116657. _this.rebuild();
  116658. return _this;
  116659. }
  116660. return BackgroundMaterialDefines;
  116661. }(BABYLON.MaterialDefines));
  116662. /**
  116663. * Background material used to create an efficient environement around your scene.
  116664. */
  116665. var BackgroundMaterial = /** @class */ (function (_super) {
  116666. __extends(BackgroundMaterial, _super);
  116667. /**
  116668. * Instantiates a Background Material in the given scene
  116669. * @param name The friendly name of the material
  116670. * @param scene The scene to add the material to
  116671. */
  116672. function BackgroundMaterial(name, scene) {
  116673. var _this = _super.call(this, name, scene) || this;
  116674. /**
  116675. * Key light Color (multiply against the environement texture)
  116676. */
  116677. _this.primaryColor = BABYLON.Color3.White();
  116678. _this._primaryColorShadowLevel = 0;
  116679. _this._primaryColorHighlightLevel = 0;
  116680. /**
  116681. * Reflection Texture used in the material.
  116682. * Should be author in a specific way for the best result (refer to the documentation).
  116683. */
  116684. _this.reflectionTexture = null;
  116685. /**
  116686. * Reflection Texture level of blur.
  116687. *
  116688. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  116689. * texture twice.
  116690. */
  116691. _this.reflectionBlur = 0;
  116692. /**
  116693. * Diffuse Texture used in the material.
  116694. * Should be author in a specific way for the best result (refer to the documentation).
  116695. */
  116696. _this.diffuseTexture = null;
  116697. _this._shadowLights = null;
  116698. /**
  116699. * Specify the list of lights casting shadow on the material.
  116700. * All scene shadow lights will be included if null.
  116701. */
  116702. _this.shadowLights = null;
  116703. /**
  116704. * Helps adjusting the shadow to a softer level if required.
  116705. * 0 means black shadows and 1 means no shadows.
  116706. */
  116707. _this.shadowLevel = 0;
  116708. /**
  116709. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  116710. * It is usually zero but might be interesting to modify according to your setup.
  116711. */
  116712. _this.sceneCenter = BABYLON.Vector3.Zero();
  116713. /**
  116714. * This helps specifying that the material is falling off to the sky box at grazing angle.
  116715. * This helps ensuring a nice transition when the camera goes under the ground.
  116716. */
  116717. _this.opacityFresnel = true;
  116718. /**
  116719. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  116720. * This helps adding a mirror texture on the ground.
  116721. */
  116722. _this.reflectionFresnel = false;
  116723. /**
  116724. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  116725. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  116726. */
  116727. _this.reflectionFalloffDistance = 0.0;
  116728. /**
  116729. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  116730. */
  116731. _this.reflectionAmount = 1.0;
  116732. /**
  116733. * This specifies the weight of the reflection at grazing angle.
  116734. */
  116735. _this.reflectionReflectance0 = 0.05;
  116736. /**
  116737. * This specifies the weight of the reflection at a perpendicular point of view.
  116738. */
  116739. _this.reflectionReflectance90 = 0.5;
  116740. /**
  116741. * Helps to directly use the maps channels instead of their level.
  116742. */
  116743. _this.useRGBColor = true;
  116744. /**
  116745. * This helps reducing the banding effect that could occur on the background.
  116746. */
  116747. _this.enableNoise = false;
  116748. _this._fovMultiplier = 1.0;
  116749. /**
  116750. * Enable the FOV adjustment feature controlled by fovMultiplier.
  116751. */
  116752. _this.useEquirectangularFOV = false;
  116753. _this._maxSimultaneousLights = 4;
  116754. /**
  116755. * Number of Simultaneous lights allowed on the material.
  116756. */
  116757. _this.maxSimultaneousLights = 4;
  116758. /**
  116759. * Keep track of the image processing observer to allow dispose and replace.
  116760. */
  116761. _this._imageProcessingObserver = null;
  116762. /**
  116763. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  116764. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  116765. */
  116766. _this.switchToBGR = false;
  116767. // Temp values kept as cache in the material.
  116768. _this._renderTargets = new BABYLON.SmartArray(16);
  116769. _this._reflectionControls = BABYLON.Vector4.Zero();
  116770. _this._white = BABYLON.Color3.White();
  116771. _this._primaryShadowColor = BABYLON.Color3.Black();
  116772. _this._primaryHighlightColor = BABYLON.Color3.Black();
  116773. // Setup the default processing configuration to the scene.
  116774. _this._attachImageProcessingConfiguration(null);
  116775. _this.getRenderTargetTextures = function () {
  116776. _this._renderTargets.reset();
  116777. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  116778. _this._renderTargets.push(_this._diffuseTexture);
  116779. }
  116780. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  116781. _this._renderTargets.push(_this._reflectionTexture);
  116782. }
  116783. return _this._renderTargets;
  116784. };
  116785. return _this;
  116786. }
  116787. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  116788. /**
  116789. * Experimental Internal Use Only.
  116790. *
  116791. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  116792. * This acts as a helper to set the primary color to a more "human friendly" value.
  116793. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  116794. * output color as close as possible from the chosen value.
  116795. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  116796. * part of lighting setup.)
  116797. */
  116798. get: function () {
  116799. return this.__perceptualColor;
  116800. },
  116801. set: function (value) {
  116802. this.__perceptualColor = value;
  116803. this._computePrimaryColorFromPerceptualColor();
  116804. this._markAllSubMeshesAsLightsDirty();
  116805. },
  116806. enumerable: true,
  116807. configurable: true
  116808. });
  116809. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  116810. /**
  116811. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  116812. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  116813. */
  116814. get: function () {
  116815. return this._primaryColorShadowLevel;
  116816. },
  116817. set: function (value) {
  116818. this._primaryColorShadowLevel = value;
  116819. this._computePrimaryColors();
  116820. this._markAllSubMeshesAsLightsDirty();
  116821. },
  116822. enumerable: true,
  116823. configurable: true
  116824. });
  116825. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  116826. /**
  116827. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  116828. * The primary color is used at the level chosen to define what the white area would look.
  116829. */
  116830. get: function () {
  116831. return this._primaryColorHighlightLevel;
  116832. },
  116833. set: function (value) {
  116834. this._primaryColorHighlightLevel = value;
  116835. this._computePrimaryColors();
  116836. this._markAllSubMeshesAsLightsDirty();
  116837. },
  116838. enumerable: true,
  116839. configurable: true
  116840. });
  116841. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  116842. /**
  116843. * Sets the reflection reflectance fresnel values according to the default standard
  116844. * empirically know to work well :-)
  116845. */
  116846. set: function (value) {
  116847. var reflectionWeight = value;
  116848. if (reflectionWeight < 0.5) {
  116849. reflectionWeight = reflectionWeight * 2.0;
  116850. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  116851. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  116852. }
  116853. else {
  116854. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  116855. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  116856. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  116857. }
  116858. },
  116859. enumerable: true,
  116860. configurable: true
  116861. });
  116862. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  116863. /**
  116864. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  116865. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  116866. * Recommended to be keep at 1.0 except for special cases.
  116867. */
  116868. get: function () {
  116869. return this._fovMultiplier;
  116870. },
  116871. set: function (value) {
  116872. if (isNaN(value)) {
  116873. value = 1.0;
  116874. }
  116875. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  116876. },
  116877. enumerable: true,
  116878. configurable: true
  116879. });
  116880. /**
  116881. * Attaches a new image processing configuration to the PBR Material.
  116882. * @param configuration (if null the scene configuration will be use)
  116883. */
  116884. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  116885. var _this = this;
  116886. if (configuration === this._imageProcessingConfiguration) {
  116887. return;
  116888. }
  116889. // Detaches observer.
  116890. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  116891. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  116892. }
  116893. // Pick the scene configuration if needed.
  116894. if (!configuration) {
  116895. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  116896. }
  116897. else {
  116898. this._imageProcessingConfiguration = configuration;
  116899. }
  116900. // Attaches observer.
  116901. if (this._imageProcessingConfiguration) {
  116902. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  116903. _this._computePrimaryColorFromPerceptualColor();
  116904. _this._markAllSubMeshesAsImageProcessingDirty();
  116905. });
  116906. }
  116907. };
  116908. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  116909. /**
  116910. * Gets the image processing configuration used either in this material.
  116911. */
  116912. get: function () {
  116913. return this._imageProcessingConfiguration;
  116914. },
  116915. /**
  116916. * Sets the Default image processing configuration used either in the this material.
  116917. *
  116918. * If sets to null, the scene one is in use.
  116919. */
  116920. set: function (value) {
  116921. this._attachImageProcessingConfiguration(value);
  116922. // Ensure the effect will be rebuilt.
  116923. this._markAllSubMeshesAsTexturesDirty();
  116924. },
  116925. enumerable: true,
  116926. configurable: true
  116927. });
  116928. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  116929. /**
  116930. * Gets wether the color curves effect is enabled.
  116931. */
  116932. get: function () {
  116933. return this.imageProcessingConfiguration.colorCurvesEnabled;
  116934. },
  116935. /**
  116936. * Sets wether the color curves effect is enabled.
  116937. */
  116938. set: function (value) {
  116939. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  116940. },
  116941. enumerable: true,
  116942. configurable: true
  116943. });
  116944. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  116945. /**
  116946. * Gets wether the color grading effect is enabled.
  116947. */
  116948. get: function () {
  116949. return this.imageProcessingConfiguration.colorGradingEnabled;
  116950. },
  116951. /**
  116952. * Gets wether the color grading effect is enabled.
  116953. */
  116954. set: function (value) {
  116955. this.imageProcessingConfiguration.colorGradingEnabled = value;
  116956. },
  116957. enumerable: true,
  116958. configurable: true
  116959. });
  116960. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  116961. /**
  116962. * Gets wether tonemapping is enabled or not.
  116963. */
  116964. get: function () {
  116965. return this._imageProcessingConfiguration.toneMappingEnabled;
  116966. },
  116967. /**
  116968. * Sets wether tonemapping is enabled or not
  116969. */
  116970. set: function (value) {
  116971. this._imageProcessingConfiguration.toneMappingEnabled = value;
  116972. },
  116973. enumerable: true,
  116974. configurable: true
  116975. });
  116976. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  116977. /**
  116978. * The camera exposure used on this material.
  116979. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  116980. * This corresponds to a photographic exposure.
  116981. */
  116982. get: function () {
  116983. return this._imageProcessingConfiguration.exposure;
  116984. },
  116985. /**
  116986. * The camera exposure used on this material.
  116987. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  116988. * This corresponds to a photographic exposure.
  116989. */
  116990. set: function (value) {
  116991. this._imageProcessingConfiguration.exposure = value;
  116992. },
  116993. enumerable: true,
  116994. configurable: true
  116995. });
  116996. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  116997. /**
  116998. * Gets The camera contrast used on this material.
  116999. */
  117000. get: function () {
  117001. return this._imageProcessingConfiguration.contrast;
  117002. },
  117003. /**
  117004. * Sets The camera contrast used on this material.
  117005. */
  117006. set: function (value) {
  117007. this._imageProcessingConfiguration.contrast = value;
  117008. },
  117009. enumerable: true,
  117010. configurable: true
  117011. });
  117012. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  117013. /**
  117014. * Gets the Color Grading 2D Lookup Texture.
  117015. */
  117016. get: function () {
  117017. return this._imageProcessingConfiguration.colorGradingTexture;
  117018. },
  117019. /**
  117020. * Sets the Color Grading 2D Lookup Texture.
  117021. */
  117022. set: function (value) {
  117023. this.imageProcessingConfiguration.colorGradingTexture = value;
  117024. },
  117025. enumerable: true,
  117026. configurable: true
  117027. });
  117028. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  117029. /**
  117030. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  117031. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  117032. * 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;
  117033. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  117034. */
  117035. get: function () {
  117036. return this.imageProcessingConfiguration.colorCurves;
  117037. },
  117038. /**
  117039. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  117040. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  117041. * 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;
  117042. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  117043. */
  117044. set: function (value) {
  117045. this.imageProcessingConfiguration.colorCurves = value;
  117046. },
  117047. enumerable: true,
  117048. configurable: true
  117049. });
  117050. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  117051. /**
  117052. * Gets a boolean indicating that current material needs to register RTT
  117053. */
  117054. get: function () {
  117055. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  117056. return true;
  117057. }
  117058. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  117059. return true;
  117060. }
  117061. return false;
  117062. },
  117063. enumerable: true,
  117064. configurable: true
  117065. });
  117066. /**
  117067. * The entire material has been created in order to prevent overdraw.
  117068. * @returns false
  117069. */
  117070. BackgroundMaterial.prototype.needAlphaTesting = function () {
  117071. return true;
  117072. };
  117073. /**
  117074. * The entire material has been created in order to prevent overdraw.
  117075. * @returns true if blending is enable
  117076. */
  117077. BackgroundMaterial.prototype.needAlphaBlending = function () {
  117078. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  117079. };
  117080. /**
  117081. * Checks wether the material is ready to be rendered for a given mesh.
  117082. * @param mesh The mesh to render
  117083. * @param subMesh The submesh to check against
  117084. * @param useInstances Specify wether or not the material is used with instances
  117085. * @returns true if all the dependencies are ready (Textures, Effects...)
  117086. */
  117087. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  117088. var _this = this;
  117089. if (useInstances === void 0) { useInstances = false; }
  117090. if (subMesh.effect && this.isFrozen) {
  117091. if (this._wasPreviouslyReady) {
  117092. return true;
  117093. }
  117094. }
  117095. if (!subMesh._materialDefines) {
  117096. subMesh._materialDefines = new BackgroundMaterialDefines();
  117097. }
  117098. var scene = this.getScene();
  117099. var defines = subMesh._materialDefines;
  117100. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  117101. if (defines._renderId === scene.getRenderId()) {
  117102. return true;
  117103. }
  117104. }
  117105. var engine = scene.getEngine();
  117106. // Lights
  117107. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  117108. defines._needNormals = true;
  117109. // Textures
  117110. if (defines._areTexturesDirty) {
  117111. defines._needUVs = false;
  117112. if (scene.texturesEnabled) {
  117113. if (scene.getEngine().getCaps().textureLOD) {
  117114. defines.TEXTURELODSUPPORT = true;
  117115. }
  117116. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  117117. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  117118. return false;
  117119. }
  117120. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  117121. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  117122. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  117123. defines.OPACITYFRESNEL = this._opacityFresnel;
  117124. }
  117125. else {
  117126. defines.DIFFUSE = false;
  117127. defines.DIFFUSEHASALPHA = false;
  117128. defines.GAMMADIFFUSE = false;
  117129. defines.OPACITYFRESNEL = false;
  117130. }
  117131. var reflectionTexture = this._reflectionTexture;
  117132. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  117133. if (!reflectionTexture.isReadyOrNotBlocking()) {
  117134. return false;
  117135. }
  117136. defines.REFLECTION = true;
  117137. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  117138. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  117139. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  117140. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  117141. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  117142. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  117143. defines.REFLECTIONBGR = this.switchToBGR;
  117144. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  117145. defines.INVERTCUBICMAP = true;
  117146. }
  117147. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  117148. switch (reflectionTexture.coordinatesMode) {
  117149. case BABYLON.Texture.EXPLICIT_MODE:
  117150. defines.REFLECTIONMAP_EXPLICIT = true;
  117151. break;
  117152. case BABYLON.Texture.PLANAR_MODE:
  117153. defines.REFLECTIONMAP_PLANAR = true;
  117154. break;
  117155. case BABYLON.Texture.PROJECTION_MODE:
  117156. defines.REFLECTIONMAP_PROJECTION = true;
  117157. break;
  117158. case BABYLON.Texture.SKYBOX_MODE:
  117159. defines.REFLECTIONMAP_SKYBOX = true;
  117160. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  117161. break;
  117162. case BABYLON.Texture.SPHERICAL_MODE:
  117163. defines.REFLECTIONMAP_SPHERICAL = true;
  117164. break;
  117165. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  117166. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  117167. break;
  117168. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  117169. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  117170. break;
  117171. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  117172. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  117173. break;
  117174. case BABYLON.Texture.CUBIC_MODE:
  117175. case BABYLON.Texture.INVCUBIC_MODE:
  117176. default:
  117177. defines.REFLECTIONMAP_CUBIC = true;
  117178. break;
  117179. }
  117180. if (this.reflectionFresnel) {
  117181. defines.REFLECTIONFRESNEL = true;
  117182. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  117183. this._reflectionControls.x = this.reflectionAmount;
  117184. this._reflectionControls.y = this.reflectionReflectance0;
  117185. this._reflectionControls.z = this.reflectionReflectance90;
  117186. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  117187. }
  117188. else {
  117189. defines.REFLECTIONFRESNEL = false;
  117190. defines.REFLECTIONFALLOFF = false;
  117191. }
  117192. }
  117193. else {
  117194. defines.REFLECTION = false;
  117195. defines.REFLECTIONFRESNEL = false;
  117196. defines.REFLECTIONFALLOFF = false;
  117197. defines.REFLECTIONBLUR = false;
  117198. defines.REFLECTIONMAP_3D = false;
  117199. defines.REFLECTIONMAP_SPHERICAL = false;
  117200. defines.REFLECTIONMAP_PLANAR = false;
  117201. defines.REFLECTIONMAP_CUBIC = false;
  117202. defines.REFLECTIONMAP_PROJECTION = false;
  117203. defines.REFLECTIONMAP_SKYBOX = false;
  117204. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  117205. defines.REFLECTIONMAP_EXPLICIT = false;
  117206. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  117207. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  117208. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  117209. defines.INVERTCUBICMAP = false;
  117210. defines.REFLECTIONMAP_OPPOSITEZ = false;
  117211. defines.LODINREFLECTIONALPHA = false;
  117212. defines.GAMMAREFLECTION = false;
  117213. defines.RGBDREFLECTION = false;
  117214. }
  117215. }
  117216. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  117217. defines.USERGBCOLOR = this._useRGBColor;
  117218. defines.NOISE = this._enableNoise;
  117219. }
  117220. if (defines._areLightsDirty) {
  117221. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  117222. }
  117223. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  117224. if (!this._imageProcessingConfiguration.isReady()) {
  117225. return false;
  117226. }
  117227. this._imageProcessingConfiguration.prepareDefines(defines);
  117228. }
  117229. // Misc.
  117230. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  117231. // Values that need to be evaluated on every frame
  117232. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  117233. // Attribs
  117234. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  117235. if (mesh) {
  117236. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  117237. mesh.createNormals(true);
  117238. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  117239. }
  117240. }
  117241. }
  117242. // Get correct effect
  117243. if (defines.isDirty) {
  117244. defines.markAsProcessed();
  117245. scene.resetCachedMaterial();
  117246. // Fallbacks
  117247. var fallbacks = new BABYLON.EffectFallbacks();
  117248. if (defines.FOG) {
  117249. fallbacks.addFallback(0, "FOG");
  117250. }
  117251. if (defines.POINTSIZE) {
  117252. fallbacks.addFallback(1, "POINTSIZE");
  117253. }
  117254. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  117255. if (defines.NUM_BONE_INFLUENCERS > 0) {
  117256. fallbacks.addCPUSkinningFallback(0, mesh);
  117257. }
  117258. //Attributes
  117259. var attribs = [BABYLON.VertexBuffer.PositionKind];
  117260. if (defines.NORMAL) {
  117261. attribs.push(BABYLON.VertexBuffer.NormalKind);
  117262. }
  117263. if (defines.UV1) {
  117264. attribs.push(BABYLON.VertexBuffer.UVKind);
  117265. }
  117266. if (defines.UV2) {
  117267. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  117268. }
  117269. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  117270. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  117271. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  117272. "vFogInfos", "vFogColor", "pointSize",
  117273. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  117274. "vPrimaryColor", "vPrimaryColorShadow",
  117275. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  117276. "shadowLevel", "alpha",
  117277. "vBackgroundCenter", "vReflectionControl",
  117278. "vDiffuseInfos", "diffuseMatrix",
  117279. ];
  117280. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  117281. var uniformBuffers = ["Material", "Scene"];
  117282. if (BABYLON.ImageProcessingConfiguration) {
  117283. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  117284. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  117285. }
  117286. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  117287. uniformsNames: uniforms,
  117288. uniformBuffersNames: uniformBuffers,
  117289. samplers: samplers,
  117290. defines: defines,
  117291. maxSimultaneousLights: this._maxSimultaneousLights
  117292. });
  117293. var onCompiled = function (effect) {
  117294. if (_this.onCompiled) {
  117295. _this.onCompiled(effect);
  117296. }
  117297. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  117298. };
  117299. var join = defines.toString();
  117300. subMesh.setEffect(scene.getEngine().createEffect("background", {
  117301. attributes: attribs,
  117302. uniformsNames: uniforms,
  117303. uniformBuffersNames: uniformBuffers,
  117304. samplers: samplers,
  117305. defines: join,
  117306. fallbacks: fallbacks,
  117307. onCompiled: onCompiled,
  117308. onError: this.onError,
  117309. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  117310. }, engine), defines);
  117311. this.buildUniformLayout();
  117312. }
  117313. if (!subMesh.effect || !subMesh.effect.isReady()) {
  117314. return false;
  117315. }
  117316. defines._renderId = scene.getRenderId();
  117317. this._wasPreviouslyReady = true;
  117318. return true;
  117319. };
  117320. /**
  117321. * Compute the primary color according to the chosen perceptual color.
  117322. */
  117323. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  117324. if (!this.__perceptualColor) {
  117325. return;
  117326. }
  117327. this._primaryColor.copyFrom(this.__perceptualColor);
  117328. // Revert gamma space.
  117329. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  117330. // Revert image processing configuration.
  117331. if (this._imageProcessingConfiguration) {
  117332. // Revert Exposure.
  117333. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  117334. }
  117335. this._computePrimaryColors();
  117336. };
  117337. /**
  117338. * Compute the highlights and shadow colors according to their chosen levels.
  117339. */
  117340. BackgroundMaterial.prototype._computePrimaryColors = function () {
  117341. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  117342. return;
  117343. }
  117344. // Find the highlight color based on the configuration.
  117345. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  117346. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  117347. // Find the shadow color based on the configuration.
  117348. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  117349. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  117350. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  117351. };
  117352. /**
  117353. * Build the uniform buffer used in the material.
  117354. */
  117355. BackgroundMaterial.prototype.buildUniformLayout = function () {
  117356. // Order is important !
  117357. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  117358. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  117359. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  117360. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  117361. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  117362. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  117363. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  117364. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  117365. this._uniformBuffer.addUniform("pointSize", 1);
  117366. this._uniformBuffer.addUniform("shadowLevel", 1);
  117367. this._uniformBuffer.addUniform("alpha", 1);
  117368. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  117369. this._uniformBuffer.addUniform("vReflectionControl", 4);
  117370. this._uniformBuffer.create();
  117371. };
  117372. /**
  117373. * Unbind the material.
  117374. */
  117375. BackgroundMaterial.prototype.unbind = function () {
  117376. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  117377. this._uniformBuffer.setTexture("diffuseSampler", null);
  117378. }
  117379. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  117380. this._uniformBuffer.setTexture("reflectionSampler", null);
  117381. }
  117382. _super.prototype.unbind.call(this);
  117383. };
  117384. /**
  117385. * Bind only the world matrix to the material.
  117386. * @param world The world matrix to bind.
  117387. */
  117388. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  117389. this._activeEffect.setMatrix("world", world);
  117390. };
  117391. /**
  117392. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  117393. * @param world The world matrix to bind.
  117394. * @param subMesh The submesh to bind for.
  117395. */
  117396. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  117397. var scene = this.getScene();
  117398. var defines = subMesh._materialDefines;
  117399. if (!defines) {
  117400. return;
  117401. }
  117402. var effect = subMesh.effect;
  117403. if (!effect) {
  117404. return;
  117405. }
  117406. this._activeEffect = effect;
  117407. // Matrices
  117408. this.bindOnlyWorldMatrix(world);
  117409. // Bones
  117410. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  117411. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  117412. if (mustRebind) {
  117413. this._uniformBuffer.bindToEffect(effect, "Material");
  117414. this.bindViewProjection(effect);
  117415. var reflectionTexture = this._reflectionTexture;
  117416. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  117417. // Texture uniforms
  117418. if (scene.texturesEnabled) {
  117419. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  117420. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  117421. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  117422. }
  117423. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  117424. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  117425. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  117426. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  117427. }
  117428. }
  117429. if (this.shadowLevel > 0) {
  117430. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  117431. }
  117432. this._uniformBuffer.updateFloat("alpha", this.alpha);
  117433. // Point size
  117434. if (this.pointsCloud) {
  117435. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  117436. }
  117437. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  117438. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  117439. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  117440. }
  117441. else {
  117442. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  117443. }
  117444. }
  117445. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  117446. // Textures
  117447. if (scene.texturesEnabled) {
  117448. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  117449. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  117450. }
  117451. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  117452. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  117453. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  117454. }
  117455. else if (!defines.REFLECTIONBLUR) {
  117456. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  117457. }
  117458. else {
  117459. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  117460. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  117461. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  117462. }
  117463. if (defines.REFLECTIONFRESNEL) {
  117464. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  117465. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  117466. }
  117467. }
  117468. }
  117469. // Clip plane
  117470. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  117471. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  117472. }
  117473. if (mustRebind || !this.isFrozen) {
  117474. if (scene.lightsEnabled) {
  117475. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  117476. }
  117477. // View
  117478. this.bindView(effect);
  117479. // Fog
  117480. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  117481. // image processing
  117482. if (this._imageProcessingConfiguration) {
  117483. this._imageProcessingConfiguration.bind(this._activeEffect);
  117484. }
  117485. }
  117486. this._uniformBuffer.update();
  117487. this._afterBind(mesh, this._activeEffect);
  117488. };
  117489. /**
  117490. * Dispose the material.
  117491. * @param forceDisposeEffect Force disposal of the associated effect.
  117492. * @param forceDisposeTextures Force disposal of the associated textures.
  117493. */
  117494. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  117495. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  117496. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  117497. if (forceDisposeTextures) {
  117498. if (this.diffuseTexture) {
  117499. this.diffuseTexture.dispose();
  117500. }
  117501. if (this.reflectionTexture) {
  117502. this.reflectionTexture.dispose();
  117503. }
  117504. }
  117505. this._renderTargets.dispose();
  117506. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  117507. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  117508. }
  117509. _super.prototype.dispose.call(this, forceDisposeEffect);
  117510. };
  117511. /**
  117512. * Clones the material.
  117513. * @param name The cloned name.
  117514. * @returns The cloned material.
  117515. */
  117516. BackgroundMaterial.prototype.clone = function (name) {
  117517. var _this = this;
  117518. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  117519. };
  117520. /**
  117521. * Serializes the current material to its JSON representation.
  117522. * @returns The JSON representation.
  117523. */
  117524. BackgroundMaterial.prototype.serialize = function () {
  117525. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  117526. serializationObject.customType = "BABYLON.BackgroundMaterial";
  117527. return serializationObject;
  117528. };
  117529. /**
  117530. * Gets the class name of the material
  117531. * @returns "BackgroundMaterial"
  117532. */
  117533. BackgroundMaterial.prototype.getClassName = function () {
  117534. return "BackgroundMaterial";
  117535. };
  117536. /**
  117537. * Parse a JSON input to create back a background material.
  117538. * @param source The JSON data to parse
  117539. * @param scene The scene to create the parsed material in
  117540. * @param rootUrl The root url of the assets the material depends upon
  117541. * @returns the instantiated BackgroundMaterial.
  117542. */
  117543. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  117544. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  117545. };
  117546. /**
  117547. * Standard reflectance value at parallel view angle.
  117548. */
  117549. BackgroundMaterial.StandardReflectance0 = 0.05;
  117550. /**
  117551. * Standard reflectance value at grazing angle.
  117552. */
  117553. BackgroundMaterial.StandardReflectance90 = 0.5;
  117554. __decorate([
  117555. BABYLON.serializeAsColor3()
  117556. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  117557. __decorate([
  117558. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  117559. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  117560. __decorate([
  117561. BABYLON.serializeAsColor3()
  117562. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  117563. __decorate([
  117564. BABYLON.serialize()
  117565. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  117566. __decorate([
  117567. BABYLON.serialize()
  117568. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  117569. __decorate([
  117570. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  117571. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  117572. __decorate([
  117573. BABYLON.serializeAsTexture()
  117574. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  117575. __decorate([
  117576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117577. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  117578. __decorate([
  117579. BABYLON.serialize()
  117580. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  117581. __decorate([
  117582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117583. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  117584. __decorate([
  117585. BABYLON.serializeAsTexture()
  117586. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  117587. __decorate([
  117588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117589. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  117590. __decorate([
  117591. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117592. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  117593. __decorate([
  117594. BABYLON.serialize()
  117595. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  117596. __decorate([
  117597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117598. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  117599. __decorate([
  117600. BABYLON.serializeAsVector3()
  117601. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  117602. __decorate([
  117603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117604. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  117605. __decorate([
  117606. BABYLON.serialize()
  117607. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  117608. __decorate([
  117609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117610. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  117611. __decorate([
  117612. BABYLON.serialize()
  117613. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  117614. __decorate([
  117615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117616. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  117617. __decorate([
  117618. BABYLON.serialize()
  117619. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  117620. __decorate([
  117621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117622. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  117623. __decorate([
  117624. BABYLON.serialize()
  117625. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  117626. __decorate([
  117627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117628. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  117629. __decorate([
  117630. BABYLON.serialize()
  117631. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  117632. __decorate([
  117633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117634. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  117635. __decorate([
  117636. BABYLON.serialize()
  117637. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  117638. __decorate([
  117639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117640. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  117641. __decorate([
  117642. BABYLON.serialize()
  117643. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  117644. __decorate([
  117645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117646. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  117647. __decorate([
  117648. BABYLON.serialize()
  117649. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  117650. __decorate([
  117651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117652. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  117653. __decorate([
  117654. BABYLON.serialize()
  117655. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  117656. __decorate([
  117657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  117658. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  117659. __decorate([
  117660. BABYLON.serializeAsImageProcessingConfiguration()
  117661. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  117662. return BackgroundMaterial;
  117663. }(BABYLON.PushMaterial));
  117664. BABYLON.BackgroundMaterial = BackgroundMaterial;
  117665. })(BABYLON || (BABYLON = {}));
  117666. //# sourceMappingURL=backgroundMaterial.js.map
  117667. var __assign = (this && this.__assign) || function () {
  117668. __assign = Object.assign || function(t) {
  117669. for (var s, i = 1, n = arguments.length; i < n; i++) {
  117670. s = arguments[i];
  117671. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  117672. t[p] = s[p];
  117673. }
  117674. return t;
  117675. };
  117676. return __assign.apply(this, arguments);
  117677. };
  117678. var BABYLON;
  117679. (function (BABYLON) {
  117680. /**
  117681. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  117682. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  117683. * It also helps with the default setup of your imageProcessing configuration.
  117684. */
  117685. var EnvironmentHelper = /** @class */ (function () {
  117686. /**
  117687. * constructor
  117688. * @param options
  117689. * @param scene The scene to add the material to
  117690. */
  117691. function EnvironmentHelper(options, scene) {
  117692. var _this = this;
  117693. this._errorHandler = function (message, exception) {
  117694. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  117695. };
  117696. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  117697. this._scene = scene;
  117698. this.onErrorObservable = new BABYLON.Observable();
  117699. this._setupBackground();
  117700. this._setupImageProcessing();
  117701. }
  117702. /**
  117703. * Creates the default options for the helper.
  117704. */
  117705. EnvironmentHelper._getDefaultOptions = function () {
  117706. return {
  117707. createGround: true,
  117708. groundSize: 15,
  117709. groundTexture: this._groundTextureCDNUrl,
  117710. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  117711. groundOpacity: 0.9,
  117712. enableGroundShadow: true,
  117713. groundShadowLevel: 0.5,
  117714. enableGroundMirror: false,
  117715. groundMirrorSizeRatio: 0.3,
  117716. groundMirrorBlurKernel: 64,
  117717. groundMirrorAmount: 1,
  117718. groundMirrorFresnelWeight: 1,
  117719. groundMirrorFallOffDistance: 0,
  117720. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  117721. groundYBias: 0.00001,
  117722. createSkybox: true,
  117723. skyboxSize: 20,
  117724. skyboxTexture: this._skyboxTextureCDNUrl,
  117725. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  117726. backgroundYRotation: 0,
  117727. sizeAuto: true,
  117728. rootPosition: BABYLON.Vector3.Zero(),
  117729. setupImageProcessing: true,
  117730. environmentTexture: this._environmentTextureCDNUrl,
  117731. cameraExposure: 0.8,
  117732. cameraContrast: 1.2,
  117733. toneMappingEnabled: true,
  117734. };
  117735. };
  117736. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  117737. /**
  117738. * Gets the root mesh created by the helper.
  117739. */
  117740. get: function () {
  117741. return this._rootMesh;
  117742. },
  117743. enumerable: true,
  117744. configurable: true
  117745. });
  117746. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  117747. /**
  117748. * Gets the skybox created by the helper.
  117749. */
  117750. get: function () {
  117751. return this._skybox;
  117752. },
  117753. enumerable: true,
  117754. configurable: true
  117755. });
  117756. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  117757. /**
  117758. * Gets the skybox texture created by the helper.
  117759. */
  117760. get: function () {
  117761. return this._skyboxTexture;
  117762. },
  117763. enumerable: true,
  117764. configurable: true
  117765. });
  117766. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  117767. /**
  117768. * Gets the skybox material created by the helper.
  117769. */
  117770. get: function () {
  117771. return this._skyboxMaterial;
  117772. },
  117773. enumerable: true,
  117774. configurable: true
  117775. });
  117776. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  117777. /**
  117778. * Gets the ground mesh created by the helper.
  117779. */
  117780. get: function () {
  117781. return this._ground;
  117782. },
  117783. enumerable: true,
  117784. configurable: true
  117785. });
  117786. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  117787. /**
  117788. * Gets the ground texture created by the helper.
  117789. */
  117790. get: function () {
  117791. return this._groundTexture;
  117792. },
  117793. enumerable: true,
  117794. configurable: true
  117795. });
  117796. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  117797. /**
  117798. * Gets the ground mirror created by the helper.
  117799. */
  117800. get: function () {
  117801. return this._groundMirror;
  117802. },
  117803. enumerable: true,
  117804. configurable: true
  117805. });
  117806. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  117807. /**
  117808. * Gets the ground mirror render list to helps pushing the meshes
  117809. * you wish in the ground reflection.
  117810. */
  117811. get: function () {
  117812. if (this._groundMirror) {
  117813. return this._groundMirror.renderList;
  117814. }
  117815. return null;
  117816. },
  117817. enumerable: true,
  117818. configurable: true
  117819. });
  117820. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  117821. /**
  117822. * Gets the ground material created by the helper.
  117823. */
  117824. get: function () {
  117825. return this._groundMaterial;
  117826. },
  117827. enumerable: true,
  117828. configurable: true
  117829. });
  117830. /**
  117831. * Updates the background according to the new options
  117832. * @param options
  117833. */
  117834. EnvironmentHelper.prototype.updateOptions = function (options) {
  117835. var newOptions = __assign({}, this._options, options);
  117836. if (this._ground && !newOptions.createGround) {
  117837. this._ground.dispose();
  117838. this._ground = null;
  117839. }
  117840. if (this._groundMaterial && !newOptions.createGround) {
  117841. this._groundMaterial.dispose();
  117842. this._groundMaterial = null;
  117843. }
  117844. if (this._groundTexture) {
  117845. if (this._options.groundTexture != newOptions.groundTexture) {
  117846. this._groundTexture.dispose();
  117847. this._groundTexture = null;
  117848. }
  117849. }
  117850. if (this._skybox && !newOptions.createSkybox) {
  117851. this._skybox.dispose();
  117852. this._skybox = null;
  117853. }
  117854. if (this._skyboxMaterial && !newOptions.createSkybox) {
  117855. this._skyboxMaterial.dispose();
  117856. this._skyboxMaterial = null;
  117857. }
  117858. if (this._skyboxTexture) {
  117859. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  117860. this._skyboxTexture.dispose();
  117861. this._skyboxTexture = null;
  117862. }
  117863. }
  117864. if (this._groundMirror && !newOptions.enableGroundMirror) {
  117865. this._groundMirror.dispose();
  117866. this._groundMirror = null;
  117867. }
  117868. if (this._scene.environmentTexture) {
  117869. if (this._options.environmentTexture != newOptions.environmentTexture) {
  117870. this._scene.environmentTexture.dispose();
  117871. }
  117872. }
  117873. this._options = newOptions;
  117874. this._setupBackground();
  117875. this._setupImageProcessing();
  117876. };
  117877. /**
  117878. * Sets the primary color of all the available elements.
  117879. * @param color the main color to affect to the ground and the background
  117880. */
  117881. EnvironmentHelper.prototype.setMainColor = function (color) {
  117882. if (this.groundMaterial) {
  117883. this.groundMaterial.primaryColor = color;
  117884. }
  117885. if (this.skyboxMaterial) {
  117886. this.skyboxMaterial.primaryColor = color;
  117887. }
  117888. if (this.groundMirror) {
  117889. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  117890. }
  117891. };
  117892. /**
  117893. * Setup the image processing according to the specified options.
  117894. */
  117895. EnvironmentHelper.prototype._setupImageProcessing = function () {
  117896. if (this._options.setupImageProcessing) {
  117897. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  117898. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  117899. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  117900. this._setupEnvironmentTexture();
  117901. }
  117902. };
  117903. /**
  117904. * Setup the environment texture according to the specified options.
  117905. */
  117906. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  117907. if (this._scene.environmentTexture) {
  117908. return;
  117909. }
  117910. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  117911. this._scene.environmentTexture = this._options.environmentTexture;
  117912. return;
  117913. }
  117914. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  117915. this._scene.environmentTexture = environmentTexture;
  117916. };
  117917. /**
  117918. * Setup the background according to the specified options.
  117919. */
  117920. EnvironmentHelper.prototype._setupBackground = function () {
  117921. if (!this._rootMesh) {
  117922. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  117923. }
  117924. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  117925. var sceneSize = this._getSceneSize();
  117926. if (this._options.createGround) {
  117927. this._setupGround(sceneSize);
  117928. this._setupGroundMaterial();
  117929. this._setupGroundDiffuseTexture();
  117930. if (this._options.enableGroundMirror) {
  117931. this._setupGroundMirrorTexture(sceneSize);
  117932. }
  117933. this._setupMirrorInGroundMaterial();
  117934. }
  117935. if (this._options.createSkybox) {
  117936. this._setupSkybox(sceneSize);
  117937. this._setupSkyboxMaterial();
  117938. this._setupSkyboxReflectionTexture();
  117939. }
  117940. this._rootMesh.position.x = sceneSize.rootPosition.x;
  117941. this._rootMesh.position.z = sceneSize.rootPosition.z;
  117942. this._rootMesh.position.y = sceneSize.rootPosition.y;
  117943. };
  117944. /**
  117945. * Get the scene sizes according to the setup.
  117946. */
  117947. EnvironmentHelper.prototype._getSceneSize = function () {
  117948. var _this = this;
  117949. var groundSize = this._options.groundSize;
  117950. var skyboxSize = this._options.skyboxSize;
  117951. var rootPosition = this._options.rootPosition;
  117952. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  117953. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  117954. }
  117955. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  117956. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  117957. });
  117958. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  117959. if (this._options.sizeAuto) {
  117960. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  117961. this._scene.activeCamera.upperRadiusLimit) {
  117962. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  117963. skyboxSize = groundSize;
  117964. }
  117965. var sceneDiagonalLenght = sceneDiagonal.length();
  117966. if (sceneDiagonalLenght > groundSize) {
  117967. groundSize = sceneDiagonalLenght * 2;
  117968. skyboxSize = groundSize;
  117969. }
  117970. // 10 % bigger.
  117971. groundSize *= 1.1;
  117972. skyboxSize *= 1.5;
  117973. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  117974. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  117975. }
  117976. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  117977. };
  117978. /**
  117979. * Setup the ground according to the specified options.
  117980. */
  117981. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  117982. var _this = this;
  117983. if (!this._ground || this._ground.isDisposed()) {
  117984. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  117985. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  117986. this._ground.parent = this._rootMesh;
  117987. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  117988. }
  117989. this._ground.receiveShadows = this._options.enableGroundShadow;
  117990. };
  117991. /**
  117992. * Setup the ground material according to the specified options.
  117993. */
  117994. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  117995. if (!this._groundMaterial) {
  117996. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  117997. }
  117998. this._groundMaterial.alpha = this._options.groundOpacity;
  117999. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  118000. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  118001. this._groundMaterial.primaryColor = this._options.groundColor;
  118002. this._groundMaterial.useRGBColor = false;
  118003. this._groundMaterial.enableNoise = true;
  118004. if (this._ground) {
  118005. this._ground.material = this._groundMaterial;
  118006. }
  118007. };
  118008. /**
  118009. * Setup the ground diffuse texture according to the specified options.
  118010. */
  118011. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  118012. if (!this._groundMaterial) {
  118013. return;
  118014. }
  118015. if (this._groundTexture) {
  118016. return;
  118017. }
  118018. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  118019. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  118020. return;
  118021. }
  118022. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  118023. diffuseTexture.gammaSpace = false;
  118024. diffuseTexture.hasAlpha = true;
  118025. this._groundMaterial.diffuseTexture = diffuseTexture;
  118026. };
  118027. /**
  118028. * Setup the ground mirror texture according to the specified options.
  118029. */
  118030. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  118031. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  118032. if (!this._groundMirror) {
  118033. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  118034. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  118035. this._groundMirror.anisotropicFilteringLevel = 1;
  118036. this._groundMirror.wrapU = wrapping;
  118037. this._groundMirror.wrapV = wrapping;
  118038. this._groundMirror.gammaSpace = false;
  118039. if (this._groundMirror.renderList) {
  118040. for (var i = 0; i < this._scene.meshes.length; i++) {
  118041. var mesh = this._scene.meshes[i];
  118042. if (mesh !== this._ground &&
  118043. mesh !== this._skybox &&
  118044. mesh !== this._rootMesh) {
  118045. this._groundMirror.renderList.push(mesh);
  118046. }
  118047. }
  118048. }
  118049. }
  118050. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  118051. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  118052. };
  118053. /**
  118054. * Setup the ground to receive the mirror texture.
  118055. */
  118056. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  118057. if (this._groundMaterial) {
  118058. this._groundMaterial.reflectionTexture = this._groundMirror;
  118059. this._groundMaterial.reflectionFresnel = true;
  118060. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  118061. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  118062. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  118063. }
  118064. };
  118065. /**
  118066. * Setup the skybox according to the specified options.
  118067. */
  118068. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  118069. var _this = this;
  118070. if (!this._skybox || this._skybox.isDisposed()) {
  118071. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  118072. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  118073. }
  118074. this._skybox.parent = this._rootMesh;
  118075. };
  118076. /**
  118077. * Setup the skybox material according to the specified options.
  118078. */
  118079. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  118080. if (!this._skybox) {
  118081. return;
  118082. }
  118083. if (!this._skyboxMaterial) {
  118084. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  118085. }
  118086. this._skyboxMaterial.useRGBColor = false;
  118087. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  118088. this._skyboxMaterial.enableNoise = true;
  118089. this._skybox.material = this._skyboxMaterial;
  118090. };
  118091. /**
  118092. * Setup the skybox reflection texture according to the specified options.
  118093. */
  118094. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  118095. if (!this._skyboxMaterial) {
  118096. return;
  118097. }
  118098. if (this._skyboxTexture) {
  118099. return;
  118100. }
  118101. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  118102. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  118103. return;
  118104. }
  118105. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  118106. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  118107. this._skyboxTexture.gammaSpace = false;
  118108. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  118109. };
  118110. /**
  118111. * Dispose all the elements created by the Helper.
  118112. */
  118113. EnvironmentHelper.prototype.dispose = function () {
  118114. if (this._groundMaterial) {
  118115. this._groundMaterial.dispose(true, true);
  118116. }
  118117. if (this._skyboxMaterial) {
  118118. this._skyboxMaterial.dispose(true, true);
  118119. }
  118120. this._rootMesh.dispose(false);
  118121. };
  118122. /**
  118123. * Default ground texture URL.
  118124. */
  118125. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  118126. /**
  118127. * Default skybox texture URL.
  118128. */
  118129. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  118130. /**
  118131. * Default environment texture URL.
  118132. */
  118133. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  118134. return EnvironmentHelper;
  118135. }());
  118136. BABYLON.EnvironmentHelper = EnvironmentHelper;
  118137. })(BABYLON || (BABYLON = {}));
  118138. //# sourceMappingURL=environmentHelper.js.map
  118139. var BABYLON;
  118140. (function (BABYLON) {
  118141. /** Internal class used to store shapes for emitters */
  118142. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  118143. function ParticleSystemSetEmitterCreationOptions() {
  118144. }
  118145. return ParticleSystemSetEmitterCreationOptions;
  118146. }());
  118147. /**
  118148. * Represents a set of particle systems working together to create a specific effect
  118149. */
  118150. var ParticleSystemSet = /** @class */ (function () {
  118151. function ParticleSystemSet() {
  118152. /**
  118153. * Gets the particle system list
  118154. */
  118155. this.systems = new Array();
  118156. }
  118157. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  118158. /**
  118159. * Gets the emitter node used with this set
  118160. */
  118161. get: function () {
  118162. return this._emitterNode;
  118163. },
  118164. enumerable: true,
  118165. configurable: true
  118166. });
  118167. /**
  118168. * Creates a new emitter mesh as a sphere
  118169. * @param options defines the options used to create the sphere
  118170. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  118171. * @param scene defines the hosting scene
  118172. */
  118173. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  118174. if (this._emitterNode) {
  118175. this._emitterNode.dispose();
  118176. }
  118177. this._emitterCreationOptions = {
  118178. kind: "Sphere",
  118179. options: options,
  118180. renderingGroupId: renderingGroupId
  118181. };
  118182. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  118183. emitterMesh.renderingGroupId = renderingGroupId;
  118184. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  118185. material.emissiveColor = options.color;
  118186. emitterMesh.material = material;
  118187. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  118188. var system = _a[_i];
  118189. system.emitter = emitterMesh;
  118190. }
  118191. this._emitterNode = emitterMesh;
  118192. };
  118193. /**
  118194. * Starts all particle systems of the set
  118195. * @param emitter defines an optional mesh to use as emitter for the particle systems
  118196. */
  118197. ParticleSystemSet.prototype.start = function (emitter) {
  118198. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  118199. var system = _a[_i];
  118200. if (emitter) {
  118201. system.emitter = emitter;
  118202. }
  118203. system.start();
  118204. }
  118205. };
  118206. /**
  118207. * Release all associated resources
  118208. */
  118209. ParticleSystemSet.prototype.dispose = function () {
  118210. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  118211. var system = _a[_i];
  118212. system.dispose();
  118213. }
  118214. this.systems = [];
  118215. if (this._emitterNode) {
  118216. this._emitterNode.dispose();
  118217. this._emitterNode = null;
  118218. }
  118219. };
  118220. /**
  118221. * Serialize the set into a JSON compatible object
  118222. * @returns a JSON compatible representation of the set
  118223. */
  118224. ParticleSystemSet.prototype.serialize = function () {
  118225. var result = {};
  118226. result.systems = [];
  118227. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  118228. var system = _a[_i];
  118229. result.systems.push(system.serialize());
  118230. }
  118231. if (this._emitterNode) {
  118232. result.emitter = this._emitterCreationOptions;
  118233. }
  118234. return result;
  118235. };
  118236. /**
  118237. * Parse a new ParticleSystemSet from a serialized source
  118238. * @param data defines a JSON compatible representation of the set
  118239. * @param scene defines the hosting scene
  118240. * @param gpu defines if we want GPU particles or CPU particles
  118241. * @returns a new ParticleSystemSet
  118242. */
  118243. ParticleSystemSet.Parse = function (data, scene, gpu) {
  118244. if (gpu === void 0) { gpu = false; }
  118245. var result = new ParticleSystemSet();
  118246. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  118247. scene = scene || BABYLON.Engine.LastCreatedScene;
  118248. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  118249. var system = _a[_i];
  118250. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  118251. }
  118252. if (data.emitter) {
  118253. var options = data.emitter.options;
  118254. switch (data.emitter.kind) {
  118255. case "Sphere":
  118256. result.setEmitterAsSphere({
  118257. diameter: options.diameter,
  118258. segments: options.segments,
  118259. color: BABYLON.Color3.FromArray(options.color)
  118260. }, data.emitter.renderingGroupId, scene);
  118261. break;
  118262. }
  118263. }
  118264. return result;
  118265. };
  118266. return ParticleSystemSet;
  118267. }());
  118268. BABYLON.ParticleSystemSet = ParticleSystemSet;
  118269. })(BABYLON || (BABYLON = {}));
  118270. //# sourceMappingURL=particleSystemSet.js.map
  118271. var BABYLON;
  118272. (function (BABYLON) {
  118273. /**
  118274. * This class is made for on one-liner static method to help creating particle system set.
  118275. */
  118276. var ParticleHelper = /** @class */ (function () {
  118277. function ParticleHelper() {
  118278. }
  118279. /**
  118280. * Create a default particle system that you can tweak
  118281. * @param emitter defines the emitter to use
  118282. * @param capacity defines the system capacity (default is 500 particles)
  118283. * @param scene defines the hosting scene
  118284. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  118285. * @returns the new Particle system
  118286. */
  118287. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  118288. if (capacity === void 0) { capacity = 500; }
  118289. if (useGPU === void 0) { useGPU = false; }
  118290. var system;
  118291. if (useGPU) {
  118292. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  118293. }
  118294. else {
  118295. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  118296. }
  118297. system.emitter = emitter;
  118298. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  118299. system.createConeEmitter(0.1, Math.PI / 4);
  118300. // Particle color
  118301. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  118302. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  118303. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  118304. // Particle Size
  118305. system.minSize = 0.1;
  118306. system.maxSize = 0.1;
  118307. // Emission speed
  118308. system.minEmitPower = 2;
  118309. system.maxEmitPower = 2;
  118310. // Update speed
  118311. system.updateSpeed = 1 / 60;
  118312. system.emitRate = 30;
  118313. return system;
  118314. };
  118315. /**
  118316. * This is the main static method (one-liner) of this helper to create different particle systems
  118317. * @param type This string represents the type to the particle system to create
  118318. * @param scene The scene where the particle system should live
  118319. * @param gpu If the system will use gpu
  118320. * @returns the ParticleSystemSet created
  118321. */
  118322. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  118323. if (gpu === void 0) { gpu = false; }
  118324. if (!scene) {
  118325. scene = BABYLON.Engine.LastCreatedScene;
  118326. }
  118327. var token = {};
  118328. scene._addPendingData(token);
  118329. return new Promise(function (resolve, reject) {
  118330. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  118331. scene._removePendingData(token);
  118332. return reject("Particle system with GPU is not supported.");
  118333. }
  118334. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  118335. scene._removePendingData(token);
  118336. var newData = JSON.parse(data.toString());
  118337. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  118338. }, undefined, undefined, undefined, function (req, exception) {
  118339. scene._removePendingData(token);
  118340. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  118341. });
  118342. });
  118343. };
  118344. /**
  118345. * Static function used to export a particle system to a ParticleSystemSet variable.
  118346. * Please note that the emitter shape is not exported
  118347. * @param systems defines the particle systems to export
  118348. * @returns the created particle system set
  118349. */
  118350. ParticleHelper.ExportSet = function (systems) {
  118351. var set = new BABYLON.ParticleSystemSet();
  118352. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  118353. var system = systems_1[_i];
  118354. set.systems.push(system);
  118355. }
  118356. return set;
  118357. };
  118358. /**
  118359. * Gets or sets base Assets URL
  118360. */
  118361. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  118362. return ParticleHelper;
  118363. }());
  118364. BABYLON.ParticleHelper = ParticleHelper;
  118365. })(BABYLON || (BABYLON = {}));
  118366. //# sourceMappingURL=particleHelper.js.map
  118367. var BABYLON;
  118368. (function (BABYLON) {
  118369. /**
  118370. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  118371. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  118372. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  118373. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  118374. */
  118375. var VideoDome = /** @class */ (function (_super) {
  118376. __extends(VideoDome, _super);
  118377. /**
  118378. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  118379. * @param name Element's name, child elements will append suffixes for their own names.
  118380. * @param urlsOrVideo defines the url(s) or the video element to use
  118381. * @param options An object containing optional or exposed sub element properties
  118382. */
  118383. function VideoDome(name, urlsOrVideo, options, scene) {
  118384. var _this = _super.call(this, name, scene) || this;
  118385. _this._useDirectMapping = false;
  118386. // set defaults and manage values
  118387. name = name || "videoDome";
  118388. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  118389. options.clickToPlay = Boolean(options.clickToPlay);
  118390. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  118391. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  118392. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  118393. if (options.useDirectMapping === undefined) {
  118394. _this._useDirectMapping = true;
  118395. }
  118396. else {
  118397. _this._useDirectMapping = options.useDirectMapping;
  118398. }
  118399. _this._setReady(false);
  118400. // create
  118401. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  118402. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  118403. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  118404. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  118405. texture.onLoadObservable.addOnce(function () {
  118406. _this._setReady(true);
  118407. });
  118408. // configure material
  118409. material.useEquirectangularFOV = true;
  118410. material.fovMultiplier = 1.0;
  118411. material.opacityFresnel = false;
  118412. if (_this._useDirectMapping) {
  118413. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  118414. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  118415. material.diffuseTexture = texture;
  118416. }
  118417. else {
  118418. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  118419. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  118420. material.reflectionTexture = texture;
  118421. }
  118422. // configure mesh
  118423. _this._mesh.material = material;
  118424. _this._mesh.parent = _this;
  118425. // optional configuration
  118426. if (options.clickToPlay) {
  118427. scene.onPointerUp = function () {
  118428. _this._videoTexture.video.play();
  118429. };
  118430. }
  118431. return _this;
  118432. }
  118433. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  118434. /**
  118435. * Gets the video texture being displayed on the sphere
  118436. */
  118437. get: function () {
  118438. return this._videoTexture;
  118439. },
  118440. enumerable: true,
  118441. configurable: true
  118442. });
  118443. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  118444. /**
  118445. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  118446. * Also see the options.resolution property.
  118447. */
  118448. get: function () {
  118449. return this._material.fovMultiplier;
  118450. },
  118451. set: function (value) {
  118452. this._material.fovMultiplier = value;
  118453. },
  118454. enumerable: true,
  118455. configurable: true
  118456. });
  118457. /**
  118458. * Releases resources associated with this node.
  118459. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  118460. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  118461. */
  118462. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  118463. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  118464. this._videoTexture.dispose();
  118465. this._mesh.dispose();
  118466. this._material.dispose();
  118467. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  118468. };
  118469. return VideoDome;
  118470. }(BABYLON.TransformNode));
  118471. BABYLON.VideoDome = VideoDome;
  118472. })(BABYLON || (BABYLON = {}));
  118473. //# sourceMappingURL=videoDome.js.map
  118474. var BABYLON;
  118475. (function (BABYLON) {
  118476. /**
  118477. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  118478. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  118479. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  118480. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  118481. */
  118482. var PhotoDome = /** @class */ (function (_super) {
  118483. __extends(PhotoDome, _super);
  118484. /**
  118485. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  118486. * @param name Element's name, child elements will append suffixes for their own names.
  118487. * @param urlsOfPhoto defines the url of the photo to display
  118488. * @param options defines an object containing optional or exposed sub element properties
  118489. * @param onError defines a callback called when an error occured while loading the texture
  118490. */
  118491. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  118492. if (onError === void 0) { onError = null; }
  118493. var _this = _super.call(this, name, scene) || this;
  118494. _this._useDirectMapping = false;
  118495. /**
  118496. * Observable raised when an error occured while loading the 360 image
  118497. */
  118498. _this.onLoadErrorObservable = new BABYLON.Observable();
  118499. // set defaults and manage values
  118500. name = name || "photoDome";
  118501. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  118502. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  118503. if (options.useDirectMapping === undefined) {
  118504. _this._useDirectMapping = true;
  118505. }
  118506. else {
  118507. _this._useDirectMapping = options.useDirectMapping;
  118508. }
  118509. _this._setReady(false);
  118510. // create
  118511. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  118512. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  118513. // configure material
  118514. material.opacityFresnel = false;
  118515. material.useEquirectangularFOV = true;
  118516. material.fovMultiplier = 1.0;
  118517. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  118518. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  118519. if (onError) {
  118520. onError(message, exception);
  118521. }
  118522. });
  118523. _this.photoTexture.onLoadObservable.addOnce(function () {
  118524. _this._setReady(true);
  118525. });
  118526. // configure mesh
  118527. _this._mesh.material = material;
  118528. _this._mesh.parent = _this;
  118529. return _this;
  118530. }
  118531. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  118532. /**
  118533. * Gets or sets the texture being displayed on the sphere
  118534. */
  118535. get: function () {
  118536. return this._photoTexture;
  118537. },
  118538. set: function (value) {
  118539. if (this._photoTexture === value) {
  118540. return;
  118541. }
  118542. this._photoTexture = value;
  118543. if (this._useDirectMapping) {
  118544. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  118545. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  118546. this._material.diffuseTexture = this._photoTexture;
  118547. }
  118548. else {
  118549. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  118550. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  118551. this._material.reflectionTexture = this._photoTexture;
  118552. }
  118553. },
  118554. enumerable: true,
  118555. configurable: true
  118556. });
  118557. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  118558. /**
  118559. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  118560. * Also see the options.resolution property.
  118561. */
  118562. get: function () {
  118563. return this._material.fovMultiplier;
  118564. },
  118565. set: function (value) {
  118566. this._material.fovMultiplier = value;
  118567. },
  118568. enumerable: true,
  118569. configurable: true
  118570. });
  118571. /**
  118572. * Releases resources associated with this node.
  118573. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  118574. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  118575. */
  118576. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  118577. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  118578. this._photoTexture.dispose();
  118579. this._mesh.dispose();
  118580. this._material.dispose();
  118581. this.onLoadErrorObservable.clear();
  118582. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  118583. };
  118584. return PhotoDome;
  118585. }(BABYLON.TransformNode));
  118586. BABYLON.PhotoDome = PhotoDome;
  118587. })(BABYLON || (BABYLON = {}));
  118588. //# sourceMappingURL=photoDome.js.map
  118589. var BABYLON;
  118590. (function (BABYLON) {
  118591. /** @hidden */
  118592. var _OcclusionDataStorage = /** @class */ (function () {
  118593. function _OcclusionDataStorage() {
  118594. /** @hidden */
  118595. this.occlusionInternalRetryCounter = 0;
  118596. /** @hidden */
  118597. this.isOcclusionQueryInProgress = false;
  118598. /** @hidden */
  118599. this.isOccluded = false;
  118600. /** @hidden */
  118601. this.occlusionRetryCount = -1;
  118602. /** @hidden */
  118603. this.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE;
  118604. /** @hidden */
  118605. this.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  118606. }
  118607. return _OcclusionDataStorage;
  118608. }());
  118609. BABYLON.Engine.prototype.createQuery = function () {
  118610. return this._gl.createQuery();
  118611. };
  118612. BABYLON.Engine.prototype.deleteQuery = function (query) {
  118613. this._gl.deleteQuery(query);
  118614. return this;
  118615. };
  118616. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  118617. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  118618. };
  118619. BABYLON.Engine.prototype.getQueryResult = function (query) {
  118620. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  118621. };
  118622. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  118623. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  118624. this._gl.beginQuery(glAlgorithm, query);
  118625. return this;
  118626. };
  118627. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  118628. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  118629. this._gl.endQuery(glAlgorithm);
  118630. return this;
  118631. };
  118632. BABYLON.Engine.prototype._createTimeQuery = function () {
  118633. var timerQuery = this.getCaps().timerQuery;
  118634. if (timerQuery.createQueryEXT) {
  118635. return timerQuery.createQueryEXT();
  118636. }
  118637. return this.createQuery();
  118638. };
  118639. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  118640. var timerQuery = this.getCaps().timerQuery;
  118641. if (timerQuery.deleteQueryEXT) {
  118642. timerQuery.deleteQueryEXT(query);
  118643. return;
  118644. }
  118645. this.deleteQuery(query);
  118646. };
  118647. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  118648. var timerQuery = this.getCaps().timerQuery;
  118649. if (timerQuery.getQueryObjectEXT) {
  118650. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  118651. }
  118652. return this.getQueryResult(query);
  118653. };
  118654. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  118655. var timerQuery = this.getCaps().timerQuery;
  118656. if (timerQuery.getQueryObjectEXT) {
  118657. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  118658. }
  118659. return this.isQueryResultAvailable(query);
  118660. };
  118661. BABYLON.Engine.prototype.startTimeQuery = function () {
  118662. var caps = this.getCaps();
  118663. var timerQuery = caps.timerQuery;
  118664. if (!timerQuery) {
  118665. return null;
  118666. }
  118667. var token = new BABYLON._TimeToken();
  118668. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  118669. if (caps.canUseTimestampForTimerQuery) {
  118670. token._startTimeQuery = this._createTimeQuery();
  118671. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  118672. }
  118673. else {
  118674. if (this._currentNonTimestampToken) {
  118675. return this._currentNonTimestampToken;
  118676. }
  118677. token._timeElapsedQuery = this._createTimeQuery();
  118678. if (timerQuery.beginQueryEXT) {
  118679. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  118680. }
  118681. else {
  118682. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  118683. }
  118684. this._currentNonTimestampToken = token;
  118685. }
  118686. return token;
  118687. };
  118688. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  118689. var caps = this.getCaps();
  118690. var timerQuery = caps.timerQuery;
  118691. if (!timerQuery || !token) {
  118692. return -1;
  118693. }
  118694. if (caps.canUseTimestampForTimerQuery) {
  118695. if (!token._startTimeQuery) {
  118696. return -1;
  118697. }
  118698. if (!token._endTimeQuery) {
  118699. token._endTimeQuery = this._createTimeQuery();
  118700. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  118701. }
  118702. }
  118703. else if (!token._timeElapsedQueryEnded) {
  118704. if (!token._timeElapsedQuery) {
  118705. return -1;
  118706. }
  118707. if (timerQuery.endQueryEXT) {
  118708. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  118709. }
  118710. else {
  118711. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  118712. }
  118713. token._timeElapsedQueryEnded = true;
  118714. }
  118715. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  118716. var available = false;
  118717. if (token._endTimeQuery) {
  118718. available = this._getTimeQueryAvailability(token._endTimeQuery);
  118719. }
  118720. else if (token._timeElapsedQuery) {
  118721. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  118722. }
  118723. if (available && !disjoint) {
  118724. var result = 0;
  118725. if (caps.canUseTimestampForTimerQuery) {
  118726. if (!token._startTimeQuery || !token._endTimeQuery) {
  118727. return -1;
  118728. }
  118729. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  118730. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  118731. result = timeEnd - timeStart;
  118732. this._deleteTimeQuery(token._startTimeQuery);
  118733. this._deleteTimeQuery(token._endTimeQuery);
  118734. token._startTimeQuery = null;
  118735. token._endTimeQuery = null;
  118736. }
  118737. else {
  118738. if (!token._timeElapsedQuery) {
  118739. return -1;
  118740. }
  118741. result = this._getTimeQueryResult(token._timeElapsedQuery);
  118742. this._deleteTimeQuery(token._timeElapsedQuery);
  118743. token._timeElapsedQuery = null;
  118744. token._timeElapsedQueryEnded = false;
  118745. this._currentNonTimestampToken = null;
  118746. }
  118747. return result;
  118748. }
  118749. return -1;
  118750. };
  118751. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  118752. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  118753. };
  118754. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  118755. get: function () {
  118756. return this._occlusionDataStorage.isOcclusionQueryInProgress;
  118757. },
  118758. enumerable: false,
  118759. configurable: true
  118760. });
  118761. Object.defineProperty(BABYLON.AbstractMesh.prototype, "_occlusionDataStorage", {
  118762. get: function () {
  118763. if (!this.__occlusionDataStorage) {
  118764. this.__occlusionDataStorage = new _OcclusionDataStorage();
  118765. }
  118766. return this.__occlusionDataStorage;
  118767. },
  118768. enumerable: false,
  118769. configurable: true
  118770. });
  118771. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOccluded", {
  118772. get: function () {
  118773. return this._occlusionDataStorage.isOccluded;
  118774. },
  118775. set: function (value) {
  118776. this._occlusionDataStorage.isOccluded = value;
  118777. },
  118778. enumerable: true,
  118779. configurable: true
  118780. });
  118781. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
  118782. get: function () {
  118783. return this._occlusionDataStorage.occlusionQueryAlgorithmType;
  118784. },
  118785. set: function (value) {
  118786. this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
  118787. },
  118788. enumerable: true,
  118789. configurable: true
  118790. });
  118791. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionType", {
  118792. get: function () {
  118793. return this._occlusionDataStorage.occlusionType;
  118794. },
  118795. set: function (value) {
  118796. this._occlusionDataStorage.occlusionType = value;
  118797. },
  118798. enumerable: true,
  118799. configurable: true
  118800. });
  118801. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionRetryCount", {
  118802. get: function () {
  118803. return this._occlusionDataStorage.occlusionRetryCount;
  118804. },
  118805. set: function (value) {
  118806. this._occlusionDataStorage.occlusionRetryCount = value;
  118807. },
  118808. enumerable: true,
  118809. configurable: true
  118810. });
  118811. // We also need to update AbstractMesh as there is a portion of the code there
  118812. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  118813. var dataStorage = this._occlusionDataStorage;
  118814. if (dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  118815. dataStorage.isOccluded = false;
  118816. return false;
  118817. }
  118818. var engine = this.getEngine();
  118819. if (engine.webGLVersion < 2) {
  118820. dataStorage.isOccluded = false;
  118821. return false;
  118822. }
  118823. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  118824. dataStorage.isOccluded = false;
  118825. return false;
  118826. }
  118827. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  118828. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  118829. if (isOcclusionQueryAvailable) {
  118830. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  118831. dataStorage.isOcclusionQueryInProgress = false;
  118832. dataStorage.occlusionInternalRetryCounter = 0;
  118833. dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true;
  118834. }
  118835. else {
  118836. dataStorage.occlusionInternalRetryCounter++;
  118837. if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
  118838. dataStorage.isOcclusionQueryInProgress = false;
  118839. dataStorage.occlusionInternalRetryCounter = 0;
  118840. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  118841. // if strict continue the last state of the object.
  118842. dataStorage.isOccluded = dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
  118843. }
  118844. else {
  118845. return false;
  118846. }
  118847. }
  118848. }
  118849. var scene = this.getScene();
  118850. if (scene.getBoundingBoxRenderer) {
  118851. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  118852. if (!this._occlusionQuery) {
  118853. this._occlusionQuery = engine.createQuery();
  118854. }
  118855. engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery);
  118856. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  118857. engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
  118858. this._occlusionDataStorage.isOcclusionQueryInProgress = true;
  118859. }
  118860. return dataStorage.isOccluded;
  118861. };
  118862. })(BABYLON || (BABYLON = {}));
  118863. //# sourceMappingURL=engine.occlusionQuery.js.map
  118864. var BABYLON;
  118865. (function (BABYLON) {
  118866. /**
  118867. * Class used to generate noise procedural textures
  118868. */
  118869. var NoiseProceduralTexture = /** @class */ (function (_super) {
  118870. __extends(NoiseProceduralTexture, _super);
  118871. /**
  118872. * Creates a new NoiseProceduralTexture
  118873. * @param name defines the name fo the texture
  118874. * @param size defines the size of the texture (default is 256)
  118875. * @param scene defines the hosting scene
  118876. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  118877. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  118878. */
  118879. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  118880. if (size === void 0) { size = 256; }
  118881. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  118882. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  118883. _this._time = 0;
  118884. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  118885. _this.brightness = 0.2;
  118886. /** Defines the number of octaves to process */
  118887. _this.octaves = 3;
  118888. /** Defines the level of persistence (0.8 by default) */
  118889. _this.persistence = 0.8;
  118890. /** Gets or sets animation speed factor (default is 1) */
  118891. _this.animationSpeedFactor = 1;
  118892. _this.autoClear = false;
  118893. _this._updateShaderUniforms();
  118894. return _this;
  118895. }
  118896. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  118897. var scene = this.getScene();
  118898. if (!scene) {
  118899. return;
  118900. }
  118901. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  118902. this.setFloat("brightness", this.brightness);
  118903. this.setFloat("persistence", this.persistence);
  118904. this.setFloat("timeScale", this._time);
  118905. };
  118906. NoiseProceduralTexture.prototype._getDefines = function () {
  118907. return "#define OCTAVES " + (this.octaves | 0);
  118908. };
  118909. /** Generate the current state of the procedural texture */
  118910. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  118911. this._updateShaderUniforms();
  118912. _super.prototype.render.call(this, useCameraPostProcess);
  118913. };
  118914. /**
  118915. * Serializes this noise procedural texture
  118916. * @returns a serialized noise procedural texture object
  118917. */
  118918. NoiseProceduralTexture.prototype.serialize = function () {
  118919. var serializationObject = {};
  118920. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  118921. serializationObject.brightness = this.brightness;
  118922. serializationObject.octaves = this.octaves;
  118923. serializationObject.persistence = this.persistence;
  118924. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  118925. serializationObject.size = this.getSize().width;
  118926. serializationObject.generateMipMaps = this._generateMipMaps;
  118927. return serializationObject;
  118928. };
  118929. /**
  118930. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  118931. * @param parsedTexture defines parsed texture data
  118932. * @param scene defines the current scene
  118933. * @param rootUrl defines the root URL containing noise procedural texture information
  118934. * @returns a parsed NoiseProceduralTexture
  118935. */
  118936. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  118937. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  118938. texture.brightness = parsedTexture.brightness;
  118939. texture.octaves = parsedTexture.octaves;
  118940. texture.persistence = parsedTexture.persistence;
  118941. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  118942. return texture;
  118943. };
  118944. return NoiseProceduralTexture;
  118945. }(BABYLON.ProceduralTexture));
  118946. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  118947. })(BABYLON || (BABYLON = {}));
  118948. //# sourceMappingURL=noiseProceduralTexture.js.map
  118949. var __assign = (this && this.__assign) || function () {
  118950. __assign = Object.assign || function(t) {
  118951. for (var s, i = 1, n = arguments.length; i < n; i++) {
  118952. s = arguments[i];
  118953. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  118954. t[p] = s[p];
  118955. }
  118956. return t;
  118957. };
  118958. return __assign.apply(this, arguments);
  118959. };
  118960. var BABYLON;
  118961. (function (BABYLON) {
  118962. /**
  118963. * This can helps recording videos from BabylonJS.
  118964. * This is based on the available WebRTC functionalities of the browser.
  118965. *
  118966. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  118967. */
  118968. var VideoRecorder = /** @class */ (function () {
  118969. /**
  118970. * Create a new VideoCapture object which can help converting what you see in Babylon to
  118971. * a video file.
  118972. * @param engine Defines the BabylonJS Engine you wish to record
  118973. * @param options Defines options that can be used to customized the capture
  118974. */
  118975. function VideoRecorder(engine, options) {
  118976. if (options === void 0) { options = null; }
  118977. if (!VideoRecorder.IsSupported(engine)) {
  118978. throw "Your browser does not support recording so far.";
  118979. }
  118980. var canvas = engine.getRenderingCanvas();
  118981. if (!canvas) {
  118982. throw "The babylon engine must have a canvas to be recorded";
  118983. }
  118984. this._canvas = canvas;
  118985. this._canvas.isRecording = false;
  118986. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  118987. var stream = this._canvas.captureStream(this._options.fps);
  118988. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  118989. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  118990. this._mediaRecorder.onerror = this._handleError.bind(this);
  118991. this._mediaRecorder.onstop = this._handleStop.bind(this);
  118992. }
  118993. /**
  118994. * Returns wehther or not the VideoRecorder is available in your browser.
  118995. * @param engine Defines the Babylon Engine to check the support for
  118996. * @returns true if supported otherwise false
  118997. */
  118998. VideoRecorder.IsSupported = function (engine) {
  118999. var canvas = engine.getRenderingCanvas();
  119000. return (!!canvas && typeof canvas.captureStream === "function");
  119001. };
  119002. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  119003. /**
  119004. * True wether a recording is already in progress.
  119005. */
  119006. get: function () {
  119007. return !!this._canvas && this._canvas.isRecording;
  119008. },
  119009. enumerable: true,
  119010. configurable: true
  119011. });
  119012. /**
  119013. * Stops the current recording before the default capture timeout passed in the startRecording
  119014. * functions.
  119015. */
  119016. VideoRecorder.prototype.stopRecording = function () {
  119017. if (!this._canvas || !this._mediaRecorder) {
  119018. return;
  119019. }
  119020. if (!this.isRecording) {
  119021. return;
  119022. }
  119023. this._canvas.isRecording = false;
  119024. this._mediaRecorder.stop();
  119025. };
  119026. /**
  119027. * Starts recording the canvas for a max duration specified in parameters.
  119028. * @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.
  119029. * @param maxDuration Defines the maximum recording time in seconds.
  119030. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  119031. * @return a promise callback at the end of the recording with the video data in Blob.
  119032. */
  119033. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  119034. var _this = this;
  119035. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  119036. if (maxDuration === void 0) { maxDuration = 7; }
  119037. if (!this._canvas || !this._mediaRecorder) {
  119038. throw "Recorder has already been disposed";
  119039. }
  119040. if (this.isRecording) {
  119041. throw "Recording already in progress";
  119042. }
  119043. if (maxDuration > 0) {
  119044. setTimeout(function () {
  119045. _this.stopRecording();
  119046. }, maxDuration * 1000);
  119047. }
  119048. this._fileName = fileName;
  119049. this._recordedChunks = [];
  119050. this._resolve = null;
  119051. this._reject = null;
  119052. this._canvas.isRecording = true;
  119053. this._mediaRecorder.start(this._options.recordChunckSize);
  119054. return new Promise(function (resolve, reject) {
  119055. _this._resolve = resolve;
  119056. _this._reject = reject;
  119057. });
  119058. };
  119059. /**
  119060. * Releases internal resources used during the recording.
  119061. */
  119062. VideoRecorder.prototype.dispose = function () {
  119063. this._canvas = null;
  119064. this._mediaRecorder = null;
  119065. this._recordedChunks = [];
  119066. this._fileName = null;
  119067. this._resolve = null;
  119068. this._reject = null;
  119069. };
  119070. VideoRecorder.prototype._handleDataAvailable = function (event) {
  119071. if (event.data.size > 0) {
  119072. this._recordedChunks.push(event.data);
  119073. }
  119074. };
  119075. VideoRecorder.prototype._handleError = function (event) {
  119076. this.stopRecording();
  119077. if (this._reject) {
  119078. this._reject(event.error);
  119079. }
  119080. else {
  119081. throw new event.error();
  119082. }
  119083. };
  119084. VideoRecorder.prototype._handleStop = function () {
  119085. this.stopRecording();
  119086. var superBuffer = new Blob(this._recordedChunks);
  119087. if (this._resolve) {
  119088. this._resolve(superBuffer);
  119089. }
  119090. window.URL.createObjectURL(superBuffer);
  119091. if (this._fileName) {
  119092. BABYLON.Tools.Download(superBuffer, this._fileName);
  119093. }
  119094. };
  119095. VideoRecorder._defaultOptions = {
  119096. mimeType: "video/webm",
  119097. fps: 25,
  119098. recordChunckSize: 3000
  119099. };
  119100. return VideoRecorder;
  119101. }());
  119102. BABYLON.VideoRecorder = VideoRecorder;
  119103. })(BABYLON || (BABYLON = {}));
  119104. //# sourceMappingURL=videoRecorder.js.map
  119105. var BABYLON;
  119106. (function (BABYLON) {
  119107. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  119108. if (replace === void 0) { replace = false; }
  119109. // Dispose existing light in replace mode.
  119110. if (replace) {
  119111. if (this.lights) {
  119112. for (var i = 0; i < this.lights.length; i++) {
  119113. this.lights[i].dispose();
  119114. }
  119115. }
  119116. }
  119117. // Light
  119118. if (this.lights.length === 0) {
  119119. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  119120. }
  119121. };
  119122. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  119123. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  119124. if (replace === void 0) { replace = false; }
  119125. if (attachCameraControls === void 0) { attachCameraControls = false; }
  119126. // Dispose existing camera in replace mode.
  119127. if (replace) {
  119128. if (this.activeCamera) {
  119129. this.activeCamera.dispose();
  119130. this.activeCamera = null;
  119131. }
  119132. }
  119133. // Camera
  119134. if (!this.activeCamera) {
  119135. var worldExtends = this.getWorldExtends();
  119136. var worldSize = worldExtends.max.subtract(worldExtends.min);
  119137. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  119138. var camera;
  119139. var radius = worldSize.length() * 1.5;
  119140. // empty scene scenario!
  119141. if (!isFinite(radius)) {
  119142. radius = 1;
  119143. worldCenter.copyFromFloats(0, 0, 0);
  119144. }
  119145. if (createArcRotateCamera) {
  119146. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  119147. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  119148. arcRotateCamera.wheelPrecision = 100 / radius;
  119149. camera = arcRotateCamera;
  119150. }
  119151. else {
  119152. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  119153. freeCamera.setTarget(worldCenter);
  119154. camera = freeCamera;
  119155. }
  119156. camera.minZ = radius * 0.01;
  119157. camera.maxZ = radius * 1000;
  119158. camera.speed = radius * 0.2;
  119159. this.activeCamera = camera;
  119160. var canvas = this.getEngine().getRenderingCanvas();
  119161. if (attachCameraControls && canvas) {
  119162. camera.attachControl(canvas);
  119163. }
  119164. }
  119165. };
  119166. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  119167. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  119168. if (replace === void 0) { replace = false; }
  119169. if (attachCameraControls === void 0) { attachCameraControls = false; }
  119170. this.createDefaultLight(replace);
  119171. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  119172. };
  119173. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  119174. if (pbr === void 0) { pbr = false; }
  119175. if (scale === void 0) { scale = 1000; }
  119176. if (blur === void 0) { blur = 0; }
  119177. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  119178. if (!environmentTexture) {
  119179. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  119180. return null;
  119181. }
  119182. if (setGlobalEnvTexture) {
  119183. if (environmentTexture) {
  119184. this.environmentTexture = environmentTexture;
  119185. }
  119186. }
  119187. // Skybox
  119188. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  119189. if (pbr) {
  119190. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  119191. hdrSkyboxMaterial.backFaceCulling = false;
  119192. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  119193. if (hdrSkyboxMaterial.reflectionTexture) {
  119194. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  119195. }
  119196. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  119197. hdrSkyboxMaterial.disableLighting = true;
  119198. hdrSkyboxMaterial.twoSidedLighting = true;
  119199. hdrSkybox.infiniteDistance = true;
  119200. hdrSkybox.material = hdrSkyboxMaterial;
  119201. }
  119202. else {
  119203. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  119204. skyboxMaterial.backFaceCulling = false;
  119205. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  119206. if (skyboxMaterial.reflectionTexture) {
  119207. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  119208. }
  119209. skyboxMaterial.disableLighting = true;
  119210. hdrSkybox.infiniteDistance = true;
  119211. hdrSkybox.material = skyboxMaterial;
  119212. }
  119213. return hdrSkybox;
  119214. };
  119215. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  119216. if (BABYLON.EnvironmentHelper) {
  119217. return new BABYLON.EnvironmentHelper(options, this);
  119218. }
  119219. return null;
  119220. };
  119221. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  119222. if (webVROptions === void 0) { webVROptions = {}; }
  119223. return new BABYLON.VRExperienceHelper(this, webVROptions);
  119224. };
  119225. BABYLON.Scene.prototype.createDefaultXRExperienceAsync = function () {
  119226. var _this = this;
  119227. return BABYLON.WebXRExperienceHelper.CreateAsync(this).then(function (helper) {
  119228. var outputCanvas = new BABYLON.WebXRManagedOutputCanvas(helper);
  119229. return BABYLON.WebXREnterExitUI.CreateAsync(_this, helper, { outputCanvasContext: outputCanvas.canvasContext })
  119230. .then(function (ui) {
  119231. new BABYLON.WebXRInput(helper);
  119232. return helper;
  119233. });
  119234. });
  119235. };
  119236. })(BABYLON || (BABYLON = {}));
  119237. //# sourceMappingURL=sceneHelpers.js.map
  119238. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction; \n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\n\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nin vec3 direction;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \nvec4 textureColor=texture(textureSampler,vUV);\noutFragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\noutFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); \n#endif \n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\nin vec3 noiseCoordinates2;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\nout vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nfloat newAge=age+timeDelta; \n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(direction,0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#endif \nfloat ratio=clamp(mod(offsetAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef VELOCITY\nuniform mat4 previousWorldViewProjection;\nvarying vec4 vCurrentPosition;\nvarying vec4 vPreviousPosition;\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\n#ifdef VELOCITY\nvCurrentPosition=viewProjection*finalWorld*vec4(position,1.0);\nvPreviousPosition=previousWorldViewProjection*vec4(position,1.0);\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 VELOCITY\nvarying vec4 vCurrentPosition;\nvarying vec4 vPreviousPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<mrtFragmentDeclaration>[RENDER_TARGET_COUNT]\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[POSITION_INDEX]=vec4(vPosition,1.0);\n#endif\n#ifdef VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;\nvec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;\nvec2 velocity=(a-b)*0.5+0.5;\nvelocity*=0.5+0.5;\nvelocity=vec2(pow(velocity.x,3.0),pow(velocity.y,3.0));\ngl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,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}","motionBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D velocitySampler;\nuniform float motionStrength;\nuniform float motionScale;\nuniform vec2 screenSize;\nvoid main(void)\n{\n#ifdef GEOMETRY_SUPPORTED\nvec2 texelSize=1.0/screenSize;\nvec2 velocityColor=texture2D(velocitySampler,vUV).rg;\nvec2 velocity=vec2(pow(velocityColor.r,1.0/3.0),pow(velocityColor.g,1.0/3.0))*2.0-1.0;\nvelocity*=motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint samplesCount=int(clamp(speed,1.0,SAMPLES));\nvelocity=normalize(velocity)*texelSize;\nfloat hlim=float(-samplesCount)*0.5+0.5;\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(SAMPLES); ++i)\n{\nif (i>=samplesCount)\nbreak;\nvec2 offset=vUV+velocity*(hlim+float(i));\nresult+=texture2D(textureSampler,offset);\n}\ngl_FragColor=result/float(samplesCount);\n#else\ngl_FragColor=texture2D(textureSampler,vUV);\n#endif\n}\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"};
  119239. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\n#ifdef BONETEXTURE\nuniform sampler2D boneSampler;\nuniform float boneTextureWidth;\n#else\nuniform mat4 mBones[BonesPerMesh];\n#endif \nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#ifdef BONETEXTURE\nmat4 readMatrixFromRawSampler(sampler2D smp,float index)\n{\nfloat offset=index*4.0; \nfloat dx=1.0/boneTextureWidth;\nvec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));\nvec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));\nvec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));\nvec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));\nreturn mat4(m0,m1,m2,m3);\n}\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;\n#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3];\n#endif \n#else \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 \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\n#ifdef BONETEXTURE\nuniform sampler2D boneSampler;\n#else\nuniform mat4 mBones[BonesPerMesh];\n#endif \nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#ifdef BONETEXTURE\nmat4 readMatrixFromRawSampler(sampler2D smp,float index)\n{\nmat4 result;\nfloat offset=index*4.0; \nfloat dx=1.0/boneTextureWidth;\nresult[0]=texture(smp,vec2(dx*(offset+0.5),0.));\nresult[1]=texture(smp,vec2(dx*(offset+1.5),0.));\nresult[2]=texture(smp,vec2(dx*(offset+2.5),0.));\nresult[3]=texture(smp,vec2(dx*(offset+3.5),0.));\nreturn result;\n}\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};"};